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

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

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

$action = $_POST['action'] ?? '';
$orderId = (int) ($_POST['order_id'] ?? 0);

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

$validTransitions = [
    'start_preparing' => ['new', 'confirmed'],
    'mark_ready'      => ['preparing'],
    'mark_served'     => ['ready'],
    'update_status'   => ['new', 'confirmed', 'preparing', 'ready'],
];

if (!isset($validTransitions[$action])) {
    jsonResponse(false, 'Invalid action');
}

$statusMap = [
    'start_preparing' => 'preparing',
    'mark_ready'      => 'ready',
    'mark_served'     => 'served',
];

if ($action === 'update_status') {
    $newStatus = $_POST['status'] ?? '';
    $allowed = ['cancelled', 'rejected'];
    if (!in_array($newStatus, $allowed)) {
        jsonResponse(false, 'Invalid target status for update_status');
    }
} else {
    $newStatus = $statusMap[$action];
}

$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');
}

$allowedStatuses = $validTransitions[$action];
if (!in_array($order['order_status'], $allowedStatuses)) {
    jsonResponse(false, 'Cannot transition from ' . $order['order_status'] . ' to ' . $newStatus);
}

$pdo->beginTransaction();

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

    $updateStmt = $pdo->prepare(
        "UPDATE orders SET order_status = ?, updated_at = NOW() WHERE id = ?"
    );
    $updateStmt->execute([$newStatus, $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,
        $newStatus,
        ucfirst(str_replace('_', ' ', $action)) . ' by kitchen',
        $auth->userId()
    ]);

    if ($order['table_id']) {
        $tableStatusMap = [
            'preparing' => 'preparing',
            'ready'     => 'ready',
            'served'    => 'occupied',
        ];
        if (isset($tableStatusMap[$newStatus])) {
            $tableStmt = $pdo->prepare(
                "UPDATE tables SET status = ?, updated_at = NOW() WHERE id = ? AND restaurant_id = ?"
            );
            $tableStmt->execute([$tableStatusMap[$newStatus], $order['table_id'], $restaurantId]);
        }
    }

    $pdo->commit();

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

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