<?php
// === HEADER CORS WAJIB DI ATAS ===
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}
// ===============================================

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Panggil koneksi DAN si "Tukang Pos"
require_once 'db.php'; 
require_once 'send_notification.php'; // <-- Panggil file baru

// --- DI SINI ANDA MEM-PASTE KUNCI SERVER FIREBASE ANDA ---
$FCM_SERVER_KEY = "AAAA...Kunci_Server_Rahasia_Anda_Dari_Firebase...QY";
// --------------------------------------------------------

$data = json_decode(file_get_contents("php://input"));

// (Validasi data... biarkan sama)
if (!isset($data->user_id) || !isset($data->restaurant_id) || ... ) {
    // ...
    exit();
}

try {
    $conn->beginTransaction();

    // (Kode INSERT INTO orders... biarkan sama)
    $sqlOrder = "INSERT INTO orders (user_id, restaurant_id, ...) VALUES (...)";
    $stmtOrder = $conn->prepare($sqlOrder);
    // ... (bind params)
    $stmtOrder->execute();
    $order_id = $conn->lastInsertId();

    // (Kode INSERT INTO order_items... biarkan sama)
    // ... (looping foreach)
    
    $conn->commit(); // Kunci pesanan

    // --- LANGKAH BARU: KIRIM NOTIFIKASI ---
    try {
        // 1. Cari Token HP si Penjual (Merchant)
        // Kita asumsikan ID Restoran = ID User Merchant
        $stmtToken = $conn->prepare("SELECT fcm_token FROM users WHERE id = :resto_id");
        $stmtToken->bindParam(':resto_id', $data->restaurant_id);
        $stmtToken->execute();
        $merchant = $stmtToken->fetch();

        if ($merchant && !empty($merchant['fcm_token'])) {
            // 2. Kirim notifikasi ke HP Penjual!
            $title = "Pesanan Baru!";
            $body = "Ada pesanan baru masuk (ID: #$order_id) senilai Rp " . number_format($data->total_price);
            sendFirebaseNotification($FCM_SERVER_KEY, $merchant['fcm_token'], $title, $body, $order_id);
        }
    } catch (Exception $e) {
        // abaikan jika notif gagal, yang penting orderan masuk
        error_log("Gagal kirim notif: " . $e->getMessage()); 
    }
    // ----------------------------------------

    http_response_code(201);
    echo json_encode([
        "status" => "success",
        "message" => "Pesanan berhasil dibuat!",
        "order_id" => $order_id
    ]);

} catch (PDOException $e) {
    // (Blok catch error... biarkan sama)
}
?>