<?php
session_start();
include 'koneksi.php';

$id_user = $_SESSION['id_user'] ?? 1;

// Filter tanggal
$tanggal_mulai = $_GET['tanggal_mulai'] ?? date('Y-m-01');
$tanggal_akhir = $_GET['tanggal_akhir'] ?? date('Y-m-d');

// Query untuk laporan penjualan dengan filter tanggal
$laporan_query = "
    SELECT p.*, sg.kode_pengepakan, sg.kelas_mutu, sg.mutu, sg.grade, sg.jenis_kemasan
    FROM penjualan p
    LEFT JOIN stok_gudang sg ON p.id_stok = sg.id_stok
    WHERE p.tanggal_jual BETWEEN ? AND ?
    ORDER BY p.tanggal_jual DESC
";

$laporan_stmt = $conn->prepare($laporan_query);
$laporan_stmt->bind_param("ss", $tanggal_mulai, $tanggal_akhir);
$laporan_stmt->execute();
$laporan_result = $laporan_stmt->get_result();

// Hitung total penjualan dalam periode
$total_periode_query = "
    SELECT 
        SUM(total_harga) as total_penjualan,
        SUM(quantity_kg) as total_quantity,
        COUNT(*) as jumlah_transaksi
    FROM penjualan 
    WHERE tanggal_jual BETWEEN ? AND ?
";

$total_periode_stmt = $conn->prepare($total_periode_query);
$total_periode_stmt->bind_param("ss", $tanggal_mulai, $tanggal_akhir);
$total_periode_stmt->execute();
$total_periode_result = $total_periode_stmt->get_result();
$total_periode = $total_periode_result->fetch_assoc();

// Laporan berdasarkan kelas mutu
$laporan_kelas_query = "
    SELECT 
        sg.kelas_mutu,
        sg.mutu,
        SUM(p.quantity_kg) as total_quantity,
        SUM(p.total_harga) as total_penjualan,
        COUNT(*) as jumlah_transaksi
    FROM penjualan p
    LEFT JOIN stok_gudang sg ON p.id_stok = sg.id_stok
    WHERE p.tanggal_jual BETWEEN ? AND ?
    GROUP BY sg.kelas_mutu, sg.mutu
    ORDER BY total_penjualan DESC
";

$laporan_kelas_stmt = $conn->prepare($laporan_kelas_query);
$laporan_kelas_stmt->bind_param("ss", $tanggal_mulai, $tanggal_akhir);
$laporan_kelas_stmt->execute();
$laporan_kelas_result = $laporan_kelas_stmt->get_result();

// Laporan berdasarkan status pembayaran
$laporan_status_query = "
    SELECT 
        status_pembayaran,
        SUM(total_harga) as total_penjualan,
        COUNT(*) as jumlah_transaksi
    FROM penjualan 
    WHERE tanggal_jual BETWEEN ? AND ?
    GROUP BY status_pembayaran
    ORDER BY total_penjualan DESC
";

$laporan_status_stmt = $conn->prepare($laporan_status_query);
$laporan_status_stmt->bind_param("ss", $tanggal_mulai, $tanggal_akhir);
$laporan_status_stmt->execute();
$laporan_status_result = $laporan_status_stmt->get_result();

// Data untuk chart
$chart_data_query = "
    SELECT 
        DATE(tanggal_jual) as tanggal,
        SUM(total_harga) as total_penjualan,
        SUM(quantity_kg) as total_quantity
    FROM penjualan 
    WHERE tanggal_jual BETWEEN ? AND ?
    GROUP BY DATE(tanggal_jual)
    ORDER BY tanggal_jual
";

$chart_data_stmt = $conn->prepare($chart_data_query);
$chart_data_stmt->bind_param("ss", $tanggal_mulai, $tanggal_akhir);
$chart_data_stmt->execute();
$chart_data_result = $chart_data_stmt->get_result();

$chart_labels = [];
$chart_penjualan = [];
$chart_quantity = [];

while ($row = $chart_data_result->fetch_assoc()) {
    $chart_labels[] = date('d/m/Y', strtotime($row['tanggal']));
    $chart_penjualan[] = (float) $row['total_penjualan'];
    $chart_quantity[] = (float) $row['total_quantity'];
}
?>

<!DOCTYPE html>
<html :class="{ 'theme-dark': dark }" x-data="data()" lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Laporan Penjualan</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="./assets/css/tailwind.output.css" />
    <style>
      @media print {
        aside, header, .no-print, .no-print * { display: none !important; }
        main { padding: 0 !important; }
        body { background: #fff !important; }
        #print-header { display:block !important; margin-bottom:16px; }
      }
      /* Default: kop tidak tampil di layar */
      #print-header { display:none; }
      .report { color:#000 !important; }
    </style>
    <script
      src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"
      defer
    ></script>
    <script src="./assets/js/init-alpine.js"></script>
    <script src="./assets/js/focus-trap.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  </head>
  <body>
    <div
      class="flex h-screen bg-gray-50 dark:bg-gray-900"
      :class="{ 'overflow-hidden': isSideMenuOpen}"
    >
      <!-- Desktop sidebar -->
      <?php
      $currentPage = basename($_SERVER['PHP_SELF']);
      include 'sidebar.php';
      ?>

<?php include 'header.php'; ?>
        <main class="h-full overflow-y-auto">
          <div class="container px-6 mx-auto grid report">
            <!-- Kop surat di paling atas -->
            <div id="print-header" class="flex items-center">
              <img src="assets/img/kop.png" alt="kop" style="max-width:100%; height:auto;" />
            </div>
            <h2 class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200">
              LAPORAN PENJUALAN
            </h2>

              <!-- Cards (hanya tampil di layar, disembunyikan saat cetak) -->
              <div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4 no-print">
              <!-- Total Penjualan -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Total Penjualan
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      Rp <?= number_format($total_periode['total_penjualan'] ?? 0, 0, ',', '.') ?>
                    </p>
                  </div>
                </div>
              </div>

              <!-- Total Quantity -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Total Quantity
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= number_format($total_periode['total_quantity'] ?? 0, 2) ?> kg
                    </p>
                  </div>
                </div>
              </div>

              <!-- Jumlah Transaksi -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6zM14 9a1 1 0 00-1 1v6a1 1 0 001 1h2a1 1 0 001-1v-6a1 1 0 00-1-1h-2z"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Jumlah Transaksi
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= $total_periode['jumlah_transaksi'] ?? 0 ?>
                    </p>
                  </div>
                </div>
              </div>

              <!-- Rata-rata per Transaksi -->
              <div class="min-w-0 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
                <div class="flex items-center">
                  <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
                    </svg>
                  </div>
                  <div>
                    <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                      Rata-rata/Transaksi
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?php 
                        $avg = ($total_periode['jumlah_transaksi'] > 0) ? 
                               $total_periode['total_penjualan'] / $total_periode['jumlah_transaksi'] : 0;
                        echo 'Rp ' . number_format($avg, 0, ',', '.');
                      ?>
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <!-- Filter -->
            <div class="w-full overflow-hidden rounded-lg shadow-xs mb-8 no-print">
              <div class="w-full overflow-x-auto">
                <div class="p-4 bg-white dark:bg-gray-800">
                  <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200 mb-4">Filter Periode</h3>
                  <form method="GET" action="" class="flex gap-6 items-end flex-wrap">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Tanggal Mulai
                      </label>
                      <input type="date" name="tanggal_mulai" value="<?= htmlspecialchars($_GET['tanggal_mulai'] ?? '') ?>" 
                             class="px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Tanggal Akhir
                      </label>
                      <input type="date" name="tanggal_akhir" value="<?= htmlspecialchars($_GET['tanggal_akhir'] ?? '') ?>" 
                             class="px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                    </div>
                    <div class="no-print flex items-center gap-2">
                      <button type="submit" 
                              class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500">
                        Filter
                      </button>
                      <a href="laporan_penjualan.php" class="px-4 py-2 text-sm font-medium bg-gray-100 rounded-md dark:bg-gray-700 dark:text-gray-200">Reset</a>
                    </div>
                    <div class="no-print">
                      <button type="button" onclick="window.print()"
                              class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        Cetak Laporan
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </div>
            
            <!-- Laporan berdasarkan Kelas Mutu -->
            <div class="w-full overflow-hidden rounded-lg shadow-xs mb-8">
              <div class="w-full overflow-x-auto">
                <table class="w-full whitespace-no-wrap">
                  <thead>
                    <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                      <th class="px-4 py-3">Kelas Mutu</th>
                      <th class="px-4 py-3">Mutu</th>
                      <th class="px-4 py-3">Total Quantity</th>
                      <th class="px-4 py-3">Total Penjualan</th>
                      <th class="px-4 py-3">Jumlah Transaksi</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                    <?php while ($row = $laporan_kelas_result->fetch_assoc()): ?>
                    <tr class="text-gray-700 dark:text-gray-300">
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['kelas_mutu']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['mutu']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= number_format($row['total_quantity'], 2) ?> kg
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <strong>Rp <?= number_format($row['total_penjualan'], 0, ',', '.') ?></strong>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= $row['jumlah_transaksi'] ?>
                      </td>
                    </tr>
                    <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Laporan berdasarkan Status Pembayaran -->
            <div class="w-full overflow-hidden rounded-lg shadow-xs mb-8">
              <div class="w-full overflow-x-auto">
                <table class="w-full whitespace-no-wrap">
                  <thead>
                    <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                      <th class="px-4 py-3">Status Pembayaran</th>
                      <th class="px-4 py-3">Total Penjualan</th>
                      <th class="px-4 py-3">Jumlah Transaksi</th>
                      <th class="px-4 py-3">Persentase</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                    <?php while ($row = $laporan_status_result->fetch_assoc()): ?>
                    <tr class="text-gray-700 dark:text-gray-300">
                      <td class="px-4 py-3 text-sm">
                        <?php if ($row['status_pembayaran'] == 'Lunas'): ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
                            Lunas
                          </span>
                        <?php elseif ($row['status_pembayaran'] == 'Belum Lunas'): ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">
                            Belum Lunas
                          </span>
                        <?php else: ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-yellow-700 bg-yellow-100 rounded-full dark:bg-yellow-700 dark:text-yellow-100">
                            Cicilan
                          </span>
                        <?php endif; ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <strong>Rp <?= number_format($row['total_penjualan'], 0, ',', '.') ?></strong>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= $row['jumlah_transaksi'] ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?php 
                          $persentase = ($total_periode['total_penjualan'] > 0) ? 
                                       ($row['total_penjualan'] / $total_periode['total_penjualan']) * 100 : 0;
                          echo number_format($persentase, 1) . '%';
                        ?>
                      </td>
                    </tr>
                    <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Detail Transaksi -->
            <div class="w-full overflow-hidden rounded-lg shadow-xs">
              <div class="w-full overflow-x-auto">
                <table class="w-full whitespace-no-wrap">
                  <thead>
                    <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                      <th class="px-4 py-3">No</th>
                      <th class="px-4 py-3">Kode Penjualan</th>
                      <th class="px-4 py-3">Tanggal</th>
                      <th class="px-4 py-3">Pembeli</th>
                      <th class="px-4 py-3">Produk</th>
                      <th class="px-4 py-3">Quantity</th>
                      <th class="px-4 py-3">Total</th>
                      <th class="px-4 py-3">Status</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                    <?php $no=1; while ($row = $laporan_result->fetch_assoc()): ?>
                    <tr class="text-gray-700 dark:text-gray-300">
                      <td class="px-4 py-3 text-sm"><?= $no++ ?></td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['kode_penjualan']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= date('d/m/Y', strtotime($row['tanggal_jual'])) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['nama_pembeli']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= htmlspecialchars($row['kelas_mutu']) ?> <?= htmlspecialchars($row['mutu']) ?>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?= number_format($row['quantity_kg'], 2) ?> kg
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <strong>Rp <?= number_format($row['total_harga'], 0, ',', '.') ?></strong>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <?php if ($row['status_pembayaran'] == 'Lunas'): ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
                            Lunas
                          </span>
                        <?php elseif ($row['status_pembayaran'] == 'Belum Lunas'): ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">
                            Belum Lunas
                          </span>
                        <?php else: ?>
                          <span class="px-2 py-1 font-semibold leading-tight text-yellow-700 bg-yellow-100 rounded-full dark:bg-yellow-700 dark:text-yellow-100">
                            Cicilan
                          </span>
                        <?php endif; ?>
                      </td>
                    </tr>
                    <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Charts (dipindah ke bawah tabel) -->
           
            </div>
          </div>
        </main>
      </div>
    </div>

  </body>
</html>
