<?php
// Konfigurasi Database
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Default range tanggal: bulan ini
$start_date = date('Y-m-01');
$end_date = date('Y-m-t');

// Jika form disubmit, ambil dari input
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
}

// Query utama
$sql = "
SELECT 
    jual.brand,
    jual.cab,
    tipe_transaksi.nama AS tipe_nama,
    jual.mesin,
    jual.nomor,
    jual.tanggal,
    jual.jamm,
    jual.shift,
    jual.cover,
    jual.user AS user_jual,
    jual.batal,
    jual.kasir,
    jual.register,
    jual.deliver,
    pesani.sub,
    pesani.payment,
    pesani.tglo,
    pesani.kode,
    pesani.name AS nama_barang,
    pesani.group_name,
    pesani.quantity,
    pesani.harga,
    pesani.price,
    pesani.discp,
    pesani.discr,
    pesani.netto,
    pesani.disc,
    pesani.ppn,
    pesani.pajak,
    pesani.serv,
    pesani.service,
    pesani.jumlah,
    pesani.meja,
    pesani.user AS user_pesani
FROM jual
LEFT JOIN pesani ON jual.nomor = pesani.nomor
LEFT JOIN tipe_transaksi ON jual.tipe = tipe_transaksi.kode
WHERE jual.tanggal BETWEEN ? AND ?
  AND jual.batal = 0
ORDER BY jual.tanggal ASC, jual.nomor ASC, pesani.kode ASC
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Pastikan kolom numerik tetap numerik untuk agregasi di pivot
    $row['quantity'] = (float)$row['quantity'];
    $row['harga'] = (float)$row['harga'];
    $row['jumlah'] = (float)$row['jumlah'];
    $row['discr'] = (float)$row['discr'];
    $row['pajak'] = (float)$row['pajak'];
    $row['service'] = (float)$row['service'];

    $data[] = $row;
}

$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Laporan Penjualan Interaktif (Pivot)</title>
    
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pivottable/2.23.0/pivot.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/pivottable/2.23.0/pivot.min.css">

    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h2 { color: #333; }
        .filter { background: #f5f5f5; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        label { display: inline-block; width: 120px; font-weight: bold; }
        input[type="date"] { padding: 6px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px; }
        button { 
            padding: 8px 20px; background: #28a745; color: white; border: none; 
            border-radius: 4px; cursor: pointer; 
        }
        button:hover { background: #218838; }
        .pvtUI { margin-top: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .no-data { color: #dc3545; font-weight: bold; margin-top: 20px; }
    </style>
</head>
<body>

<h2>📊 Laporan Penjualan Interaktif</h2>

<div class="filter">
    <form method="POST">
        <label>Tanggal Mulai:</label>
        <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" required>
        
        <label>Tanggal Akhir:</label>
        <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" required>
        
        <button type="submit">Tampilkan Laporan</button>
    </form>
</div>

<?php if (empty($data)): ?>
    <p class="no-data">❌ Tidak ada data penjualan untuk rentang tanggal ini.</p>
<?php else: ?>
    <p><strong>💡 Drag & drop field</strong> di bawah untuk menganalisa <strong><?= count($data) ?> baris data</strong> dari tanggal <strong><?= $start_date ?></strong> sampai <strong><?= $end_date ?></strong></p>
    
    <div id="output"></div>
<?php endif; ?>

<script>
    // Pastikan script berjalan setelah halaman siap
    $(function(){
        // Cek jika ada data dari PHP
        <?php if (!empty($data)): ?>
        
            // 4. Mengubah data PHP menjadi variabel JavaScript
            var data = <?= json_encode($data); ?>;

            // 5. Konfigurasi dan inisialisasi PivotTable
            $("#output").pivotUI(
                data,
                {
                    // Pengaturan default saat pertama kali dimuat
                    rows: ["group_name", "nama_barang"], // Field untuk baris
                    cols: ["tipe_nama"],                // Field untuk kolom
                    aggregatorName: "Sum",              // Jenis agregasi (Sum, Count, Average, dll.)
                    vals: ["jumlah"],                   // Nilai yang dihitung
                    rendererName: "Table Barchart"      // Tampilan awal
                }
            );
        <?php endif; ?>
    });
</script>

</body>
</html>