<?php
require_once 'config/database.php';
require_once 'config/session.php';

// Redirect if not logged in
redirectIfNotLoggedIn();

// Check session timeout
checkSessionTimeout();

// Get page parameter
$page = isset($_GET['page']) ? $_GET['page'] : 'overview';

// Check if user has access to this page
if (!checkPageAccess($page)) {
    echo "<div class='container mt-5'>
            <div class='alert alert-danger'>
                <h4><i class='bi bi-shield-exclamation'></i> Access Denied</h4>
                <p>You don't have permission to access this page.</p>
                <a href='dashboard.php' class='btn btn-primary'>Go to Dashboard</a>
            </div>
          </div>";
    exit();
}

// Get pending approvals count for admin
$pending_approvals = 0;
if ($_SESSION['role'] === 'admin') {
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM users WHERE is_active = 0 AND role = 'employee'");
    $result = $stmt->fetch();
    $pending_approvals = $result['count'] ?? 0;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HR System - <?php echo ucfirst($page); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        #page-content-wrapper {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .navbar {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
            z-index: 1000;
        }
        .sidebar-heading {
            background: linear-gradient(90deg, #0d6efd, #0dcaf0);
            color: white;
        }
        .list-group-item.active {
            background-color: #0d6efd !important;
            border-color: #0d6efd !important;
        }
        .card {
            border-radius: 10px;
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,.075);
            margin-bottom: 1.5rem;
        }
        .card-header {
            background-color: white;
            border-bottom: 1px solid rgba(0,0,0,.125);
            font-weight: 600;
        }
        .alert-fixed {
            position: fixed;
            top: 70px;
            right: 20px;
            z-index: 1050;
            min-width: 300px;
            animation: slideIn 0.3s ease-out;
        }
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        .badge-notification {
            position: absolute;
            top: -5px;
            right: -5px;
            font-size: 0.7rem;
            padding: 0.25rem 0.5rem;
        }
        .notification-dropdown {
            min-width: 300px;
            max-height: 400px;
            overflow-y: auto;
        }
        .notification-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .notification-item.unread {
            background-color: #f8f9fa;
        }
        .notification-item:hover {
            background-color: #e9ecef;
        }
    </style>
</head>
<body>
    <div class="d-flex" id="wrapper">
        <!-- Sidebar -->
        <?php include 'includes/sidebar.php'; ?>
        
        <!-- Page content -->
        <div id="page-content-wrapper">
            <!-- Top navbar -->
            <?php include 'includes/header.php'; ?>
            
            <!-- Main content -->
            <div class="container-fluid px-4 pt-4">
                <!-- Role Indicator -->
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="alert alert-secondary py-2" role="alert">
                            <div class="d-flex justify-content-between align-items-center">
                                <small>
                                    <i class="bi bi-person-badge"></i> 
                                    Logged in as: <strong><?php echo ucfirst($_SESSION['role']); ?></strong>
                                    <?php if(isset($_SESSION['department']) && !empty($_SESSION['department'])): ?>
                                        | Department: <strong><?php echo htmlspecialchars($_SESSION['department']); ?></strong>
                                    <?php endif; ?>
                                    | Session: <?php echo date('h:i A', $_SESSION['login_time']); ?>
                                </small>
                                <small>
                                    <i class="bi bi-clock"></i> 
                                    <?php 
                                    $timeout = $_SESSION['timeout'] ?? (time() + 1800);
                                    $remaining = $timeout - time();
                                    $minutes = floor($remaining / 60);
                                    echo "Auto logout in: " . $minutes . " min";
                                    ?>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Pending Approvals Alert for Admin -->
                <?php if ($_SESSION['role'] === 'admin' && $pending_approvals > 0 && $page !== 'pending_approvals'): ?>
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="alert alert-warning alert-dismissible fade show">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="bi bi-exclamation-triangle"></i>
                                    <strong>You have <?php echo $pending_approvals; ?> pending registration(s) waiting for approval.</strong>
                                </div>
                                <div>
                                    <a href="dashboard.php?page=pending_approvals" class="btn btn-sm btn-warning">Review Now</a>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
               <!-- Page Content -->
                <?php
                // Load page based on URL parameter with role-based checks
                $module_path = "modules/{$page}/index.php";
                
                if (file_exists($module_path)) {
                    include $module_path;
                } else {
                    // Check if it's a core module
                    switch($page) {
                        case 'overview':
                            include 'modules/overview.php';
                            break;
                        case 'profile':
                            include 'modules/profile.php';
                            break;
                        case 'users':
                            if (hasPermission('manage_users')) {
                                include 'modules/users/index.php';
                            } else {
                                echo "<div class='alert alert-danger'>Access Denied</div>";
                            }
                            break;
                        case 'departments':
                            if (hasPermission('manage_departments')) {
                                include 'modules/departments/index.php';
                            } else {
                                echo "<div class='alert alert-danger'>Access Denied</div>";
                            }
                            break;
                        case 'settings':
                            if (isAdmin()) {
                                include 'modules/settings/index.php';
                            } else {
                                echo "<div class='alert alert-danger'>Access Denied</div>";
                            }
                            break;
                        case 'pending_approvals':
                            if (isAdmin()) {
                                include 'modules/users/pending_approvals.php';
                            } else {
                                echo "<div class='alert alert-danger'>Access Denied</div>";
                            }
                            break;

                            // dashboard.php හි
// Add to the switch statement
case 'leave':
    if (hasPermission('apply_leaves') || hasPermission('manage_leaves')) {
        include 'modules/leave/index.php';
    } else {
        echo "<div class='alert alert-danger'>Access Denied</div>";
    }
    break;
                            // Add to the switch statement
case 'salary_update':
    if (hasPermission('manage_salary')) {
        include 'modules/employees/salary_update.php';
    } else {
        echo "<div class='alert alert-danger'>Access Denied</div>";
    }
    break;
                        default:
                            echo "<div class='alert alert-warning'>Page not found</div>";
                    }
                }
                ?>
            </div>
            
            <!-- Footer -->
            <?php include 'includes/footer.php'; ?>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Custom Scripts -->
    <script src="assets/js/script.js"></script>
    
    <script>
        // Toggle sidebar
        document.addEventListener('DOMContentLoaded', function() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.getElementById('sidebar-wrapper');
            
            if(sidebarToggle && sidebar) {
                sidebarToggle.addEventListener('click', function() {
                    const currentMargin = sidebar.style.marginLeft || getComputedStyle(sidebar).marginLeft;
                    
                    if(currentMargin === '0px' || currentMargin === '' || currentMargin === '0') {
                        sidebar.style.marginLeft = '-300px';
                    } else {
                        sidebar.style.marginLeft = '0px';
                    }
                });
            }
            
            // Auto-hide sidebar on mobile
            function checkWindowSize() {
                if (window.innerWidth < 768) {
                    sidebar.style.marginLeft = '-300px';
                } else {
                    sidebar.style.marginLeft = '0px';
                }
            }
            
            window.addEventListener('resize', checkWindowSize);
            checkWindowSize();
            
            // Real-time clock
            function updateClock() {
                const now = new Date();
                const clockElement = document.getElementById('liveClock');
                if(clockElement) {
                    clockElement.textContent = now.toLocaleTimeString();
                }
            }
            setInterval(updateClock, 1000);
            updateClock();
            
            // Session timeout warning
            let timeoutWarningShown = false;
            function checkSessionTimeout() {
                const timeout = <?php echo ($_SESSION['timeout'] ?? (time() + 1800)) * 1000; ?>;
                const now = Date.now();
                const remaining = timeout - now;
                
                if (remaining < 300000 && !timeoutWarningShown) { // 5 minutes
                    timeoutWarningShown = true;
                    showTimeoutWarning(Math.floor(remaining / 60000));
                }
                
                if (remaining < 0) {
                    window.location.href = 'logout.php?timeout=1';
                }
            }
            
            function showTimeoutWarning(minutes) {
                const warning = document.createElement('div');
                warning.className = 'alert alert-warning alert-fixed';
                warning.innerHTML = `
                    <i class="bi bi-clock"></i> 
                    <strong>Session Expiring Soon!</strong><br>
                    Your session will expire in ${minutes} minutes.
                    <button class="btn btn-sm btn-outline-warning float-end" onclick="extendSession()">
                        Extend Session
                    </button>
                `;
                document.body.appendChild(warning);
                
                setTimeout(() => {
                    warning.remove();
                }, 10000);
            }
            
            window.extendSession = function() {
                fetch('ajax/extend_session.php')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            timeoutWarningShown = false;
                            document.querySelector('.alert-fixed')?.remove();
                            showSuccess('Session extended successfully!');
                        }
                    });
            };
            
            function showSuccess(message) {
                const success = document.createElement('div');
                success.className = 'alert alert-success alert-fixed';
                success.innerHTML = `
                    <i class="bi bi-check-circle"></i> ${message}
                `;
                document.body.appendChild(success);
                
                setTimeout(() => {
                    success.remove();
                }, 3000);
            }
            
            // Check session every minute
            setInterval(checkSessionTimeout, 60000);
            checkSessionTimeout();
            
            // Auto-refresh page every 10 minutes to prevent session timeout
            setTimeout(() => {
                window.location.reload();
            }, 600000);
            
            // Highlight active page in sidebar
            const currentPage = '<?php echo $page; ?>';
            const sidebarLinks = document.querySelectorAll('.list-group-item');
            sidebarLinks.forEach(link => {
                const href = link.getAttribute('href');
                if (href && href.includes(currentPage)) {
                    link.classList.add('active');
                }
            });
            
            // Handle notifications
            function loadNotifications() {
                fetch('ajax/get_notifications.php')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.notifications.length > 0) {
                            updateNotificationBadge(data.unread_count);
                            updateNotificationDropdown(data.notifications);
                        }
                    });
            }
            
            function updateNotificationBadge(count) {
                const badge = document.getElementById('notificationBadge');
                if (badge) {
                    badge.textContent = count;
                    badge.style.display = count > 0 ? 'inline-block' : 'none';
                }
            }
            
            function updateNotificationDropdown(notifications) {
                const dropdown = document.getElementById('notificationDropdown');
                if (dropdown) {
                    dropdown.innerHTML = '';
                    notifications.forEach(notification => {
                        const item = document.createElement('a');
                        item.className = `dropdown-item notification-item ${notification.unread ? 'unread' : ''}`;
                        item.href = '#';
                        item.innerHTML = `
                            <div class="d-flex w-100 justify-content-between">
                                <strong>${notification.title}</strong>
                                <small>${notification.time}</small>
                            </div>
                            <p class="mb-0">${notification.message}</p>
                        `;
                        dropdown.appendChild(item);
                    });
                }
            }
            
            // Load notifications on page load
            loadNotifications();
            
            // Refresh notifications every 30 seconds
            setInterval(loadNotifications, 30000);
        });
    </script>
</body>
</html>