<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['order_id'])) {
        echo json_encode(["success" => false, "message" => "Missing order_id"]);
        exit;
    }

    $orderId = intval($_POST['order_id']);

    try {
        // Start transaction
        $conn->begin_transaction();

        // Delete order items first
        $stmt1 = $conn->prepare("DELETE FROM tbl_order_items WHERE order_id = ?");
        $stmt1->bind_param("i", $orderId);
        $stmt1->execute();
        $stmt1->close();

        // Delete order
        $stmt2 = $conn->prepare("DELETE FROM tbl_order WHERE id = ?");
        $stmt2->bind_param("i", $orderId);
        $stmt2->execute();
        $stmt2->close();

        // Commit
        $conn->commit();

        echo json_encode(["success" => true, "message" => "Order deleted successfully"]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Delete failed: " . $e->getMessage()]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Invalid request"]);
}

