<?php
// app/Controllers/KitchenController.php

class KitchenController {

    private function requireKitchenAccess() {
        if (!isset($_SESSION['user_id'])) {
            header('Location: ' . BASE_URL . '/lsign');
            exit;
        }
        // Allow admin, cashier, waiter and kitchen to see KDS
        $allowed = ['superadmin', 'admin', 'cashier', 'waiter', 'kitchen'];
        if (!in_array($_SESSION['role'], $allowed)) {
            header('Location: ' . BASE_URL . '/lsign');
            exit;
        }
        FeatureGate::enforceKitchen($_SESSION['restaurant_id']);
    }

    public function index() {
        $this->requireKitchenAccess();
        FeatureGate::enforceSubscription($_SESSION['restaurant_id']);

        $role = $_SESSION['role'] ?? '';
        $restaurant_id = $_SESSION['restaurant_id'];

        // Restore context from cookie if available
        if (!isset($_SESSION['selected_cashier_id_kitchen']) && isset($_COOKIE['selected_cashier_id_kitchen'])) {
            $_SESSION['selected_cashier_id_kitchen'] = $_COOKIE['selected_cashier_id_kitchen'];
            if (isset($_COOKIE['selected_cashier_name_kitchen'])) {
                $_SESSION['selected_cashier_name_kitchen'] = $_COOKIE['selected_cashier_name_kitchen'];
            }
        }

        if ($role === 'admin' || $role === 'superadmin') {
            $db = getDB();
            if (isset($_GET['cashier_id'])) {
                if ($_GET['cashier_id'] === 'change') {
                    unset($_SESSION['selected_cashier_id_kitchen']);
                    unset($_SESSION['selected_cashier_name_kitchen']);
                    setcookie('selected_cashier_id_kitchen', '', time() - 3600, '/');
                    setcookie('selected_cashier_name_kitchen', '', time() - 3600, '/');
                    header('Location: ' . BASE_URL . '/kitchen');
                    exit;
                }

                if ($_GET['cashier_id'] === 'all') {
                    $_SESSION['selected_cashier_id_kitchen'] = 'all';
                    setcookie('selected_cashier_id_kitchen', 'all', time() + (86400 * 30), '/');
                    setcookie('selected_cashier_name_kitchen', 'All Queues', time() + (86400 * 30), '/');
                    header('Location: ' . BASE_URL . '/kitchen');
                    exit;
                }

                $cId = intval($_GET['cashier_id']);
                $cStmt = $db->prepare('SELECT id, name FROM users WHERE id = ? AND restaurant_id = ? AND role = "cashier" AND status = "active" LIMIT 1');
                $cStmt->execute([$cId, $restaurant_id]);
                $selected_cashier = $cStmt->fetch();
                if ($selected_cashier) {
                    $_SESSION['selected_cashier_id_kitchen'] = $selected_cashier['id'];
                    $_SESSION['selected_cashier_name_kitchen'] = $selected_cashier['name'];
                    setcookie('selected_cashier_id_kitchen', $selected_cashier['id'], time() + (86400 * 30), '/');
                    setcookie('selected_cashier_name_kitchen', $selected_cashier['name'], time() + (86400 * 30), '/');
                }
                header('Location: ' . BASE_URL . '/kitchen');
                exit;
            }

            if (!isset($_SESSION['selected_cashier_id_kitchen'])) {
                // Fetch active cashiers and their active session count (open sessions)
                $cStmt = $db->prepare('
                    SELECT u.id, u.name, u.email,
                           (SELECT COUNT(*) FROM sessions s WHERE s.user_id = u.id AND s.status = "open" AND s.restaurant_id = ?) as has_active_session
                    FROM users u
                    WHERE u.restaurant_id = ? AND u.role = "cashier" AND u.status = "active"
                    ORDER BY u.name
                ');
                $cStmt->execute([$restaurant_id, $restaurant_id]);
                $cashiers = $cStmt->fetchAll();

                $target_page = 'kitchen';
                require_once 'app/Views/admin/cashier_select.php';
                exit;
            }
        }

        require_once 'app/Views/kitchen/display.php';
    }

    // ── AJAX: Live kitchen queue ─────────────────────────────────────────────
    public function getQueue() {
        header('Content-Type: application/json');
        $this->requireKitchenAccess();
        FeatureGate::enforceSubscription($_SESSION['restaurant_id']);

        $db  = getDB();
        $rid = $_SESSION['restaurant_id'];

        $role = $_SESSION['role'] ?? '';
        $cashier_id = null;
        $filterByCashier = false;

        // Restore context from cookie if available
        if (($role === 'admin' || $role === 'superadmin') && !isset($_SESSION['selected_cashier_id_kitchen']) && isset($_COOKIE['selected_cashier_id_kitchen'])) {
            $_SESSION['selected_cashier_id_kitchen'] = $_COOKIE['selected_cashier_id_kitchen'];
            if (isset($_COOKIE['selected_cashier_name_kitchen'])) {
                $_SESSION['selected_cashier_name_kitchen'] = $_COOKIE['selected_cashier_name_kitchen'];
            }
        }

        if ($role === 'cashier') {
            $cashier_id = $_SESSION['user_id'];
            $filterByCashier = true;
        } elseif ($role === 'waiter' || $role === 'kitchen') {
            $userStmt = $db->prepare('SELECT cashier_id FROM users WHERE id = ?');
            $userStmt->execute([$_SESSION['user_id']]);
            $cashier_id = $userStmt->fetchColumn();
            if ($cashier_id === false) {
                $cashier_id = null;
            }
            $filterByCashier = true;
        } elseif ($role === 'admin' || $role === 'superadmin') {
            if (isset($_SESSION['selected_cashier_id_kitchen'])) {
                if ($_SESSION['selected_cashier_id_kitchen'] === 'all') {
                    $filterByCashier = false;
                } else {
                    $cashier_id = intval($_SESSION['selected_cashier_id_kitchen']);
                    $filterByCashier = true;
                }
            }
        }

        if ($filterByCashier && $cashier_id !== null) {
            $orders = $db->prepare("
                SELECT o.id, o.order_number, o.kitchen_status, o.order_type, o.notes, o.created_at,
                       t.name AS table_name, u.name AS waiter_name
                FROM orders o
                LEFT JOIN tables t ON t.id = o.table_id
                LEFT JOIN floors f ON f.id = t.floor_id
                LEFT JOIN users u ON u.id = o.waiter_id
                WHERE o.restaurant_id = ?
                  AND o.status NOT IN ('completed','voided')
                  AND o.kitchen_status != 'served'
                  AND (
                      f.cashier_id = ?
                      OR o.cashier_id = ?
                      OR u.cashier_id = ?
                  )
                ORDER BY o.created_at ASC
            ");
            $orders->execute([$rid, $cashier_id, $cashier_id, $cashier_id]);
        } else {
            // Admins, Superadmins, or UNASSIGNED kitchen/waiters see everything
            $orders = $db->prepare("
                SELECT o.id, o.order_number, o.kitchen_status, o.order_type, o.notes, o.created_at,
                       t.name AS table_name, u.name AS waiter_name
                FROM orders o
                LEFT JOIN tables t ON t.id = o.table_id
                LEFT JOIN users u ON u.id = o.waiter_id
                WHERE o.restaurant_id = ?
                  AND o.status NOT IN ('completed','voided')
                  AND o.kitchen_status != 'served'
                ORDER BY o.created_at ASC
            ");
            $orders->execute([$rid]);
        }
        $ordersData = $orders->fetchAll();

        foreach ($ordersData as &$order) {
            $items = $db->prepare("
                SELECT oi.quantity, oi.kitchen_note, p.name AS product_name
                FROM order_items oi
                JOIN products p ON p.id = oi.product_id
                WHERE oi.order_id = ? AND oi.status != 'voided'
            ");
            $items->execute([$order['id']]);
            $order['items'] = $items->fetchAll();
        }

        echo json_encode(['orders' => $ordersData]);
        exit;
    }

    // ── AJAX: Update kitchen status ──────────────────────────────────────────
    public function updateStatus() {
        header('Content-Type: application/json');
        $this->requireKitchenAccess();
        FeatureGate::enforceSubscription($_SESSION['restaurant_id']);

        $db   = getDB();
        $rid  = $_SESSION['restaurant_id'];
        $data = json_decode(file_get_contents('php://input'), true);

        $order_id = intval($data['order_id'] ?? 0);
        $status   = $data['status'] ?? '';
        $allowed_statuses = ['queued', 'preparing', 'ready', 'served'];

        if (!$order_id || !in_array($status, $allowed_statuses)) {
            echo json_encode(['success' => false, 'message' => 'Invalid request']);
            exit;
        }

        $stmt = $db->prepare("UPDATE orders SET kitchen_status = ? WHERE id = ? AND restaurant_id = ?");
        $stmt->execute([$status, $order_id, $rid]);

        echo json_encode(['success' => true]);
        exit;
    }
}
