<?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;
}

$order_id   = intval($data['order_id'] ?? 0);
$new_status = trim($db->real_escape_string($data['status'] ?? '')); // E.g., 'Pending', 'Dispatched'

// ✅ MATCHES YOUR EXACT CAPITALIZED SPELLINGS IN DATABASE
$valid_statuses = ['Pending', 'Confirmed', 'Processing', 'Packed', 'Dispatched', 'Delivered', 'Cancelled', 'Refunded', 'Failed'];

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

$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"]);
    exit;
}

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

// Case-insensitive comparisons for inventory stock adjustments
if ((strcasecmp($new_status, 'cancelled') == 0 || strcasecmp($new_status, 'refunded') == 0) && 
    (strcasecmp($current_status, 'cancelled') != 0 && strcasecmp($current_status, 'refunded') != 0)) {
        
    $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 update directly using the Capitalized status value
$update = $db->query("UPDATE orders SET status = '$new_status' WHERE id = $order_id");

if ($update) {
    echo json_encode(["success" => true, "message" => "Order state changed to " . $new_status . " successfully"]);
} else {
    echo json_encode(["success" => false, "message" => $db->error]);
}