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

// Set header ke JSON
header('Content-Type: application/json');

// Ambil parameter dari request
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');
$cabang = $_GET['cabang'] ?? '';

try {
    // Koneksi ke database
    // $conn = new mysqli($host, $user, $pass, $db);
    include_once '../data.php';
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        throw new Exception("Koneksi gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");
    
    // 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
    ";
    
    // Tambahkan filter cabang jika ada
    if (!empty($cabang)) {
        $sql .= " AND j.cab = ?";
    }
    
    $sql .= " ORDER BY j.tanggal ASC, j.nomor ASC, p.kode ASC";
    
    $stmt = $conn->prepare($sql);
    
    if (!empty($cabang)) {
        $stmt->bind_param("sss", $start_date, $end_date, $cabang);
    } else {
        $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) {
            if ($value === null) {
                $row[$key] = is_numeric($row[$key]) ? 0 : '-';
            }
        }
        $data[] = $row;
    }
    $stmt->close();
    $conn->close();
    
    // Return JSON response
    echo json_encode([
        'success' => true,
        'data' => $data
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>