<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();

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

if (!$data) {
    echo json_encode(["success" => false, "message" => "Empty transaction criteria parsed"]);
    exit;
}

// Guarantee absolute integer extraction from the request payload
$order_id   = intval($data['order_id'] ?? 0);
$new_status = trim($db->real_escape_string($data['status'] ?? ''));

$valid_statuses = ['pending', 'confirmed', 'processing', 'packed', 'out_for_delivery', 'delivered', 'cancelled', 'refunded', 'failed'];

if (!in_array($new_status, $valid_statuses)) {
    echo json_encode(["success" => false, "message" => "Illegal order status parsed: " . $new_status]);
    exit;
}

// Fetch current state parameters to confirm rollback operations rules logic boundaries
$orderCheck = $db->query("SELECT status FROM orders WHERE id = $order_id LIMIT 1");
if (!$orderCheck || $orderCheck->num_rows == 0) {
    echo json_encode(["success" => false, "message" => "Target order instance not found for ID: " . $order_id]);
    exit;
}

$current_status = $orderCheck->fetch_assoc()['status'];

if (($new_status == 'cancelled' || $new_status == 'refunded') && ($current_status != 'cancelled' && $current_status != 'refunded')) {
    $itemsResult = $db->query("SELECT product_id, quantity FROM order_items WHERE order_id = $order_id");
    if ($itemsResult) {
        while ($item = $itemsResult->fetch_assoc()) {
            $p_id = intval($item['product_id']);
            $qty  = intval($item['quantity']);
            
            if ($p_id > 0) {
                $db->query("UPDATE products SET stock = stock + $qty, total_sales = GREATEST(0, total_sales - $qty) WHERE id = $p_id");
            }
        }
    }
}

// Execute master status mutation transaction update
$update = $db->query("UPDATE orders SET status = '$new_status' WHERE id = $order_id");

if ($update && $db->affected_rows > 0) {
    echo json_encode(["success" => true, "message" => "Order state changed to " . $new_status . " successfully"]);
} else if ($update && $db->affected_rows === 0) {
    echo json_encode(["success" => true, "message" => "Status was already set to " . $new_status]);
} else {
    echo json_encode(["success" => false, "message" => "Database write failure: " . $db->error]);
}