<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

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

$orderId = (int) ($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
$orderNumber = trim($_GET['order_number'] ?? $_POST['order_number'] ?? '');
$restaurantId = (int) ($_GET['restaurant_id'] ?? $_POST['restaurant_id'] ?? 0);

if ($restaurantId <= 0) {
    jsonResponse(false, 'Invalid restaurant');
}

$db = Database::getInstance();

if ($orderId > 0) {
    $order = $db->query(
        "SELECT id, order_number, order_status, order_type, grand_total, created_at
         FROM orders WHERE id = ? AND restaurant_id = ?",
        [$orderId, $restaurantId]
    )->fetch();
} elseif (!empty($orderNumber)) {
    $order = $db->query(
        "SELECT id, order_number, order_status, order_type, grand_total, created_at
         FROM orders WHERE order_number = ? AND restaurant_id = ?",
        [$orderNumber, $restaurantId]
    )->fetch();
} else {
    jsonResponse(false, 'Please provide order ID or order number');
}

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

$statusLabels = [
    'pending'    => 'Order Received',
    'confirmed'  => 'Order Confirmed',
    'preparing'  => 'Being Prepared',
    'ready'      => 'Ready for Pickup',
    'served'     => 'Served',
    'completed'  => 'Completed',
    'cancelled'  => 'Cancelled',
];

$statusSteps = ['pending', 'confirmed', 'preparing', 'ready', 'served'];
$currentStatus = $order['order_status'];
$currentStepIndex = array_search($currentStatus, $statusSteps);
if ($currentStepIndex === false) $currentStepIndex = -1;

$steps = [];
foreach ($statusSteps as $idx => $step) {
    $steps[] = [
        'status'    => $step,
        'label'     => $statusLabels[$step] ?? ucfirst($step),
        'completed' => $idx < $currentStepIndex,
        'active'    => $idx === $currentStepIndex,
    ];
}

jsonResponse(true, 'Order status retrieved', [
    'order_id'       => $order['id'],
    'order_number'   => $order['order_number'],
    'order_status'   => $currentStatus,
    'status_label'   => $statusLabels[$currentStatus] ?? ucfirst($currentStatus),
    'order_type'     => $order['order_type'],
    'grand_total'    => (float) $order['grand_total'],
    'created_at'     => $order['created_at'],
    'steps'          => $steps,
    'is_terminal'    => in_array($currentStatus, ['served', 'completed', 'cancelled']),
]);
