<?php
require 'Prozigzig.php';
header('Content-type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

// Validate input
if (empty($data['uid']) || empty($data['parcel_id'])) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Something Went Wrong!"
    ]);
    exit();
}

$uid = $data['uid'];
$parcel_id = $data['parcel_id'];
$h = new Prozigzig();

// Step 1: Fetch current status of the parcel
$parcel = $h->queryfire("SELECT status FROM tbl_parcel WHERE uid = $uid AND id = $parcel_id")->fetch_assoc();

if (!$parcel) {
    echo json_encode([
        "ResponseCode" => "404",
        "Result" => "false",
        "ResponseMsg" => "Parcel not found!"
    ]);
    exit();
}

$current_status = $parcel['status'];

// Step 2: Allow cancellation only if status is 'Pending'
if (strtolower($current_status) === 'pending') {
    $table = "tbl_parcel";
    $field = ["status" => 'Cancelled'];
    $where = "WHERE uid = $uid AND id = $parcel_id";
    $h->updateData_Api($field, $table, $where);

    echo json_encode([
        "ResponseCode" => "200",
        "Result" => "true",
        "ResponseMsg" => "Parcel Cancelled Successfully!!"
    ]);
} else {
    echo json_encode([
        "ResponseCode" => "403",
        "Result" => "false",
        "ResponseMsg" => "Parcel cannot be cancelled as it is already " . $current_status . "."
    ]);
}
?>
