<?php
// Set header untuk memberitahu browser bahwa responsnya adalah JSON
header('Content-Type: application/json');

// Error reporting untuk development
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // --- KONEKSI DATABASE ---
    // Pastikan file data.php berada di lokasi yang benar (../data.php)
    include_once '../data.php'; 
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        // Lemparkan exception jika koneksi gagal
        throw new Exception("Koneksi database gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");

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

    // Ambil tanggal dari request POST yang dikirim oleh JavaScript
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['start_date']) && !empty($_POST['start_date'])) {
            $start_date = filter_var($_POST['start_date'], FILTER_SANITIZE_STRING);
        }
        if (isset($_POST['end_date']) && !empty($_POST['end_date'])) {
            $end_date = filter_var($_POST['end_date'], FILTER_SANITIZE_STRING);
        }
    }

    // --- QUERY UTAMA ---
    $sql = "
    SELECT 
        j.brand, j.cab, cabang.nama AS cabang_nama, tt.nama AS tipe_nama, j.mesin, j.nomor, j.tanggal, j.jamm, j.shift, j.user AS user_jual, j.batal, 
        j.kasir, users.nama AS kasir_nama, j.register, j.deliver, p.sub, p.payment, p.tglo, p.kode, p.name AS nama_barang, p.group_name,
        CAST(p.quantity AS DECIMAL(10,2)) as quantity, CAST(p.harga AS DECIMAL(15,2)) as harga,
        CAST(p.price AS DECIMAL(15,2)) as price, CAST(p.discp AS DECIMAL(10,2)) as discp,
        CAST(p.discr AS DECIMAL(15,2)) as discr, CAST(p.netto AS DECIMAL(15,2)) as netto,
        CAST(p.disc AS DECIMAL(15,2)) as disc, CAST(p.ppn AS DECIMAL(15,2)) as ppn,
        CAST(p.pajak AS DECIMAL(15,2)) as pajak, CAST(p.serv AS DECIMAL(15,2)) as serv,
        CAST(p.service AS DECIMAL(15,2)) as service, CAST(p.jumlah AS DECIMAL(15,2)) as jumlah,
        p.meja, p.user AS user_pesani
    FROM jual j
    LEFT JOIN pesani p ON j.nomor = p.nomor
    LEFT JOIN tipe_transaksi tt ON j.tipe = tt.kode
    LEFT JOIN cabang ON j.cab = cabang.kode
    LEFT JOIN users ON j.kasir = users.kode
    WHERE j.tanggal BETWEEN ? AND ? AND j.batal = 0 and p.payment < '01'
    ORDER BY j.tanggal ASC, j.nomor ASC, p.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()) {
        // Ganti nilai null agar tidak menyebabkan error di JavaScript
        foreach ($row as $key => $value) {
            if ($value === null) {
                // Jika kolom seharusnya angka, beri nilai 0, selain itu beri string kosong
                $row[$key] = is_numeric($row[$key]) ? 0 : '';
            }
        }
        $data[] = $row;
    }

    $stmt->close();
    $conn->close();
    
    // --- OUTPUT JSON ---
    // Cetak data sebagai JSON. Ini akan menjadi satu-satunya output dari file ini.
    echo json_encode($data, JSON_NUMERIC_CHECK);

} catch (Exception $e) {
    // Jika terjadi error di mana pun dalam blok try, kirim respons error
    http_response_code(500); // Set status code ke 'Internal Server Error'
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>