<?php
// START SESSION AND AUTHENTICATION CHECK
session_start();

// --- 1. AUTHENTICATION CHECK (UPDATED) ---
// Redirect non-logged-in users to the login page if not authenticated
// Assuming successful login sets $_SESSION['user_id'] and $_SESSION['role']
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// Get the user's role and name from the session
$user_role = $_SESSION['role'] ?? 'Guest'; // Default to 'Guest' if role is missing
$user_name = $_SESSION['username'] ?? 'User';

// Include Database Connection
require_once 'config/db_connection.php';

// Determine which section to load based on the 'page' URL parameter
$page = $_GET['page'] ?? 'home';

// --- 2. DEFINE ALL SECTIONS AND PERMISSIONS ---

// Define which roles can see which sections (mapped by key)
// This is the core logic for filtering the sidebar.
$role_permissions = [
    'Admin' => [
        'home', 'upload_confidential', 'manage_users', 'view_employees', 
        'manage_documents', 'manage_photos', 'manage_videos', 'manage_cv_bank', 
        'manage_clients', 'manage_assets', 'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
    'HR Manager' => [
        'home', 'view_employees', 
        'manage_documents', 'manage_photos', 'manage_videos', 'manage_cv_bank', 
        'manage_clients', 'manage_assets', 'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
    'SOC Engineer' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 
        'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Pentester' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 
        'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Supervisor' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 
        'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Employee' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 
        'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Manager' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 
        'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Markeing Manager' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 
        'manage_templates', 'create_activity_report', 
        'supervisor_approval'
    ],
    // Add more roles as needed
    'Guest' => ['home'],
];

// --- VISIBLE SECTIONS (Used to build the Sidebar Navigation) ---
$allowed_sections = [
    'home' => ['title' => 'Welcome', 'file' => null], // Default content
    'upload_confidential' => ['title' => 'Confidential Files', 'file' => 'sections/upload_confidential.php'], // Section 1 - Admin Only
    'manage_users' => ['title' => 'Create User', 'file' => 'sections/manage_users.php'], // Section 2 - Admin Only
    'view_employees' => ['title' => 'Employee Database', 'file' => 'sections/view_employees.php'], // Section 3 - HR/Admin
    'manage_documents' => ['title' => 'Documents Database', 'file' => 'sections/manage_documents.php'], // Section 4 - HR/Admin
    'manage_photos' => ['title' => 'Photos Database', 'file' => 'sections/manage_photos.php'], // Section 5 - HR/Admin
    'manage_videos' => ['title' => 'Videos Database', 'file' => 'sections/manage_videos.php'], // Section 6 - HR/Admin
    'manage_cv_bank' => ['title' => 'CV Bank Management', 'file' => 'sections/manage_cv_bank.php'], // Section 7 - HR/Admin
    'manage_clients' => ['title' => 'All Clients', 'file' => 'sections/manage_clients.php'], // Section 8 - HR/Admin
    'manage_assets' => ['title' => 'Asset Management', 'file' => 'sections/manage_assets.php'], // Section 9 - SOC/Admin
    'manage_templates' => ['title' => 'Document Templates', 'file' => 'sections/document_maker.php'], // Section 10 - HR/Admin
    'create_activity_report' => ['title' => 'Create Activity Report', 'file' => 'sections/create_activity_report.php'], //Section 11 - All Logged In
    'supervisor_approval' => ['title' => 'Files To Approve', 'file' => 'sections/supervisor_approval.php'], //Section 12 - HR/Admin
];

// --- HIDDEN SECTIONS (Accessible via direct link/button, but NOT in sidebar) ---
$hidden_sections = [
    'company_letterpad' => ['title' => 'Company Letterpad Generator', 'file' => 'sections/company_letterpad.php'],
];

// --- COMBINE BOTH ARRAYS FOR COMPLETE ROUTING LOGIC ---
$all_sections = array_merge($allowed_sections, $hidden_sections);


// --- 3. FILTER THE SECTIONS FOR THE CURRENT USER ---

$user_allowed_keys = $role_permissions[$user_role] ?? $role_permissions['Guest'];
$user_allowed_sections = [];

// Populate the filtered list by checking against the permission map
foreach ($allowed_sections as $key => $section) {
    if (in_array($key, $user_allowed_keys)) {
        $user_allowed_sections[$key] = $section;
    }
}


// --- 4. AUTHORIZATION CHECK FOR CONTENT LOADING (CORRECTED) ---

// Check if the requested $page is in the current user's authorized sections OR hidden sections
// Note: array_key_exists is used for hidden sections because they shouldn't be in $user_allowed_keys
if (!in_array($page, $user_allowed_keys) && !array_key_exists($page, $hidden_sections)) {
    // If the user is trying to access a page they are not permitted to see,
    // fallback to the 'unauthorized' page to display the error message.
    $page = 'unauthorized'; 
}


// Set the current section details based on the authorized $page
// CRITICAL FIX: Add a new dummy section for 'unauthorized' access handling
if ($page === 'unauthorized') {
    $current_section = ['title' => 'Access Restricted', 'file' => null];
    $content_file = null;
} else {
    $current_section = $all_sections[$page] ?? $allowed_sections['home']; // Fallback to 'home' if page is missing
    $content_file = $current_section['file'];
}


$page_title = $current_section['title'] . " | CyberLog 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 $page_title; ?></title>
    <style>
        body { font-family: 'Arial', sans-serif; margin: 0; background-color: #f4f7f6; color: #333; }
        .dashboard-container { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background-color: #2c3e50; padding: 20px 0; box-shadow: 2px 0 5px rgba(0,0,0,0.1); }
        .sidebar h2 { color: #ecf0f1; text-align: center; margin-bottom: 30px; }
        .sidebar nav a { 
            display: block; 
            color: #ecf0f1; 
            padding: 15px 20px; 
            text-decoration: none; 
            font-size: 16px; 
            border-left: 5px solid transparent; 
            transition: all 0.3s;
        }
        .sidebar nav a:hover { 
            background-color: #34495e; 
            border-left-color: #3498db; 
        }
        .sidebar nav a.active { 
            background-color: #34495e; 
            border-left-color: #2ecc71; 
            font-weight: bold;
        }
        .sidebar .logout-btn {
            display: block; 
            margin-top: 40px;
            text-align: center;
        }
        .main-content { 
            flex-grow: 1; 
            padding: 30px; 
            background-color: #ecf0f1;
        }
        .form-card { 
            background-color: #fff; 
            padding: 25px; 
            border-radius: 10px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.05); 
            margin-bottom: 20px;
        }
        h1 { color: #2c3e50; margin-bottom: 20px; border-bottom: 2px solid #bdc3c7; padding-bottom: 10px; }
        /* Form styling */
        label { display: block; margin-top: 15px; font-weight: bold; color: #34495e; }
        input[type="text"], input[type="password"], input[type="email"], select {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }
        button[type="submit"] {
            background-color: #3498db;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 20px;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        button[type="submit"]:hover {
            background-color: #2980b9;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .data-table th, .data-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }
        .data-table th {
            background-color: #f2f2f2;
            color: #333;
        }
        /* Custom welcome box styling */
        .welcome-box {
            background-color: #e8f5e9; /* Light green/success color */
            border: 1px solid #c8e6c9;
            color: #2e7d32; /* Dark green text */
            padding: 20px;
            border-radius: 8px;
            font-size: 1.1rem;
        }
        .welcome-box strong {
            color: #1b5e20;
        }
    </style>
</head>
<body>

<div class="dashboard-container">
    
    <div class="sidebar">
        <!-- 5. DYNAMIC SIDEBAR TITLE -->
        <h2><?php echo htmlspecialchars($user_role); ?></h2>
        <p style="color: #bdc3c7; text-align: center; margin-top: -20px; margin-bottom: 30px; font-size: 0.9rem;">
           <strong><?php echo htmlspecialchars($user_name); ?></strong>
        </p>
        <nav>
            <!-- 6. DYNAMIC NAVIGATION LOOP -->
            <?php foreach ($user_allowed_sections as $key => $section): ?>
                <a href="admin_dashboard.php?page=<?php echo $key; ?>" 
                    class="<?php echo ($page == $key) ? 'active' : ''; ?>">
                    <?php echo htmlspecialchars($section['title']); ?>
                </a>
            <?php endforeach; ?>
        </nav>
        <div class="logout-btn">
             <a href="logout.php" style="color: #e74c3c; text-decoration: none; font-weight: bold;">Log Out</a>
        </div>
    </div>

    <div class="main-content">
        <h1><?php echo htmlspecialchars($current_section['title']); ?></h1>
        
        <?php
        // --- Dynamic Content Inclusion (Checks against $all_sections for file access) ---
        if ($content_file && file_exists($content_file)) {
            // Include the specific section file (e.g., sections/manage_users.php)
            require_once $content_file;
        } elseif ($page === 'home') {
            // Default home content (UPDATED for dynamic role)
            echo "<div class='form-card welcome-box'>";
            echo "<h2>Welcome, " . htmlspecialchars($user_name) . "!</h2>";
            echo "<p>You are logged in with the <strong>" . htmlspecialchars($user_role) . "</strong> role.</p>";
            echo "<p>Use the navigation panel on the left to access the management tools relevant to your permissions.</p>";
            echo "<p>If you need access to different sections, please contact your system administrator.</p>";
            echo "</div>";
        } elseif ($page === 'unauthorized') {
            // Unauthorized access message
            echo "<div class='form-card' style='background-color: #fbecec; border: 1px solid #e74c3c;'>";
            echo "<h2>Access Restricted</h2>";
            echo "<p>You do not have permission to view the requested page. This area is reserved for users with different access levels.</p>";
            echo "<p>Please choose an allowed section from your sidebar navigation.</p>";
            echo "</div>";
        } else {
             // Handle files that are placeholders OR files that were not found.
            echo "<div class='form-card'>";
            echo "<h2>Work in Progress</h2>";
            
            if ($content_file && !file_exists($content_file)) {
                 echo "<p style='color: red; font-weight: bold;'>ERROR: File not found at path: " . htmlspecialchars($content_file) . "</p>";
                 echo "<p>Please ensure the section file exists in the correct directory (e.g., sections/manage_users.php).</p>";
            } else {
                 echo "<p>The <b>" . htmlspecialchars($current_section['title']) . "</b> section is currently under development. Please check back later!</p>";
            }
            
            echo "</div>";
        }
        ?>
    </div>
</div>

</body>
</html>
