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

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

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager', 'cashier', 'kitchen_staff', 'waiter']);

$csrf = new CSRF();
$csrfToken = $csrf->getToken();

$currentPage = basename($_SERVER['SCRIPT_NAME'] ?? '', '.php');
$baseUrl = getBaseUrl();

$notification = new Notification();
$unreadCount = $notification->getUnreadCount($_SESSION['user_id']);

$user = $auth->user();
$restaurantId = $auth->restaurantId();

$db = Database::getInstance();
$restaurant = $db->query("SELECT * FROM restaurants WHERE id = ?", [$restaurantId])->fetch();
$restaurantSettings = $db->query("SELECT * FROM restaurant_settings WHERE restaurant_id = ?", [$restaurantId])->fetch();
$settings = $restaurantSettings;

if (!$restaurant) {
    redirect($baseUrl . '/login.php');
    exit;
}

$primaryColor = $restaurantSettings['primary_color'] ?? '#E63946';
$secondaryColor = $restaurantSettings['secondary_color'] ?? '#1D3557';
$currency = $restaurant['currency'] ?? 'USD';

$allowedRoles = ['restaurant_admin', 'restaurant_manager', 'cashier', 'kitchen_staff', 'waiter'];
$isAdmin = ($user['role'] === 'restaurant_admin');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo sanitize($csrfToken); ?>">
    <title><?php echo isset($pageTitle) ? sanitize($pageTitle) . ' - ' : ''; ?><?php echo sanitize($restaurant['name']); ?> - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="<?php echo $baseUrl; ?>/restaurant-admin/assets/style.css" rel="stylesheet">
    <style>
        :root {
            --primary: <?php echo sanitize($primaryColor); ?>;
            --secondary: <?php echo sanitize($secondaryColor); ?>;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar">
            <div class="sidebar-header">
                <a href="<?php echo $baseUrl; ?>/restaurant-admin/" class="sidebar-brand">
                    <?php if (!empty($restaurant['logo'])): ?>
                        <img src="<?php echo $baseUrl . '/' . sanitize($restaurant['logo']); ?>" alt="Logo" style="width:32px;height:32px;object-fit:cover;border-radius:6px;">
                    <?php else: ?>
                        <i class="fas fa-utensils"></i>
                    <?php endif; ?>
                    <span><?php echo sanitize($restaurant['name']); ?></span>
                    <small class="text-muted d-block" style="font-size:10px;">Restaurant Admin</small>
                </a>
            </div>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'index' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/">
                        <i class="fas fa-tachometer-alt"></i><span>Dashboard</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'profile' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/profile.php">
                        <i class="fas fa-store"></i><span>Restaurant Profile</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo in_array($currentPage, ['categories']) ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/categories.php">
                        <i class="fas fa-layer-group"></i><span>Categories</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo in_array($currentPage, ['items', 'item_form']) ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/items.php">
                        <i class="fas fa-utensils"></i><span>Menu Items</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'variations' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/variations.php">
                        <i class="fas fa-sliders-h"></i><span>Variations & Add-ons</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'offers' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/offers.php">
                        <i class="fas fa-tags"></i><span>Offers</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'advertisements' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/advertisements.php">
                        <i class="fas fa-ad"></i><span>Advertisements</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo in_array($currentPage, ['qrcodes', 'tables']) ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/tables.php">
                        <i class="fas fa-qrcode"></i><span>QR Codes & Tables</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo in_array($currentPage, ['orders', 'order_detail']) ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/orders.php">
                        <i class="fas fa-receipt"></i><span>Orders</span>
                        <span class="badge bg-danger ms-auto pending-orders-badge" style="display:none;">0</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'kitchen' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/kitchen.php">
                        <i class="fas fa-fire"></i><span>Kitchen</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'customers' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/customers.php">
                        <i class="fas fa-users"></i><span>Customers</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'reports' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/reports.php">
                        <i class="fas fa-chart-bar"></i><span>Reports</span>
                    </a>
                </li>
                <?php if ($isAdmin): ?>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'staff' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/staff.php">
                        <i class="fas fa-user-tie"></i><span>Staff</span>
                    </a>
                </li>
                <?php endif; ?>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'settings' ? 'active' : ''; ?>" href="<?php echo $baseUrl; ?>/restaurant-admin/settings.php">
                        <i class="fas fa-cog"></i><span>Settings</span>
                    </a>
                </li>
            </ul>
        </nav>

        <div id="content" class="content">
            <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm mb-3">
                <div class="d-flex align-items-center">
                    <button type="button" id="sidebarToggle" class="btn btn-sm btn-outline-secondary me-2">
                        <i class="fas fa-bars"></i>
                    </button>
                    <h5 class="mb-0 d-none d-md-block"><?php echo isset($pageTitle) ? sanitize($pageTitle) : 'Dashboard'; ?></h5>
                </div>
                <div class="ms-auto d-flex align-items-center">
                    <div class="dropdown me-2">
                        <a href="#" class="btn btn-sm btn-outline-secondary position-relative" id="notifDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-bell"></i>
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger notification-badge" style="display:<?php echo $unreadCount > 0 ? 'inline-block' : 'none'; ?>">
                                <?php echo $unreadCount; ?>
                            </span>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end notification-dropdown" style="width:320px; max-height:400px; overflow-y:auto;">
                            <h6 class="dropdown-header">Notifications</h6>
                            <div id="notificationList">
                                <div class="text-center p-3 text-muted">Loading...</div>
                            </div>
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item text-center small" href="#" id="markAllRead">Mark all as read</a>
                        </div>
                    </div>
                    <div class="dropdown">
                        <a href="#" class="d-flex align-items-center text-decoration-none dropdown-toggle" data-bs-toggle="dropdown">
                            <div class="avatar-circle me-2"><?php echo strtoupper(substr($user['name'], 0, 1)); ?></div>
                            <span class="d-none d-md-inline"><?php echo sanitize($user['name']); ?></span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="<?php echo $baseUrl; ?>/restaurant-admin/profile.php"><i class="fas fa-store me-2"></i>Restaurant Profile</a></li>
                            <li><a class="dropdown-item" href="<?php echo $baseUrl; ?>/restaurant-admin/settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="<?php echo $baseUrl; ?>/logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </nav>
            <div class="container-fluid">
