<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method', [], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$orderStatus = $input['status'] ?? '';
$orderId = (int) ($input['order_id'] ?? 0);

if (!$orderId) {
    jsonResponse(false, 'Invalid order ID');
}

$validStatuses = ['new', 'confirmed', 'preparing', 'ready', 'served', 'completed', 'cancelled', 'rejected'];
if (!in_array($orderStatus, $validStatuses)) {
    jsonResponse(false, 'Invalid order status');
}

$auth = new Auth();
if (!$auth->check()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

$csrf = new CSRF();
$csrfToken = $input['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (!$csrf->verify($csrfToken)) {
    jsonResponse(false, 'Invalid CSRF token', [], 403);
}

$restaurantId = $auth->restaurantId();
if (!$restaurantId) {
    jsonResponse(false, 'No restaurant associated', [], 403);
}

$db = Database::getInstance();
$pdo = $db->getConnection();

$stmt = $pdo->prepare(
    "SELECT id, restaurant_id, order_status, table_id FROM orders WHERE id = ? AND restaurant_id = ? LIMIT 1"
);
$stmt->execute([$orderId, $restaurantId]);
$order = $stmt->fetch();

if (!$order) {
    jsonResponse(false, 'Order not found');
}

$pdo->beginTransaction();

try {
    $fromStatus = $order['order_status'];

    $updateStmt = $pdo->prepare(
        "UPDATE orders SET order_status = ?, updated_at = NOW() WHERE id = ?"
    );
    $updateStmt->execute([$orderStatus, $orderId]);

    $historyStmt = $pdo->prepare(
        "INSERT INTO order_status_history (order_id, from_status, to_status, notes, changed_by, created_at)
         VALUES (?, ?, ?, ?, ?, NOW())"
    );
    $historyStmt->execute([
        $orderId,
        $fromStatus,
        $orderStatus,
        'Status updated to ' . $orderStatus,
        $auth->userId()
    ]);

    if ($order['table_id'] && in_array($orderStatus, ['cancelled', 'completed'])) {
        $tableReset = $pdo->prepare(
            "UPDATE tables SET status = 'available', updated_at = NOW() WHERE id = ? AND restaurant_id = ?"
        );
        $tableReset->execute([$order['table_id'], $restaurantId]);
    } elseif ($order['table_id'] && $orderStatus === 'served') {
        $tableUpdate = $pdo->prepare(
            "UPDATE tables SET status = 'occupied', updated_at = NOW() WHERE id = ? AND restaurant_id = ?"
        );
        $tableUpdate->execute([$order['table_id'], $restaurantId]);
    } elseif ($order['table_id'] && in_array($orderStatus, ['preparing'])) {
        $tableUpdate = $pdo->prepare(
            "UPDATE tables SET status = 'preparing', updated_at = NOW() WHERE id = ? AND restaurant_id = ?"
        );
        $tableUpdate->execute([$order['table_id'], $restaurantId]);
    } elseif ($order['table_id'] && $orderStatus === 'ready') {
        $tableUpdate = $pdo->prepare(
            "UPDATE tables SET status = 'ready', updated_at = NOW() WHERE id = ? AND restaurant_id = ?"
        );
        $tableUpdate->execute([$order['table_id'], $restaurantId]);
    }

    $pdo->commit();

    jsonResponse(true, 'Order status updated', [
        'order_id'    => $orderId,
        'from_status' => $fromStatus,
        'to_status'   => $orderStatus,
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    error_log('Update order status error: ' . $e->getMessage());
    jsonResponse(false, 'Failed to update order status', [], 500);
}
