<?php
// Panggil file koneksi Anda (ini sudah termasuk header CORS)
require_once 'db.php'; 

// Tampilkan error jika ada (untuk debug)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Terima data JSON dari aplikasi Ionic
$data = json_decode(file_get_contents("php://input"));

// 1. Validasi data
if (
    !isset($data->order_id) || 
    !isset($data->new_status)
) {
    http_response_code(400); // Bad Request
    echo json_encode(["error" => "Data tidak lengkap (membutuhkan order_id dan new_status)."]);
    exit();
}

// 2. Siapkan data
$order_id = $data->order_id;
$new_status = $data->new_status; // Misal: "Diproses" atau "Dibatalkan"

// 3. Update database
try {
    $sql = "UPDATE orders SET status = :new_status WHERE id = :order_id";
    $stmt = $conn->prepare($sql);
    
    $stmt->bindParam(':new_status', $new_status);
    $stmt->bindParam(':order_id', $order_id);
    
    if ($stmt->execute()) {
        http_response_code(200);
        echo json_encode([
            "status" => "success",
            "message" => "Status pesanan #" . $order_id . " berhasil diubah menjadi " . $new_status
        ]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Gagal mengeksekusi query."]);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        "status" => "error",
        "message" => "Database error.",
        "debug_sql_error" => $e->getMessage()
    ]);
}
?>