<?php
// Konfigurasi Database
$host = 'localhost';
$user = 'root';
$pass = '';
$db   = 'pos_m';

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

// Set header untuk memberitahu klien bahwa ini adalah respon JSON
header('Content-Type: application/json');

try {
    // Koneksi dengan error handling
    $conn = new mysqli($host, $user, $pass, $db);
    if ($conn->connect_error) {
        throw new Exception("Koneksi database gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");

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

    // Validasi dan sanitasi input dari POST
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
            // Mengambil input tanggal dari request POST
            $start_date = filter_var($_POST['start_date'], FILTER_SANITIZE_STRING);
            $end_date = filter_var($_POST['end_date'], FILTER_SANITIZE_STRING);
        }
    }
    
    // Jika tidak ada input POST (misalnya diakses langsung), gunakan default/bulan ini.
    // Jika input POST kosong, gunakan default.
    if (empty($start_date) || empty($end_date)) {
         $start_date = date('Y-m-01');
         $end_date = date('Y-m-t');
    }

    // 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()) {
        foreach ($row as $key => $value) {
            // Mengubah NULL menjadi 0 (untuk numerik) atau '-' (untuk string), seperti di pivot4.php
            if ($value === null) {
                $row[$key] = is_numeric($row[$key]) ? 0 : '-';
            }
        }
        $data[] = $row;
    }

    $stmt->close();
    $conn->close();
    
    // Output JSON
    echo json_encode($data, JSON_NUMERIC_CHECK);

} catch (Exception $e) {
    // Tangani error dan kembalikan JSON error
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => $e->getMessage()]);
}

// Tidak ada HTML di sini
?>