<?php
// File: API_KONEKSI/distribusi/get_distribusi.php
include '../config/koneksi.php';
header('Content-Type: application/json');

// Menggunakan tabel yang benar: mst_user (lengkap_nm) dan mst_paket (paket_nm)
    $query = "SELECT r.reservasi_id, 
                 r.reservasi_id AS invoice_no, 
                 u.lengkap_nm, 
                 p.paket_nm, 
                 d.distribusi_id, d.gdrive_link, d.akses_st, d.upload_tgl
          FROM dat_reservasi r
          LEFT JOIN mst_user u ON r.user_id = u.user_id
          LEFT JOIN mst_paket p ON r.paket_id = p.paket_id
          LEFT JOIN dat_distribusi d ON r.reservasi_id = d.reservasi_id AND d.deleted_st = 0
          WHERE r.reservasi_st = 'Selesai' AND r.deleted_st = 0
          ORDER BY r.created_at DESC";

    $stmt = $conn->prepare($query);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        $data = array();
        
        while ($row = $result->fetch_assoc()) {
            $data[] = array(
                "reservasi_id" => $row['reservasi_id'],
                "invoice_no"   => $row['invoice_no'],
                "nama_lengkap" => $row['lengkap_nm'], // Sesuai kolom di mst_user
                "paket_nm"     => $row['paket_nm'],    // Sesuai kolom di mst_paket
                "gdrive_link"  => $row['gdrive_link'],
                "upload_tgl"   => $row['upload_tgl'],
                "status_kirim" => ($row['distribusi_id'] == null) ? "BELUM" : "TERKIRIM"
            );
        }
    echo json_encode(["status" => "sukses", "pesan" => "Data dimuat", "data" => $data]);
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Gagal query", "data" => []]);
}
$stmt->close();
$conn->close();
?>