<?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', 'documents_templates',
        'manage_documents', 'manage_photos', 'manage_videos', 'manage_cv_bank', 
        'manage_clients', 'manage_assets', 'manage_files', 'create_activity_report', 
        'supervisor_approval', 'pay_slip'
    ],
    'HR Manager' => [
        'home', 'view_employees', 
        'manage_documents', 'manage_photos', 'manage_videos', 'manage_cv_bank', 'documents_templates',
        'manage_clients', 'manage_assets', 'manage_files', 'create_activity_report', 
        'supervisor_approval'
    ],
    'SOC Engineer' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 'documents_templates',
        'manage_files', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Pentester' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 'documents_templates',
        'manage_files', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Supervisor' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 'documents_templates',
        'manage_files', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Employee' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 'documents_templates',
        'manage_files', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Manager' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 'documents_templates',
        'manage_files', 'create_activity_report', 
        'supervisor_approval'
    ],
	'Markeing Manager' => [
        'home', 
        'manage_documents', 'manage_photos', 'manage_videos', 'documents_templates',
        'manage_files', '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 to Cyberlog Ltd. ', '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_files' => ['title' => 'All File Database', 'file' => 'sections/manage_files.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
    'documents_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 = [
	'manage_documents' => ['title' => 'Documents Database', 'file' => 'sections/manage_documents.php'],
    'manage_photos' => ['title' => 'Photos Database', 'file' => 'sections/manage_photos.php'], 
    'manage_videos' => ['title' => 'Videos Database', 'file' => 'sections/manage_videos.php'], 
    
    'company_letterpad' => ['title' => 'Company Letterpad Generator', 'file' => 'sections/company_letterpad.php'],
	'expense' => ['title' => 'Expense List Generator', 'file' => 'sections/expense.php'], 
	'invoice' => ['title' => 'Invoice Generator', 'file' => 'sections/invoice.php'], 
	'convey_expense' => ['title' => 'Convey Expense List Generator', 'file' => 'sections/convey_expense.php'],
	'completion_certificate' => ['title' => 'Completion Certificate Generator', 'file' => 'sections/completion_certificate.php'],	
	'pay_slip' => ['title' => 'Payslip Generator', 'file' => 'sections/pay_slip.php'],
	'salary_certificate' => ['title' => 'Salary Certificate Generator', 'file' => 'sections/salary_certificate.php'],
	'leave_application' => ['title' => 'Leave Application Generator', 'file' => 'sections/leave_application.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";


// Define logo URL
$logo_url = "logo/logo.png"; 


?>
<!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>
        /* Base Styling */
        body { 
            font-family: 'Arial', sans-serif; 
            margin: 0; 
            background-color: #fafafa; /* Lighter shade of gray */
            color: #333; 
        }
        .dashboard-container { 
            display: flex; 
            min-height: 100vh; 
        }
        
        /* --- Sidebar Styling --- */
        .sidebar { 
            width: 250px; 
            background-color: #343a40; /* Dark Gray Background (for white text contrast) */
            padding: 20px 0; 
            box-shadow: 2px 0 5px rgba(0,0,0,0.1); 
            display: flex;
            flex-direction: column;
            /* Added vertical line - UNCHANGED */
            border-right: 2px solid #2e7d32; 
        }
        
        /* Sidebar Headers & Text (White Color, Bold/Size retained) */
        .sidebar h2 { 
            color: #ffffff; /* White Text */
            text-align: center; 
            margin-top: 0; 
            /* Increased size and made bold */
            font-size: 1.2rem;
            font-weight: bold; 
            background-color: transparent; 
            padding: 10px 0;
            margin-bottom: 5px;
        }
        .sidebar p {
            color: #ffffff; /* White Text */
            text-align: center;
            /* Increased size and made bold */
            font-size: 1.1rem;
            font-weight: bold; 
            background-color: transparent; 
            padding: 5px 0;
            margin-top: -10px;
            margin-bottom: 20px;
        }
        .sidebar nav {
            flex-grow: 1;
        }
        .sidebar nav a { 
            display: block; 
            color: #ffffff; /* White Text */
            font-weight: normal; 
            padding: 15px 20px; 
            text-decoration: none; 
            font-size: 16px; 
            border-left: 5px solid transparent; 
            transition: all 0.3s;
            background-color: transparent; 
            margin: 0; 
            border-radius: 0; 
        }
        /* Hover State: Darker Gray Background, White Text */
        .sidebar nav a:hover { 
            background-color: #495057; /* Darker Gray Hover Background */
            border-left-color: #2ecc71; 
            color: #ffffff; /* White Text on Hover */
        }
        .sidebar nav a.active { 
            background-color: #495057; /* Darker Gray Active Background */
            border-left-color: #2ecc71; 
            color: #ffffff; 
        }

        /* Logout Button Styling (Standard Look - Kept as is) */
        .sidebar .logout-btn {
            padding: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1); /* Adjusted border color for contrast against dark gray BG */
        }
        .sidebar .logout-btn a {
            display: block;
            background-color: #e74c3c; /* Red button */
            color: white;
            padding: 10px;
            text-align: center;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
            transition: background-color 0.3s;
            margin: 0;
        }
        .sidebar .logout-btn a:hover {
            background-color: #c0392b;
        }

        /* --- Main Content Styling --- */
        .main-content { 
            flex-grow: 1; 
            padding: 30px; 
            background-color: #ecf0f1;
            display: flex;
            flex-direction: column;
        }
        
        /* New Logo Header Container - Moved to Right Corner */
        .header-logo-container {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #bdc3c7;
            display: flex;
            justify-content: space-between; /* Pushes logo to the right */
            align-items: flex-start;
        }
        
        /* Title remains on the left */
        .header-logo-container h1 {
            order: 1; 
            flex-grow: 1;
            border-bottom: none;
            padding-bottom: 0;
            margin-bottom: 0;
        }
        
        /* Logo on the right */
        .header-logo-container img {
            order: 2; 
            max-height: 60px; 
            width: auto;
            margin-right: 0;
        }

        /* Content Area that holds the H1 and dynamic content */
        .content-area {
            flex-grow: 1;
        }

        h1 { 
            color: #2c3e50; 
            margin-top: 0;
            margin-bottom: 20px; 
            padding-bottom: 10px; 
            border-bottom: 2px solid #bdc3c7;
            
        }
        /* Adjusted the H1 style to remove duplicate border-bottom */
        .header-logo-container + h1 {
            border-top: none; 
            border-bottom: none;
            margin-top: 0;
            padding-top: 0;
        }
        
        /* 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: 1:px solid #c8e6c9;
            color: #2e7d32; /* Dark green text */
            padding: 20px;
            border-radius: 8px;
            font-size: 1.1rem;
            margin-bottom: 20px; /* Add some space below the welcome box */
        }
        .welcome-box strong {
            color: #1b5e20;
        }

        /* Styling for the added image */
        .home-page-image {
            max-width: 100%; /* Ensure image fits within content area */
            height: auto; /* Maintain aspect ratio */
            display: block; /* Remove extra space below image */
            margin-top: 20px; /* Space above image */
            border-radius: 8px; /* Slightly rounded corners */
            box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* Subtle shadow */
        }
    </style>
</head>
<body>

<div class="dashboard-container">
    
    <div class="sidebar">
        <!-- 5. DYNAMIC SIDEBAR TITLE --><!-- Role/Name section now uses the standard sidebar styling --><div style="margin: 0 0 20px 0; padding: 10px 0;">
            <h2><?php echo htmlspecialchars($user_role); ?></h2>
            <p style="text-align: center; margin-top: -10px; margin-bottom: 0px; font-size: 1.5rem;">
                <strong><?php echo htmlspecialchars($user_name); ?></strong>
            </p>
        </div>
        
        <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>
        <!-- Standard Logout Button --><div class="logout-btn">
            <a href="logout.php">Log Out</a>
        </div>
    </div>

    <div class="main-content">
        <!-- New Logo Placement (Top Right of Body/Main Content) --><div class="header-logo-container">
            <!-- Title moved back to H1 for proper semantic structure --><h1 style="border-bottom: none; padding-bottom: 0;">
                <?php echo htmlspecialchars($current_section['title']); ?>
            </h1>
            <img src="<?php echo $logo_url; ?>" alt="Cyberlog Logo">
        </div>
        
        <div class="content-area"> 
            
            <?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>"; 
                
                // Add the image here, after the welcome box
                echo '<img src="logo/home_image4.png" alt="Team Discussion" class="home-page-image" width="1500" hight="500" >';
            } 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>
</div>

</body>
</html>

