<?php

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

require_once("../config/database.php");

$db = getDB();

$order_number =
$_POST['order_number']
?? '';

if(empty($order_number)){

    echo json_encode([

        "success" => false,

        "message" => "Missing Order"
    ]);

    exit;
}

$order_number =
$db->real_escape_string(
    $order_number
);

$result =
$db->query("SELECT *

FROM orders

WHERE order_number='$order_number'

LIMIT 1");

if($result->num_rows == 0){

    echo json_encode([

        "success" => false,

        "message" => "Order Not Found"
    ]);

    exit;
}

$order =
$result->fetch_assoc();

$status =
$order['status'];

if($status != "Pending"){

    echo json_encode([

        "success" => false,

        "message" =>
        "Cannot cancel now"
    ]);

    exit;
}

$created =
strtotime(
    $order['created_at']
);

$now = time();

$minutes =
($now - $created) / 60;

if($minutes > 30){

    echo json_encode([

        "success" => false,

        "message" =>
        "Cancel time expired"
    ]);

    exit;
}

$db->query("UPDATE orders

SET status='Cancelled'

WHERE order_number='$order_number'");

echo json_encode([

    "success" => true,

    "message" =>
    "Order Cancelled"
]);