<?php
header('Content-Type: text/html; charset=utf-8');
/**
 * CMTC Tech Solution - Self-Service Order Status Monitor (Enterprise UI)
 * Theme: Private CMTC Tech Solution Theme
 */
require_once 'db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$raw_store_id = $_REQUEST['store_id'] ?? ($_REQUEST['shop_id'] ?? ($_SESSION['scanned_store_id'] ?? ''));
$table_number = isset($_GET['table']) ? preg_replace('/[^0-9a-zA-Z_\-]/', '', $_GET['table']) : ($_SESSION['scanned_table'] ?? '');
$token_param = $_GET['token'] ?? ($_SESSION['scanned_token'] ?? '');
$shop_name_param = $_GET['shop_name'] ?? ($_SESSION['scanned_shop_name'] ?? '');

$is_demo_mode = (
    $raw_store_id === 'DEMO_STORE' ||
    (!empty($_REQUEST['is_demo']) && $_REQUEST['is_demo'] == 1) ||
    (!empty($_GET['demo']) && $_GET['demo'] == 1)
);

if ($is_demo_mode) {
    $user_role_home = "menu.php?store_id=DEMO_STORE&is_demo=1&table=" . urlencode($table_number ?: '1');
} elseif (!empty($raw_store_id) && intval($raw_store_id) > 0) {
    $user_role_home = "menu.php?store_id=" . intval($raw_store_id)
        . (!empty($shop_name_param) ? "&shop_name=" . urlencode($shop_name_param) : "")
        . (!empty($token_param) ? "&token=" . urlencode($token_param) : "")
        . (!empty($table_number) ? "&table=" . urlencode($table_number) : "");
} elseif (!empty($_SESSION['super_admin_logged_in'])) {
    $user_role_home = 'platform-admin.php';
} elseif (!empty($_SESSION['store_id']) || !empty($_SESSION['shop_admin_id'])) {
    $user_role_home = 'store-admin.php';
} else {
    $user_role_home = 'javascript:history.back()';
}

$error_msg = '';
$store_id = intval($raw_store_id);
$shop_info = null;
$active_shops = [];

try {
    if ($store_id > 0) {
        $stmt_shop = $pdo->prepare("SELECT store_id as id, store_name as name, address, category FROM tenants WHERE store_id = :id AND status = 'active'");
        $stmt_shop->execute([':id' => $store_id]);
        $shop_info = $stmt_shop->fetch();
    }

    if ($shop_info) {
        // 1. Fetch pending orders (currently cooking)
        $stmt_pending = $pdo->prepare("SELECT id, table_number, created_at FROM orders WHERE status IN ('pending', 'preparing') AND store_id = :store_id ORDER BY created_at ASC");
        $stmt_pending->execute([':store_id' => $store_id]);
        $pending_orders = $stmt_pending->fetchAll();

        // 2. Fetch ready orders (ready for customer pickup)
        $stmt_ready = $pdo->prepare("SELECT id, table_number, created_at FROM orders WHERE status IN ('ready', 'served') AND store_id = :store_id ORDER BY created_at DESC LIMIT 15");
        $stmt_ready->execute([':store_id' => $store_id]);
        $ready_orders = $stmt_ready->fetchAll();
    } else {
        $stmt_active = $pdo->query("SELECT store_id as id, store_name as name, category, address FROM tenants WHERE status = 'active' ORDER BY store_id DESC");
        $active_shops = $stmt_active->fetchAll();
        $pending_orders = [];
        $ready_orders = [];
    }
} catch (PDOException $e) {
    $pending_orders = [];
    $ready_orders = [];
    $error_msg = "ไม่สามารถเชื่อมโยงระบบบอร์ดแสดงสถานะคิวได้: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CMTC Tech Solution - บอร์ดแสดงสถานะคิวอาหาร</title>
    <link rel="stylesheet" href="style.css">
    <!-- SweetAlert2 CDN -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Navigation Sound & SweetAlert Engine -->
    <script src="js/nav_sound_swal.js"></script>
    <style>
        .queue-container {
            display: flex;
            gap: 25px;
            flex-wrap: wrap;
            margin-top: 20px;
        }
        .queue-column {
            flex: 1;
            min-width: 300px;
            background-color: #FFFFFF;
            border: 2px solid var(--border-color);
            padding: 20px;
        }
        .queue-column.ready-col {
            border-color: var(--success-color);
            background-color: #F6FFF8;
        }
        .queue-column-header {
            font-size: 20px;
            font-weight: 800;
            padding-bottom: 12px;
            margin-bottom: 20px;
            border-bottom: 3px double var(--border-color);
            text-align: center;
        }
        .queue-column.ready-col .queue-column-header {
            color: var(--success-color);
            border-bottom-color: var(--success-color);
        }
        .queue-column.pending-col .queue-column-header {
            color: var(--primary-color);
            border-bottom-color: var(--primary-color);
        }
        .queue-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 15px;
        }
        .queue-badge {
            background-color: var(--bg-light);
            border: 1px solid var(--border-color);
            padding: 15px 10px;
            text-align: center;
            font-size: 16px;
            font-weight: 700;
            color: var(--text-primary);
        }
        .queue-badge.pulse {
            background-color: #D4EDDA;
            border: 2px solid var(--success-color);
            color: var(--success-color);
            font-size: 18px;
            animation: pulse-border 1.5s infinite;
        }
        .queue-badge small {
            display: block;
            font-size: 10px;
            color: var(--text-secondary);
            font-weight: 500;
            margin-top: 3px;
        }
        .queue-badge.pulse small {
            color: #155724;
            font-weight: 700;
        }
        
        @keyframes pulse-border {
            0% {
                box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.4);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(40, 167, 69, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(40, 167, 69, 0);
            }
        }
    </style>
</head>
<body>

<!-- Global Fixed Navigation Bar -->
<nav class="global-navbar">
    <a href="<?php echo htmlspecialchars($user_role_home); ?>" class="navbar-brand">
        <img src="logo.png" class="navbar-logo" alt="Logo" style="width: 35px; height: 35px; object-fit: contain; border-radius: 50%;">
        <span class="navbar-title">สถานะคิว • CMTC Tech Solution</span>
    </a>
    <div class="navbar-nav">
        <a href="javascript:void(0)" onclick="handleGoBack(); return false;" class="btn btn-navbar-ghost">← ย้อนกลับ</a>
        <a href="<?php echo htmlspecialchars($user_role_home); ?>" class="btn btn-navbar-ghost">🏠 หน้าแรก</a>
    </div>
</nav>

<div class="wrapper" style="flex-direction: column;">
    <!-- Institutional Header -->
    <header class="gov-banner">
        <div class="gov-banner-title">
            <a href="<?php echo htmlspecialchars($user_role_home); ?>" title="กลับสู่หน้าแรกหลัก" style="text-decoration: none; color: inherit; display: block;">
                <div class="gov-title-text" style="cursor: pointer;">
                    <?php if ($shop_info): ?>
                        <h1>สถานะคิวอาหาร - <?php echo htmlspecialchars($shop_info['name']); ?></h1>
                        <p>บอร์ดความคืบหน้าการปรุงคิวอาหารสด • 📍 <?php echo htmlspecialchars($shop_info['address'] ?? 'ส่วนบริการลูกค้า'); ?></p>
                    <?php else: ?>
                        <h1>ระบบแสดงผลคิว CMTC Tech Solution</h1>
                        <p>ระบบบริหารจัดการร้านอาหาร CMTC Tech Solution • บอร์ดความคืบหน้าการปรุงคิว</p>
                    <?php endif; ?>
                </div>
            </a>
        </div>
        <div>
            <span class="system-badge" style="background: var(--success-color); color: #fff;">LIVE QUEUE MONITOR</span>
        </div>
    </header>

    <div class="page-container">
        
        <!-- Breadcrumbs Navigation -->
        <div class="breadcrumbs">
            <a href="<?php echo htmlspecialchars($user_role_home); ?>">หน้าแรก</a>
            <span>&gt;</span>
            <a href="status.php">บอร์ดแสดงสถานะคิว</a>
            <?php if ($shop_info): ?>
                <span>&gt;</span>
                <span><?php echo htmlspecialchars($shop_info['name']); ?></span>
            <?php endif; ?>
        </div>

        <?php if ($error_msg): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error_msg); ?></div>
        <?php endif; ?>

        <?php if (!$shop_info): ?>
            <!-- Shop Directory Layout -->
            <div style="max-width: 900px; margin: 40px auto; font-family: var(--font-official);">
                <div style="text-align: center; margin-bottom: 45px;">
                    <span style="font-size: 50px;">🖥️</span>
                    <h2 style="font-size: 26px; font-weight: 800; color: var(--primary-color); margin-top: 15px;">เลือกดูบอร์ดแสดงคิวของร้านค้า</h2>
                    <p style="color: var(--text-secondary); font-size: 14.5px; margin-top: 5px;">เลือกเปิดบอร์ดแสดงสถานะคิวรับอาหารสดเรียลไทม์ (Live Queue Board) ของร้านอาหารที่ท่านต้องการสั่งซื้อหรือรอคิว</p>
                </div>

                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 25px;">
                    <?php if (empty($active_shops)): ?>
                        <div style="grid-column: 1/-1; text-align: center; padding: 60px; background: #fff; border: 1px dashed var(--border-color); border-radius: 12px; color: var(--text-secondary);">
                            📭 ขณะนี้ยังไม่มีร้านค้าสมาชิกเปิดให้บริการในระบบหลัก
                        </div>
                    <?php else: ?>
                        <?php foreach ($active_shops as $ash): ?>
                            <div style="background: #ffffff; border: 1px solid var(--border-color); border-radius: 12px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); display: flex; flex-direction: column; justify-content: space-between; transition: transform 0.2s ease;">
                                <div>
                                    <h3 style="font-size: 18px; font-weight: 800; color: var(--primary-color); margin-bottom: 8px;"><?php echo htmlspecialchars($ash['name']); ?></h3>
                                    <?php if (!empty($ash['address'])): ?>
                                        <p style="font-size: 13.5px; color: var(--text-secondary); margin-bottom: 12px; line-height: 1.5;">📍 <?php echo htmlspecialchars($ash['address']); ?></p>
                                    <?php endif; ?>
                                </div>
                                <a href="status.php?store_id=<?php echo $ash['id']; ?>" class="btn btn-primary" style="text-align: center; text-decoration: none; display: block; font-weight: 800; font-size: 14px; padding: 12px 15px; border-radius: 6px;">
                                    🖥️ เปิดดูบอร์ดแสดงคิว
                                </a>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>

        <!-- Queue Status Board Header -->
        <div class="page-header" style="margin-bottom: 10px;">
            <h2>บอร์ดรายงานสถานะคิวรับอาหาร</h2>
            <div style="font-size: 13px; color: var(--text-secondary);">
                ระบบรีเฟรชข้อมูลอัตโนมัติทุกๆ 5 วินาที • เวลาปัจจุบัน: <?php echo date('H:i:s'); ?>
            </div>
        </div>

        <div class="queue-container">
            
            <!-- COLUMN 1: Preparing (กำลังจัดเตรียม) -->
            <div class="queue-column pending-col">
                <div class="queue-column-header">กำลังจัดเตรียม (Preparing)</div>
                <?php if (empty($pending_orders)): ?>
                    <div style="text-align: center; color: var(--text-secondary); padding: 40px;">
                        ไม่มีรายการอาหารที่กำลังปรุงขณะนี้
                    </div>
                <?php else: ?>
                    <div class="queue-grid">
                        <?php foreach ($pending_orders as $order): ?>
                            <div class="queue-badge">
                                โต๊ะ <?php echo htmlspecialchars($order['table_number']); ?>
                                <small>ออเดอร์ #<?php echo $order['id']; ?></small>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- COLUMN 2: Ready for Pickup (พร้อมรับอาหาร) -->
            <div class="queue-column ready-col">
                <div class="queue-column-header">พร้อมรับอาหาร! (Ready for Pickup)</div>
                <?php if (empty($ready_orders)): ?>
                    <div style="text-align: center; color: var(--text-secondary); padding: 40px;">
                        ไม่มีคิวปรุงเสร็จที่รอการรับอาหารในขณะนี้
                    </div>
                <?php else: ?>
                    <div class="queue-grid">
                        <?php foreach ($ready_orders as $order): ?>
                            <div class="queue-badge pulse">
                                โต๊ะ <?php echo htmlspecialchars($order['table_number']); ?>
                                <small>ออเดอร์ #<?php echo $order['id']; ?></small>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

        </div>

        <div style="margin-top: 30px; text-align: center;">
            <?php
                $back_url = 'menu.php?store_id=' . $store_id;
                if (!empty($table_number)) {
                    $back_url .= '&table=' . urlencode($table_number);
                }
            ?>
            <a href="<?php echo htmlspecialchars($back_url); ?>" class="btn btn-ghost">← กลับไปยังหน้าเมนูสั่งอาหาร</a>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Global Footer -->
<footer class="global-footer">
    <div class="footer-brand">CMTC Tech Solution • ระบบแอดมินร้านค้า</div>
    <div class="footer-contact">
        ติดต่อทีมงานบำรุงรักษา: CMTC Support • โทรศัพท์: 02-123-4567 • อีเมล: support@CMTC Tech Solution.cloud
    </div>
</footer>

<script>
    setTimeout(function() {
        location.reload();
    }, 5000);

    // Toggle Bottom Sheet Menu
    function toggleBottomSheet() {
        const sheet = document.getElementById('lpBottomSheet');
        if (sheet) {
            sheet.classList.toggle('open');
        }
    }

    // Handle browser go back safely
    function handleGoBack() {
        if (window.history.length > 1 && document.referrer && document.referrer !== window.location.href) {
            window.history.back();
        } else {
            window.location.href = '<?php echo htmlspecialchars($user_role_home); ?>';
        }
    }
</script>



<!-- Quick Menu Bottom Sheet -->
<div class="lp-bottom-sheet" id="lpBottomSheet">
    <div class="lp-bottom-sheet-backdrop" onclick="toggleBottomSheet()"></div>
    <div class="lp-bottom-sheet-content">
        <div class="lp-bottom-sheet-header">
            <span class="lp-bottom-sheet-title">📂 ทางลัดด่วน CMTC Tech Solution</span>
            <button class="lp-bottom-sheet-close" onclick="toggleBottomSheet()">&times;</button>
        </div>
        <div class="lp-bottom-sheet-grid">
            <a href="<?php echo htmlspecialchars($user_role_home); ?>" class="lp-bottom-sheet-item">
                <span class="lp-bottom-sheet-icon">🏠</span>
                <span class="lp-bottom-sheet-label">หน้าแรก</span>
            </a>
            <a href="menu.php" class="lp-bottom-sheet-item">
                <span class="lp-bottom-sheet-icon">🛒</span>
                <span class="lp-bottom-sheet-label">สั่งอาหาร</span>
            </a>
            <a href="status.php" class="lp-bottom-sheet-item">
                <span class="lp-bottom-sheet-icon">📊</span>
                <span class="lp-bottom-sheet-label">สถานะคิว</span>
            </a>
            <a href="store-admin.php" class="lp-bottom-sheet-item">
                <span class="lp-bottom-sheet-icon">🍳</span>
                <span class="lp-bottom-sheet-label">แอดมินร้านค้า</span>
            </a>
            <a href="platform-admin.php" class="lp-bottom-sheet-item">
                <span class="lp-bottom-sheet-icon">👑</span>
                <span class="lp-bottom-sheet-label">คุมระบบกลาง</span>
            </a>
        </div>
    </div>
</div>

</body>
</html>
