<?php
session_start();
if (!isset($_SESSION['admin'])) {
  header("Location: login_admin.php");
  exit;
}

<?php
$host = "localhost";
$user = "odmr9632_userdb";
$pass = "@Sukabumi2018";
$db   = "odmr9632_order_db";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
  die("Koneksi gagal: " . $conn->connect_error);
}
?>
if ($conn->connect_error) {
  die("Koneksi gagal: " . $conn->connect_error);
}

$tgl1 = $_GET['tgl1'] ?? '';
$tgl2 = $_GET['tgl2'] ?? '';
$filter_cs = $_GET['cs'] ?? '';
$filter_produk = $_GET['produk'] ?? '';

$where = "WHERE 1=1";
if ($tgl1 && $tgl2) $where .= " AND tanggal BETWEEN '$tgl1' AND '$tgl2'";
if ($filter_cs) $where .= " AND nama_cs='$filter_cs'";
if ($filter_produk) $where .= " AND nama_produk='$filter_produk'";

$orders = $conn->query("SELECT * FROM orders $where");
$cs_list = $conn->query("SELECT DISTINCT nama_cs FROM orders");
$produk_list = $conn->query("SELECT DISTINCT nama_produk FROM orders");

$setting = [];
$setting_result = $conn->query("SELECT * FROM cashback_setting");
while ($s = $setting_result->fetch_assoc()) {
  $prov = strtoupper(trim($s['provinsi']));
  $setting[$prov] = (int)$s['potongan'];
}

$profit_setting = [];
$profit_result = $conn->query("SELECT * FROM cs_profit_setting");
while ($p = $profit_result->fetch_assoc()) {
  $profit_setting[$p['nama_cs']] = [
    'cs' => (int)$p['persen_cs'],
    'odm' => (int)$p['persen_odm']
  ];
}

$profit_kotor = 0;
$profit_terkirim = 0;
$cashback = 0;
$total_cashback = 0;
$denda_return = 0;
$unprofit = 0;
$omset = 0;
$total_hpp = 0;
$total_biaya_iklan = 0;
$total_ppn = 0; // ✅ Ditambahkan
$per_produk_cs = [];
$per_produk_cs_bagi = [];

while ($row = $orders->fetch_assoc()) {
  $nama_produk = $conn->real_escape_string($row['nama_produk']);
  $qty = (int)$row['qty'];

  $hpp = 0;
  $get_hpp = $conn->query("SELECT hpp FROM produk_fisik WHERE nama_produk='$nama_produk'");
  if ($get_hpp && $get_hpp->num_rows > 0) {
    $hpp = (int)$get_hpp->fetch_assoc()['hpp'];
  } else {
    $get_hpp = $conn->query("SELECT hpp FROM produk_digital WHERE nama_produk='$nama_produk'");
    if ($get_hpp && $get_hpp->num_rows > 0) {
      $hpp = (int)$get_hpp->fetch_assoc()['hpp'];
    }
  }

  $total_hpp += $hpp * $qty;
  $iklan = $row['biaya_iklan'] ?? 0;
  $total_biaya_iklan += $iklan;
  $total_ppn += $row['ppn'] ?? 0; // ✅ Ditambahkan

  $profit = $row['harga_jual'] - ($hpp * $qty) - $iklan - ($row['ppn'] ?? 0);
  $profit_kotor += $profit;
  $omset += $row['harga_jual'];

  $prov = strtoupper(trim($row['provinsi']));
  $ongkir = (int)$row['ongkir'];
  $potongan = $setting[$prov] ?? round($ongkir * 0.4);
  $cash_value = $ongkir - $potongan;

  $total_cashback += $cash_value;

  if ($row['status_pengiriman'] === 'Terkirim') {
    $profit_terkirim += $profit;
    $cashback += $cash_value;
  } elseif ($row['status_pengiriman'] === 'Return') {
    $denda_return += $potongan;
    $unprofit += $profit;
  }

  $key = $row['nama_cs'] . ' - ' . $row['nama_produk'];
  if (!isset($per_produk_cs[$key])) $per_produk_cs[$key] = 0;
  $per_produk_cs[$key] += $profit;

  $cs_percent = $profit_setting[$row['nama_cs']]['cs'] ?? 50;
  $odm_percent = $profit_setting[$row['nama_cs']]['odm'] ?? 50;

  if (!isset($per_produk_cs_bagi[$key])) {
    $per_produk_cs_bagi[$key] = ['cs_profit' => 0, 'odm_profit' => 0];
  }

  $per_produk_cs_bagi[$key]['cs_profit'] += round($profit * $cs_percent / 100);
  $per_produk_cs_bagi[$key]['odm_profit'] += round($profit * $odm_percent / 100);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Laporan Laba</title>
  <style>
    body { font-family: Arial; padding: 30px; background: #f5f5f5; }
    .container { max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
    h2 { text-align: center; color: #f44336; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th, td { padding: 10px; border: 1px solid #ccc; text-align: center; }
    th { background: #f44336; color: white; }
    .filter-form select, .filter-form input { padding: 6px; margin: 5px; border-radius: 5px; border: 1px solid #ccc; }
    .btn-setting { display:inline-block; margin-top:20px; text-align:center; background:#f44336; color:white; padding:8px 16px; text-decoration:none; border-radius:6px; }
  </style>
</head>
<body>
<div class="container">
  <h2>📊 Laporan Laba</h2>

  <form method="GET" class="filter-form">
    <label>Tanggal:</label>
    <input type="date" name="tgl1" value="<?= $tgl1 ?>"> s/d
    <input type="date" name="tgl2" value="<?= $tgl2 ?>">
    <select name="cs">
      <option value="">-- Semua CS --</option>
      <?php while($cs = $cs_list->fetch_assoc()): ?>
        <option value="<?= $cs['nama_cs'] ?>" <?= $filter_cs == $cs['nama_cs'] ? 'selected' : '' ?>><?= $cs['nama_cs'] ?></option>
      <?php endwhile; ?>
    </select>
    <select name="produk">
      <option value="">-- Semua Produk --</option>
      <?php while($pr = $produk_list->fetch_assoc()): ?>
        <option value="<?= $pr['nama_produk'] ?>" <?= $filter_produk == $pr['nama_produk'] ? 'selected' : '' ?>><?= $pr['nama_produk'] ?></option>
      <?php endwhile; ?>
    </select>
    <button type="submit">🔍 Filter</button>
  </form>

  <a href="pengaturan_cashback.php" class="btn-setting">⚙️ Pengaturan Cashback</a>
  <a href="pengaturan_profit_cs.php" class="btn-setting">⚙️ Pengaturan Profit CS & ODM</a>

  <table>
    <tr><th>Kategori</th><th>Nilai</th></tr>
    <tr><td>Total Omset</td><td>Rp<?= number_format($omset) ?></td></tr>
    <tr><td>Total HPP</td><td>Rp<?= number_format($total_hpp) ?></td></tr>
    <tr><td>Total Biaya Iklan</td><td>Rp<?= number_format($total_biaya_iklan) ?></td></tr>
    <tr><td>Total PPN</td><td>Rp<?= number_format($total_ppn) ?></td></tr> <!-- ✅ Baris ditambahkan -->
    <tr><td>Profit Kotor</td><td>Rp<?= number_format($profit_kotor) ?></td></tr>
    <tr><td>Profit Terkirim</td><td>Rp<?= number_format($profit_terkirim) ?></td></tr>
    <tr><td>Total Cashback</td><td>Rp<?= number_format($total_cashback) ?></td></tr>
    <tr><td>Cashback Terkirim</td><td>Rp<?= number_format($cashback) ?></td></tr>
    <tr><td>Denda Return</td><td>Rp<?= number_format($denda_return) ?></td></tr>
    <tr><td>Unprofit</td><td>Rp<?= number_format($unprofit) ?></td></tr>
  </table>

  <h3>📈 Profit per CS & Produk</h3>
  <table>
    <tr><th>CS - Produk</th><th>Profit</th><th>Profit CS</th><th>Profit ODM</th></tr>
    <?php foreach ($per_produk_cs as $key => $val): ?>
      <tr>
        <td><?= $key ?></td>
        <td>Rp<?= number_format($val) ?></td>
        <td>Rp<?= number_format($per_produk_cs_bagi[$key]['cs_profit']) ?></td>
        <td>Rp<?= number_format($per_produk_cs_bagi[$key]['odm_profit']) ?></td>
      </tr>
    <?php endforeach; ?>
  </table>
</div>

<div style="text-align:center; margin-top: 40px;">
  <a href="menu_admin.php" style="padding: 10px 20px; background: gray; color: white; text-decoration: none; border-radius: 6px; margin-right: 10px;">⬅️ Kembali ke Menu Admin</a>
  <a href="index.php" style="padding: 10px 20px; background: #f44336; color: white; text-decoration: none; border-radius: 6px;">🏠 Kembali ke Menu Utama</a>
</div>
</body>
</html>
