<?php
include '../connection.php'; 

header('Content-Type: application/json');

$order_id = intval($_POST['order_id'] ?? 0);

if ($order_id === 0) {
    // body was JSON: read raw input
    $input = json_decode(file_get_contents('php://input'), true);
    $order_id = intval($input['order_id'] ?? 0);
}

if ($order_id <= 0) {
    echo json_encode(['success' => false, 'msg' => 'Invalid order ID']);
    exit;
}

// Only allow cancel if status is still 'Pending'
$stmt = $conn->prepare("SELECT status FROM tbl_order WHERE id = ?");
$stmt->bind_param("i", $order_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'msg' => 'Order not found']);
    exit;
}

$order = $result->fetch_assoc();

if (strtolower($order['status']) !== 'pending') {
    echo json_encode(['success' => false, 'msg' => 'Only pending orders can be cancelled']);
    exit;
}

// Update status to 'Cancelled'
$update = $conn->prepare("UPDATE tbl_order SET status = 'Cancelled' WHERE id = ?");
$update->bind_param("i", $order_id);
$update->execute();

echo json_encode(['success' => true, 'msg' => 'Order cancelled']);
?>