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

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

// Proses hapus penjualan (rollback stok)
if (isset($_GET['action']) && $_GET['action'] == 'hapus' && isset($_GET['id'])) {
    $id_penjualan = $_GET['id'];
    
    // Ambil data penjualan
    $penjualan_query = "SELECT id_stok, quantity_kg FROM penjualan WHERE id_penjualan = ?";
    $penjualan_stmt = $conn->prepare($penjualan_query);
    $penjualan_stmt->bind_param("i", $id_penjualan);
    $penjualan_stmt->execute();
    $penjualan_result = $penjualan_stmt->get_result();
    $penjualan_data = $penjualan_result->fetch_assoc();
    
    if ($penjualan_data) {
        // Tambahkan kembali jumlah pack dan berat sesuai penjualan yang dihapus
        $PACK_WEIGHT = 50; // kg per pack
        $qty_kg = (float)$penjualan_data['quantity_kg'];
        $qty_pack = max(1, (int)round($qty_kg / $PACK_WEIGHT));

        $update_stok_query = "UPDATE stok_gudang 
                               SET jumlah_kemasan = jumlah_kemasan + ?,
                                   berat_paket = berat_paket + ?,
                                   status = 'Tersedia'
                               WHERE id_stok = ?";
        $update_stok_stmt = $conn->prepare($update_stok_query);
        $update_stok_stmt->bind_param("idi", $qty_pack, $qty_kg, $penjualan_data['id_stok']);
        $update_stok_stmt->execute();
        
        // Hapus data penjualan
        $delete_query = "DELETE FROM penjualan WHERE id_penjualan = ?";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bind_param("i", $id_penjualan);
        $delete_stmt->execute();
        
        echo "<script>alert('Data penjualan berhasil dihapus!'); window.location.href='data_penjualan.php';</script>";
    }
}

// Proses form tambah penjualan (berbasis pack 50kg)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'tambah_penjualan') {
    $id_stok = $_POST['id_stok'];
    $tanggal_jual = $_POST['tanggal_jual'];
    $nama_pembeli = $_POST['nama_pembeli'];
    $alamat_pembeli = $_POST['alamat_pembeli'];
    $telepon_pembeli = $_POST['telepon_pembeli'];
    $email_pembeli = $_POST['email_pembeli'];
    $harga_per_kg = $_POST['harga_per_kg'];
    $jumlah_pack = isset($_POST['jumlah_pack']) ? (int)$_POST['jumlah_pack'] : 0;
    $PACK_WEIGHT = 50; // kg per pack
    $quantity_kg = $jumlah_pack * $PACK_WEIGHT;
    $total_harga = $harga_per_kg * $quantity_kg;
    $metode_pembayaran = $_POST['metode_pembayaran'];
    $status_pembayaran = $_POST['status_pembayaran'];
    $keterangan = $_POST['keterangan'];

    // Upload bukti pembayaran (opsional)
    $bukti_path = '';
    if (isset($_FILES['bukti_pembayaran']) && $_FILES['bukti_pembayaran']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/uploads/bukti';
        if (!is_dir($uploadDir)) {
            @mkdir($uploadDir, 0777, true);
        }
        $originalName = $_FILES['bukti_pembayaran']['name'];
        $ext = pathinfo($originalName, PATHINFO_EXTENSION);
        $safeExt = preg_replace('/[^a-zA-Z0-9]/', '', $ext);
        $newName = 'bukti_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . ($safeExt ? ('.' . strtolower($safeExt)) : '');
        $destPath = $uploadDir . '/' . $newName;
        if (move_uploaded_file($_FILES['bukti_pembayaran']['tmp_name'], $destPath)) {
            $bukti_path = 'uploads/bukti/' . $newName; // path relatif dari public
            $keterangan = trim($keterangan . (strlen($keterangan) ? ' | ' : '') . 'Bukti: ' . $bukti_path);
        }
    }
    
    // Ambil data stok
    $stok_query = "SELECT * FROM stok_gudang WHERE id_stok = ?";
    $stok_stmt = $conn->prepare($stok_query);
    $stok_stmt->bind_param("i", $id_stok);
    $stok_stmt->execute();
    $stok_result = $stok_stmt->get_result();
    $stok_data = $stok_result->fetch_assoc();
    
    // Guard: stok harus ada dan tersedia
    if (!$stok_data) {
        echo "<script>alert('Stok tidak ditemukan atau sudah dihapus.'); window.location.href='data_penjualan.php';</script>";
        exit;
    }
    if ($stok_data['status'] !== 'Tersedia') {
        echo "<script>alert('Stok tidak tersedia untuk dijual.'); window.location.href='data_penjualan.php';</script>";
        exit;
    }

    if ($stok_data && $stok_data['status'] == 'Tersedia') {
        // Validasi stok cukup berdasarkan pack
        if ((int)$stok_data['jumlah_kemasan'] < $jumlah_pack || $jumlah_pack <= 0) {
            echo "<script>alert('Jumlah pack tidak mencukupi!'); window.location.href='data_penjualan.php';</script>";
            exit;
        }
        // Generate kode penjualan
        $kode_penjualan = 'PJ-' . date('Ymd') . '-' . rand(100, 999);
        
        // Insert ke tabel penjualan
        $insert_query = "INSERT INTO penjualan (kode_penjualan, id_stok, id_pengepakan, tanggal_jual, nama_pembeli, alamat_pembeli, telepon_pembeli, email_pembeli, harga_per_kg, quantity_kg, total_harga, metode_pembayaran, status_pembayaran, keterangan, id_user, name, jabatan) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insert_stmt = $conn->prepare($insert_query);
        
        // Ambil data user
        $user_query = "SELECT name, jabatan FROM users WHERE id_user = ?";
        $user_stmt = $conn->prepare($user_query);
        $user_stmt->bind_param("i", $id_user);
        $user_stmt->execute();
        $user_result = $user_stmt->get_result();
        $user_data = $user_result->fetch_assoc();
        
        $insert_stmt->bind_param("siisssssddsssssss", 
            $kode_penjualan,
            $id_stok,
            $stok_data['id_pengepakan'],
            $tanggal_jual,
            $nama_pembeli,
            $alamat_pembeli,
            $telepon_pembeli,
            $email_pembeli,
            $harga_per_kg,
            $quantity_kg,
            $total_harga,
            $metode_pembayaran,
            $status_pembayaran,
            $keterangan,
            $id_user,
            $user_data['name'],
            $user_data['jabatan']
        );
        
        if ($insert_stmt->execute()) {
            // Kurangi stok berdasarkan jumlah pack terjual
            $update_stok_query = "UPDATE stok_gudang 
                                   SET jumlah_kemasan = jumlah_kemasan - ?,
                                       berat_paket = berat_paket - ?,
                                       status = CASE WHEN (jumlah_kemasan - ?) <= 0 THEN 'Habis' ELSE 'Tersedia' END
                                   WHERE id_stok = ?";
            $update_stok_stmt = $conn->prepare($update_stok_query);
            $update_stok_stmt->bind_param("idii", $jumlah_pack, $quantity_kg, $jumlah_pack, $id_stok);
            $update_stok_stmt->execute();
            
            echo "<script>alert('Penjualan berhasil ditambahkan!'); window.location.href='data_penjualan.php';</script>";
        } else {
            echo "<script>alert('Gagal menambahkan penjualan!');</script>";
        }
    }
}

// Filters & pagination params
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$start_date = isset($_GET['tanggal_mulai']) ? $_GET['tanggal_mulai'] : (isset($_GET['start_date']) ? $_GET['start_date'] : '');
$end_date = isset($_GET['tanggal_akhir']) ? $_GET['tanggal_akhir'] : (isset($_GET['end_date']) ? $_GET['end_date'] : '');
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = max(5, intval($_GET['per_page'] ?? 10));
$offset = ($page - 1) * $per_page;

// Ambil data stok untuk form (hanya tersedia dan belum dihapus)
$stok_tersedia_query = "SELECT * FROM stok_gudang WHERE status = 'Tersedia' ORDER BY tanggal_masuk DESC";
$stok_tersedia_result = $conn->query($stok_tersedia_query);

// Build where for penjualan
$whereParts = [];
if ($q !== '') {
    $safeQ = '%' . $conn->real_escape_string($q) . '%';
    $whereParts[] = "(p.kode_penjualan LIKE '$safeQ' OR p.nama_pembeli LIKE '$safeQ' OR sg.kode_pengepakan LIKE '$safeQ' OR sg.kelas_mutu LIKE '$safeQ' OR sg.mutu LIKE '$safeQ' OR sg.grade LIKE '$safeQ')";
}
if ($start_date !== '' && $end_date !== '') {
    $startEsc = $conn->real_escape_string($start_date);
    $endEsc = $conn->real_escape_string($end_date);
    $whereParts[] = "(DATE(p.tanggal_jual) BETWEEN '$startEsc' AND '$endEsc')";
} elseif ($start_date !== '') {
    $startEsc = $conn->real_escape_string($start_date);
    $whereParts[] = "(DATE(p.tanggal_jual) >= '$startEsc')";
} elseif ($end_date !== '') {
    $endEsc = $conn->real_escape_string($end_date);
    $whereParts[] = "(DATE(p.tanggal_jual) <= '$endEsc')";
}
$whereSql = count($whereParts) ? ('WHERE ' . implode(' AND ', $whereParts)) : '';

// Hitung total untuk pagination
$count_sql = "SELECT COUNT(*) AS cnt FROM penjualan p LEFT JOIN stok_gudang sg ON p.id_stok = sg.id_stok $whereSql";
$count_res = $conn->query($count_sql);
$total_rows = $count_res ? intval(($count_res->fetch_assoc()['cnt'] ?? 0)) : 0;
$total_pages = max(1, (int)ceil($total_rows / $per_page));

// Ambil data penjualan dengan filter dan pagination
$penjualan_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
    $whereSql
    ORDER BY p.tanggal_jual DESC
    LIMIT $per_page OFFSET $offset
";
$penjualan_result = $conn->query($penjualan_query);

// Hitung total penjualan
$total_penjualan_query = "SELECT SUM(total_harga) as total FROM penjualan";
$total_penjualan_result = $conn->query($total_penjualan_query);
$total_penjualan = $total_penjualan_result->fetch_assoc()['total'] ?? 0;

// Hitung jumlah transaksi
$jumlah_transaksi_query = "SELECT COUNT(*) as total FROM penjualan";
$jumlah_transaksi_result = $conn->query($jumlah_transaksi_query);
$jumlah_transaksi = $jumlah_transaksi_result->fetch_assoc()['total'] ?? 0;
?>

<!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>Data 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" />
    <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>
  </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">
            <h2 class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200">
              Data 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_penjualan, 0, ',', '.') ?>
                    </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-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">
                      Jumlah Transaksi
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= $jumlah_transaksi ?>
                    </p>
                  </div>
                </div>
              </div>

              <!-- Stok Tersedia -->
              <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">
                      Stok Tersedia
                    </p>
                    <p class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                      <?= $stok_tersedia_result->num_rows ?> item
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Filters + Button + Modal Tambah Penjualan -->
            <div class="" x-data="{ openAdd:false }">
              <div class="mb-6 grid gap-6 md:grid-cols-2 md:gap-8">
                <!-- Search only -->
                <form method="GET" action="data_penjualan.php" class="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-md shadow">
                  <input type="hidden" name="page" value="1" />
                  <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Cari kode/nama/kode pengepakan..."
                         class="flex-1 min-w-[220px] px-3 py-2 text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" />
                  <button type="submit" class="px-3 py-2 text-sm text-white bg-blue-600 rounded-md">Cari</button>
                </form>

                <!-- Date filter only (no defaults) -->
                <form method="GET" action="data_penjualan.php" class="flex items-center gap-4 p-4 bg-white dark:bg-gray-800 rounded-md shadow">
                  <input type="date" name="tanggal_mulai" value="<?= htmlspecialchars($start_date) ?>"
                         class="px-3 py-2 text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" />
                  <span class="text-sm text-gray-500 dark:text-gray-400">s/d</span>
                  <input type="date" name="tanggal_akhir" value="<?= htmlspecialchars($end_date) ?>"
                         class="px-3 py-2 text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200" />
                  <button type="submit" class="ml-auto px-3 py-2 text-sm text-white bg-purple-600 rounded-md">Filter Tanggal</button>
                  <a href="data_penjualan.php" class="px-3 py-2 text-sm bg-gray-100 rounded-md dark:bg-gray-700 dark:text-gray-200">Reset</a>
                </form>
              </div>
              <div class="mb-6">
                <div class="flex items-center justify-between">
                 
                  <button @click="openAdd=true" 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">Tambah Penjualan</button>
                </div>
              </div>

              <!-- Modal -->
              <div x-show="openAdd"
                   class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto"
                   x-transition:enter="transition ease-out duration-300"
                   x-transition:enter-start="opacity-0"
                   x-transition:enter-end="opacity-100"
                   x-transition:leave="transition ease-in duration-200"
                   x-transition:leave-start="opacity-100"
                   x-transition:leave-end="opacity-0">
                <!-- Modal Box -->
                <div class="bg-white dark:bg-gray-800 p-6 rounded-xl w-full max-w-4xl mx-4 overflow-y-auto max-h-[90vh]">
                  <h2 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Tambah Data Penjualan</h2>
                  <form method="POST" action="" enctype="multipart/form-data" class="space-y-6">
                    <input type="hidden" name="action" value="tambah_penjualan">
                    
                    <div class="grid gap-6 md:grid-cols-2">
                      <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          Pilih Stok
                        </label>
                        <select name="id_stok" required class="w-full 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">
                          <option value="">Pilih stok...</option>
                          <?php $stok_tersedia_result->data_seek(0); while ($stok = $stok_tersedia_result->fetch_assoc()): ?>
                            <option value="<?= $stok['id_stok'] ?>">
                              <?= $stok['kode_pengepakan'] ?> - <?= $stok['kelas_mutu'] ?> <?= $stok['mutu'] ?> (<?= (float)$stok['berat_paket'] ?> kg, <?= (int)$stok['jumlah_kemasan'] ?> pack)
                            </option>
                          <?php endwhile; ?>
                        </select>
                      </div>
                      
                      <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          Tanggal Jual
                        </label>
                        <input type="date" name="tanggal_jual" required value="<?= date('Y-m-d') ?>" 
                               class="w-full 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">
                          Nama Pembeli
                        </label>
                        <input type="text" name="nama_pembeli" required 
                               class="w-full 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">
                          Telepon Pembeli
                        </label>
                        <input type="text" name="telepon_pembeli" 
                               class="w-full 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">
                          Email Pembeli
                        </label>
                        <input type="email" name="email_pembeli" 
                               class="w-full 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">
                          Harga per Kg
                        </label>
                        <input type="number" name="harga_per_kg" required step="0.01" 
                               class="w-full 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">
                          Jumlah Pack (50kg/pack)
                        </label>
                        <input type="number" name="jumlah_pack" required min="1"
                               class="w-full 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">
                          Metode Pembayaran
                        </label>
                        <select name="metode_pembayaran" required class="w-full 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">
                          <option value="Tunai">Tunai</option>
                          <option value="Transfer">Transfer</option>
                          <option value="Kredit">Kredit</option>
                        </select>
                      </div>
                      
                      <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          Status Pembayaran
                        </label>
                        <select name="status_pembayaran" required class="w-full 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">
                          <option value="Lunas">Lunas</option>
                          <option value="Belum Lunas">Belum Lunas</option>
                          <option value="Cicilan">Cicilan</option>
                        </select>
                      </div>

                      <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          Bukti Pembayaran (gambar)
                        </label>
                        <input type="file" name="bukti_pembayaran" accept="image/*" 
                               class="w-full text-sm file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100 dark:text-gray-200" />
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Opsional. Format: JPG, PNG, dsb.</p>
                      </div>
                    </div>
                    
                    <div class="mt-4">
                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Alamat Pembeli
                      </label>
                      <textarea name="alamat_pembeli" rows="3" 
                                class="w-full 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"></textarea>
                    </div>
                    
                    <div class="mt-4">
                      <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Keterangan
                      </label>
                      <textarea name="keterangan" rows="2" 
                                class="w-full 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"></textarea>
                    </div>
                    
                    <div class="flex items-center justify-end mt-6 space-x-3">
                      <button type="button" @click="openAdd=false" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600">Batal</button>
                      <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">Simpan</button>
                    </div>
                  </form>
                </div>
              </div>
            </div>

            <!-- Table -->
            <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>
                      <th class="px-4 py-3">Aksi</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                    <?php $no = 1; while ($row = $penjualan_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>
                      <td class="px-4 py-3 text-sm">
                        <a href="?action=hapus&id=<?= $row['id_penjualan'] ?>" 
                           onclick="return confirm('Yakin ingin menghapus data penjualan ini?')"
                           class="px-3 py-1 text-sm font-medium leading-tight text-white bg-red-600 rounded-full hover:bg-red-700 focus:outline-none focus:shadow-outline">
                          Hapus
                        </a>
                      </td>
                    </tr>
                    <?php endwhile; ?>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Pagination -->
            <div class="flex items-center justify-between mt-4">
              <div class="text-sm text-gray-600 dark:text-gray-400">Halaman <?= $page ?> dari <?= $total_pages ?> (<?= $total_rows ?> data)</div>
              <div class="flex gap-2">
                <?php if ($page > 1): ?>
                  <a class="px-3 py-1 rounded bg-gray-200 dark:bg-gray-700 dark:text-gray-200" href="?<?= http_build_query(array_merge($_GET, ['page' => $page-1])) ?>">Prev</a>
                <?php endif; ?>
                <?php if ($page < $total_pages): ?>
                  <a class="px-3 py-1 rounded bg-gray-200 dark:bg-gray-700 dark:text-gray-200" href="?<?= http_build_query(array_merge($_GET, ['page' => $page+1])) ?>">Next</a>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  <script>/* Search suggestions removed; using submit-based search per request */</script>
  </body>
</html>
