<?php
/**
 * Enterprise HRM ERP System - Header Template
 * Excel-like UI with tables
 */

if (!defined('HRM_ACCESS')) {
    die('Direct access not allowed');
}

requireLogin();

$pageTitle = isset($pageTitle) ? $pageTitle : 'Dashboard';
$currentModule = isset($currentModule) ? $currentModule : 'dashboard';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - <?php echo getSetting('SYSTEM_NAME', APP_NAME); ?></title>
    <link rel="stylesheet" href="<?php echo assetUrl('assets/css/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo assetUrl('assets/css/table.css'); ?>">
</head>
<body>
    <div class="app-container">
        <!-- Mobile Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay" onclick="closeMobileSidebar()"></div>
        
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <h2><?php echo getSetting('SYSTEM_NAME', APP_NAME); ?></h2>
                <p class="site-info"><?php echo htmlspecialchars($_SESSION['site_name'] ?? 'Site'); ?></p>
            </div>
            
            <nav class="sidebar-nav">
                <ul>
                    <li class="<?php echo $currentModule === 'dashboard' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/dashboard.php">
                            <span class="icon">📊</span> Dashboard
                        </a>
                    </li>
                    <li class="<?php echo $currentModule === 'employee' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/employee/list.php">
                            <span class="icon">👥</span> Employees
                        </a>
                    </li>
                    <li class="<?php echo $currentModule === 'leave' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/leave/list.php">
                            <span class="icon">📅</span> Leave Management
                        </a>
                    </li>
                    <?php 
                    // Get pending leave count for Admin/HR
                    $pendingLeaveCount = 0;
                    if (isSuperAdmin() || isHRAdmin()) {
                        try {
                            $db = getDB();
                            $siteIdForLeave = getCurrentSiteId();
                            if (isSuperAdmin()) {
                                $stmtLeave = $db->prepare("SELECT COUNT(*) FROM leave_applications WHERE site_id = ? AND application_status = 'pending'");
                                $stmtLeave->execute([$siteIdForLeave]);
                            } else {
                                $userIdForLeave = getCurrentUserId();
                                $stmtLeave = $db->prepare("
                                    SELECT COUNT(*) FROM leave_applications la
                                    INNER JOIN employees e ON la.employee_id = e.employee_id
                                    WHERE la.site_id = ? AND la.application_status = 'pending'
                                    AND e.created_by = ?
                                ");
                                $stmtLeave->execute([$siteIdForLeave, $userIdForLeave]);
                            }
                            $pendingLeaveCount = $stmtLeave->fetchColumn();
                        } catch (Exception $e) {
                            $pendingLeaveCount = 0;
                        }
                    }
                    ?>
                    <?php if (isSuperAdmin() || isHRAdmin()): ?>
                    <li class="<?php echo $currentModule === 'leave_approvals' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/leave/approvals.php" class="approval-link">
                            <span class="icon">✅</span> Leave Approvals
                            <?php if ($pendingLeaveCount > 0): ?>
                            <span class="sidebar-badge blink-badge"><?php echo $pendingLeaveCount; ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="<?php echo $currentModule === 'payroll' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/payroll/home.php">
                            <span class="icon">💰</span> Payroll
                        </a>
                    </li>
                    <li class="<?php echo $currentModule === 'overtime' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/overtime/list.php">
                            <span class="icon">⏱️</span> Overtime
                        </a>
                    </li>
                    <!-- Stock Group with Dropdown -->
                    <?php 
                    $isStockGroupActive = in_array($currentModule, ['petty_cash', 'dfc', 'fortnight', 'mis']);
                    // Always start closed - user must click to open
                    $stockGroupOpen = '';
                    ?>
                    <li class="sidebar-dropdown <?php echo $stockGroupOpen; ?> <?php echo $isStockGroupActive ? 'active' : ''; ?>">
                        <a href="javascript:void(0);" class="dropdown-toggle" onclick="toggleStockGroup(event)">
                            <span class="icon">📦</span> Stock Group
                            <span class="dropdown-arrow">▼</span>
                        </a>
                        <ul class="dropdown-menu" id="stockGroupMenu" style="display: none;">
                            <li class="<?php echo $currentModule === 'petty_cash' ? 'active' : ''; ?>">
                                <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php">
                                    <span class="icon">💵</span> Petty Cash
                                </a>
                            </li>
                            <li class="<?php echo $currentModule === 'dfc' ? 'active' : ''; ?>">
                                <a href="<?php echo BASE_URL; ?>/modules/dfc/list.php">
                                    <span class="icon">🍽️</span> SSA
                                </a>
                            </li>
                            <li class="<?php echo $currentModule === 'fortnight' ? 'active' : ''; ?>">
                                <a href="<?php echo BASE_URL; ?>/modules/fortnight/list.php">
                                    <span class="icon">📦</span> Fortnight
                                </a>
                            </li>
                            <?php if (hasPermission('REPORTS_VIEW')): ?>
                            <li class="<?php echo $currentModule === 'mis' ? 'active' : ''; ?>">
                                <a href="<?php echo BASE_URL; ?>/modules/mis/index.php">
                                    <span class="icon">📊</span> MIS Reports
                                </a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </li>
                    <li class="<?php echo $currentModule === 'transfer' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/transfer/list.php">
                            <span class="icon">🔄</span> Transfer
                        </a>
                    </li>
                    <li class="<?php echo $currentModule === 'exit' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/exit/list.php">
                            <span class="icon">🚪</span> Exit
                        </a>
                    </li>
                    <?php if (hasPermission('REPORTS_VIEW')): ?>
                    <li class="<?php echo $currentModule === 'reports' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/reports/index.php">
                            <span class="icon">📈</span> Reports
                        </a>
                    </li>
                    <?php endif; ?>
                    <?php if (hasPermission('SETTINGS_VIEW')): ?>
                    <li class="<?php echo $currentModule === 'settings' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/modules/settings/index.php">
                            <span class="icon">⚙️</span> Settings
                        </a>
                    </li>
                    <?php endif; ?>
                    <?php if (isSuperAdmin() || hasPermission('SETTINGS_VIEW')): ?>
                    <li class="<?php echo $currentModule === 'branches' ? 'active' : ''; ?>">
                        <a href="<?php echo BASE_URL; ?>/admin/sites.php">
                            <span class="icon">🏢</span> Branch Management
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
            
            <style>
            /* Stock Group Dropdown Styles */
            .sidebar-dropdown {
                position: relative;
            }
            
            .sidebar-dropdown .dropdown-toggle {
                cursor: pointer;
                user-select: none;
            }
            
            .sidebar-dropdown .dropdown-arrow {
                margin-left: auto;
                font-size: 10px;
                transition: transform 0.3s ease;
            }
            
            .sidebar-dropdown.open .dropdown-arrow {
                transform: rotate(180deg);
            }
            
            .sidebar-dropdown .dropdown-menu {
                list-style: none;
                padding: 0;
                margin: 5px 0 0 0;
                background-color: #1e293b;
                border-radius: 6px;
                overflow: hidden;
            }
            
            .sidebar-dropdown .dropdown-menu li {
                margin: 0;
            }
            
            .sidebar-dropdown .dropdown-menu a {
                padding-left: 45px;
                font-size: 13px;
                padding-top: 10px;
                padding-bottom: 10px;
            }
            
            .sidebar-dropdown .dropdown-menu li.active a {
                background-color: rgba(37, 99, 235, 0.3);
                color: var(--white);
            }
            
            .sidebar-dropdown.active > .dropdown-toggle {
                background-color: var(--primary-color);
                color: var(--white);
            }
            
            /* Sidebar Badge for Pending Approvals */
            .sidebar-badge {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                min-width: 22px;
                height: 22px;
                padding: 0 6px;
                background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
                color: white;
                font-size: 11px;
                font-weight: 700;
                border-radius: 11px;
                margin-left: auto;
            }
            
            .blink-badge {
                animation: sidebar-blink 1s ease-in-out infinite;
            }
            
            @keyframes sidebar-blink {
                0%, 100% { 
                    opacity: 1; 
                    transform: scale(1);
                    box-shadow: 0 0 8px rgba(238, 90, 36, 0.6);
                }
                50% { 
                    opacity: 0.7; 
                    transform: scale(1.1);
                    box-shadow: 0 0 15px rgba(238, 90, 36, 1);
                }
            }
            
            .approval-link {
                display: flex !important;
                align-items: center;
                justify-content: flex-start;
            }
            
            .approval-link .icon {
                flex-shrink: 0;
            }
            
            .approval-link .sidebar-badge {
                margin-left: auto;
            }
            </style>
            
            <script>
            function toggleStockGroup(event) {
                event.preventDefault();
                event.stopPropagation();
                
                const dropdown = event.currentTarget.closest('.sidebar-dropdown');
                const menu = document.getElementById('stockGroupMenu');
                
                if (dropdown && menu) {
                    const isOpen = dropdown.classList.contains('open');
                    
                    if (isOpen) {
                        dropdown.classList.remove('open');
                        menu.style.display = 'none';
                    } else {
                        dropdown.classList.add('open');
                        menu.style.display = 'block';
                    }
                }
            }
            
            // Mobile Sidebar Toggle Functions
            function toggleMobileSidebar() {
                const sidebar = document.getElementById('sidebar');
                const overlay = document.getElementById('sidebarOverlay');
                
                if (sidebar && overlay) {
                    sidebar.classList.toggle('open');
                    overlay.classList.toggle('active');
                    document.body.style.overflow = sidebar.classList.contains('open') ? 'hidden' : '';
                }
            }
            
            function closeMobileSidebar() {
                const sidebar = document.getElementById('sidebar');
                const overlay = document.getElementById('sidebarOverlay');
                
                if (sidebar && overlay) {
                    sidebar.classList.remove('open');
                    overlay.classList.remove('active');
                    document.body.style.overflow = '';
                }
            }
            
            // Close sidebar when clicking on a link (mobile)
            document.addEventListener('DOMContentLoaded', function() {
                if (window.innerWidth <= 768) {
                    const sidebarLinks = document.querySelectorAll('.sidebar-nav a:not(.dropdown-toggle)');
                    sidebarLinks.forEach(function(link) {
                        link.addEventListener('click', closeMobileSidebar);
                    });
                }
            });
            
            // Close sidebar on window resize if going to desktop
            window.addEventListener('resize', function() {
                if (window.innerWidth > 768) {
                    closeMobileSidebar();
                }
            });
            </script>
            
            <div class="sidebar-footer">
                <div class="user-info">
                    <p><strong><?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?></strong></p>
                    <p class="role"><?php echo htmlspecialchars($_SESSION['role_name'] ?? 'Role'); ?></p>
                </div>
                <a href="<?php echo BASE_URL; ?>/logout.php" class="btn-logout">Logout</a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Bar -->
            <header class="top-bar">
                <!-- Mobile Menu Toggle -->
                <button class="mobile-menu-toggle" id="mobileMenuToggle" onclick="toggleMobileSidebar()" aria-label="Toggle menu">
                    <span></span>
                </button>
                <h1><?php echo htmlspecialchars($pageTitle); ?></h1>
                <div class="top-bar-actions">
                    <?php 
                    require_once __DIR__ . '/site_switcher.php';
                    echo getSiteSwitcher(); 
                    ?>
                    <span class="current-time" id="current-time"></span>
                </div>
            </header>

            <!-- Flash Messages -->
            <?php
            $success = getFlashMessage('success');
            $error = getFlashMessage('error');
            $warning = getFlashMessage('warning');
            $info = getFlashMessage('info');
            ?>
            
            <?php if ($success): ?>
            <div class="alert alert-success">
                <span class="alert-icon">✓</span>
                <span class="alert-message"><?php echo htmlspecialchars($success); ?></span>
            </div>
            <?php endif; ?>
            
            <?php 
            // Skip HTML error messages in header (they're displayed in the page itself to avoid duplicates)
            if ($error && strpos($error, '<a ') === false && strpos($error, '<br') === false): 
            ?>
            <div class="alert alert-error">
                <span class="alert-icon">✗</span>
                <span class="alert-message"><?php echo htmlspecialchars($error); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($warning): ?>
            <div class="alert alert-warning">
                <span class="alert-icon">⚠</span>
                <span class="alert-message"><?php echo htmlspecialchars($warning); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($info): ?>
            <div class="alert alert-info">
                <span class="alert-icon">ℹ</span>
                <span class="alert-message"><?php echo htmlspecialchars($info); ?></span>
            </div>
            <?php endif; ?>

            <!-- Page Content -->
            <div class="content-wrapper">

