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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pembayaran_id = $_POST['pembayaran_id'] ?? '';
    $pengirim_nm = $_POST['pengirim_nm'] ?? '';
    $asal_bank = $_POST['asal_bank'] ?? '';
    $validasi_st = 'Pending'; 

    if (empty($pembayaran_id) || empty($pengirim_nm) || empty($asal_bank) || empty($_FILES['file_bukti']['name'])) {
        echo json_encode(["status" => "gagal", "pesan" => "Nama pengirim, asal bank, dan foto bukti wajib diisi lengkap!", "data" => []]);
        exit;
    }

    $target_dir = "../uploads/bukti/";
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    $file_extension = strtolower(pathinfo($_FILES["file_bukti"]["name"], PATHINFO_EXTENSION));
    $allowed_extensions = array("jpg", "jpeg", "png");
    
    // Validasi ekstensi
    if (!in_array($file_extension, $allowed_extensions)) {
        echo json_encode(["status" => "gagal", "pesan" => "Hanya file JPG, JPEG, dan PNG yang diizinkan!", "data" => []]);
        exit;
    }
    
    // Validasi MIME type menggunakan finfo
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES["file_bukti"]["tmp_name"]);
    finfo_close($finfo);
    
    $allowed_mime_types = array("image/jpeg", "image/png");
    if (!in_array($mime, $allowed_mime_types)) {
        echo json_encode(["status" => "gagal", "pesan" => "File bukan merupakan gambar yang valid!", "data" => []]);
        exit;
    }

    $new_filename = "BUKTI_" . $pembayaran_id . "_" . time() . "." . $file_extension;
    $target_file = $target_dir . $new_filename;

    if (move_uploaded_file($_FILES["file_bukti"]["tmp_name"], $target_file)) {
        $query = "UPDATE dat_pembayaran SET 
                    pengirim_nm = ?, 
                    asal_bank = ?, 
                    transfer_bukti = ?, 
                    validasi_st = ?, 
                    bayar_tgl = CURRENT_TIMESTAMP 
                  WHERE pembayaran_id = ?";
                  
        $stmt = $conn->prepare($query);
        $stmt->bind_param("sssss", $pengirim_nm, $asal_bank, $new_filename, $validasi_st, $pembayaran_id);

        if ($stmt->execute()) {
            
            // --- LOGIKA NOTIFIKASI KE ADMIN ---
            // 1. Cari tau reservasi_id dari pembayaran ini dan nama pelanggan asli
            $q_res = $conn->prepare("
                SELECT r.reservasi_id, u.lengkap_nm 
                FROM dat_pembayaran p 
                JOIN dat_reservasi r ON p.reservasi_id = r.reservasi_id 
                JOIN mst_user u ON r.user_id = u.user_id 
                WHERE p.pembayaran_id = ?
            ");
            $q_res->bind_param("s", $pembayaran_id);
            $q_res->execute();
            $r_res = $q_res->get_result();
            
            $reservasi_id = '';
            $nama_pelanggan = "Pelanggan";
            if ($row_res = $r_res->fetch_assoc()) {
                $reservasi_id = $row_res['reservasi_id'];
                $nama_pelanggan = $row_res['lengkap_nm'];
            }
            $q_res->close();

            // 2. Kirim notifikasi ke semua user dengan role Admin
            if (!empty($reservasi_id)) {
                $judul_notif = "Pembayaran Baru Masuk 💰";
                $pesan_notif = "Pelanggan " . $nama_pelanggan . " baru saja mengirim bukti transfer a/n " . $pengirim_nm . " via " . $asal_bank . ". Silakan divalidasi!";
                $tipe_notif = "transaksi";

                $query_admin = "SELECT user_id FROM mst_user WHERE role_nm = 'Admin' AND active_st = 1";
                $res_admin = $conn->query($query_admin);

                if ($res_admin && $res_admin->num_rows > 0) {
                    $stmt_notif = $conn->prepare("INSERT INTO dat_notifikasi (notif_id, user_id, tipe_notif, target_id, judul_tx, pesan_tx) VALUES (?, ?, ?, ?, ?, ?)");
                    while ($row_admin = $res_admin->fetch_assoc()) {
                        $target_admin = $row_admin['user_id'];
                        $notif_id = generateNotifId($conn);
                        $stmt_notif->bind_param("ssssss", $notif_id, $target_admin, $tipe_notif, $reservasi_id, $judul_notif, $pesan_notif);
                        $stmt_notif->execute();
                    }
                    $stmt_notif->close();
                }
            }
            // ----------------------------------

            echo json_encode(["status" => "sukses", "pesan" => "Bukti berhasil dikirim! Menunggu validasi admin.", "data" => []]);
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Database error: " . $stmt->error, "data" => []]);
        }
        $stmt->close();
    } else {
        echo json_encode(["status" => "gagal", "pesan" => "Gagal mengunggah file bukti transfer ke server", "data" => []]);
    }
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Metode tidak diizinkan", "data" => []]);
}
$conn->close();
?>