<?php
// File: API_KONEKSI/admin/paket/simpan_paket.php
header('Content-Type: application/json');
include '../../config/koneksi.php';
include '../../config/middleware.php';
include '../../config/id_generator.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $paket_id = $_POST['paket_id'] ?? '';
    $paket_nm = $_POST['paket_nm'] ?? '';
    $kategori = $_POST['kategori_tx'] ?? 'Thematic'; 
    $harga = $_POST['normal_harga'] ?? 0;
    $durasi = $_POST['durasi_menit'] ?? 0;
    $deskripsi = $_POST['deskripsi_tx'] ?? '';
    $fasilitas = $_POST['fasilitas_tx'] ?? '';
    $active_st = $_POST['active_st'] ?? 1;
    $payload = authenticateJWT();
    $user_id = $payload['user_id'] ?? ''; 
    
    $foto_base64 = $_POST['foto_base64'] ?? '';
    $nama_foto = $_POST['nama_foto_lama'] ?? '';

    // PENANDA: Cek apakah ini aksi tambah paket baru atau edit
    $is_new_paket = empty($paket_id);

    // Validasi penyimpanan gambar
    if (!empty($foto_base64)) {
        $file_name = "paket_" . time() . ".jpg";
        $path = "../../uploads/" . $file_name;

        if (file_put_contents($path, base64_decode($foto_base64))) {
            $nama_foto = $file_name;
        } else {
            echo json_encode([
                "status" => "gagal",
                "pesan" => "Gagal menyimpan gambar",
                "data" => []
            ]);
            exit;
        }
    }

    // Siapkan query berdasarkan kondisi (Baru vs Edit)
    if ($is_new_paket) {
        $paket_id = generatePaketId($conn);
        $stmt = $conn->prepare("INSERT INTO mst_paket (paket_id, paket_nm, kategori_tx, deskripsi_tx, fasilitas_tx, durasi_menit, normal_harga, thumbnail_foto, active_st, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssiisis", $paket_id, $paket_nm, $kategori, $deskripsi, $fasilitas, $durasi, $harga, $nama_foto, $active_st, $user_id);
        $pesan = "Paket berhasil ditambahkan!";
    } else {
        $stmt = $conn->prepare("UPDATE mst_paket SET paket_nm=?, kategori_tx=?, deskripsi_tx=?, fasilitas_tx=?, durasi_menit=?, normal_harga=?, thumbnail_foto=?, active_st=?, updated_by=? WHERE paket_id=?");
        $stmt->bind_param("ssssiisiss", $paket_nm, $kategori, $deskripsi, $fasilitas, $durasi, $harga, $nama_foto, $active_st, $user_id, $paket_id);
        $pesan = "Paket berhasil diperbarui!";
    }

    // Eksekusi query
    if ($stmt->execute()) {
        
        // --- LOGIKA NOTIFIKASI KHUSUS UNTUK PAKET BARU ---
        if ($is_new_paket) {
            $new_paket_id = $paket_id; // Ambil ID dari paket yang barusan masuk
            
            $judul_notif = "Paket Baru: " . $paket_nm . " 🎉";
            $pesan_notif = "Koneksi Studio Sleman punya layanan baru nih! Yuk cek detail paket " . $paket_nm . " sekarang.";
            $tipe_notif = "paket";
            
            // Broadcast ke semua pelanggan
            $query_pelanggan = "SELECT user_id FROM mst_user WHERE role_nm = 'Pelanggan' AND active_st = 1 AND deleted_st = 0";
            $res_pelanggan = $conn->query($query_pelanggan);
            if ($res_pelanggan && $res_pelanggan->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_pelanggan = $res_pelanggan->fetch_assoc()) {
                    $target_user = $row_pelanggan['user_id'];
                    $notif_id = generateNotifId($conn);
                    $stmt_notif->bind_param("ssssss", $notif_id, $target_user, $tipe_notif, $new_paket_id, $judul_notif, $pesan_notif);
                    $stmt_notif->execute();
                }
                $stmt_notif->close();
            }
        }
        // ------------------------------------------------

        echo json_encode(["status" => "sukses", "pesan" => $pesan, "data" => []]);
    } else {
        echo json_encode(["status" => "gagal", "pesan" => "Gagal menyimpan: " . $stmt->error, "data" => []]);
    }
    
    $stmt->close();
}
$conn->close();
?>
