<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Prevent session notice if already initialized by an auto-loaded configuration file
if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
    session_write_close();
}

// FORCE WEST AFRICA TIME (WAT) TO MATCH LOGS AND LOCAL TIME EXACTLY
date_default_timezone_set('Africa/Lagos');

// Use require_once to protect global definitions
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$username = $_SESSION['username'] ?? 'User';
$userRole = strtolower(trim($_SESSION['role'] ?? ''));

if (!in_array($userRole, ['admin', 'superadmin','hr'])) {
    die("Access Denied");
}

// Get and Validate Employee ID from GET parameter
$employeeId = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($employeeId <= 0) {
    die("Invalid Employee ID reference.");
}

/*
==========================================================
DATA FETCHING: CORE EMPLOYEE PROFILE WITH JOINS
==========================================================
*/
$sql = "SELECT e.*, d.name as department_name 
        FROM employees e 
        LEFT JOIN departments d ON d.id = e.department_id 
        WHERE e.id = ? 
        LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $employeeId);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();

if (!$employee) {
    die("Operational Error: Targeted employee record could not be found.");
}

// Format Data Cleanly for safe UI presentation
$profileName   = !empty($employee['name']) ? htmlspecialchars($employee['name']) : 'Unnamed Staff';
$profileEmail  = !empty($employee['email']) ? htmlspecialchars($employee['email']) : 'no-email@system.local';
$profilePhone  = !empty($employee['phone']) ? htmlspecialchars($employee['phone']) : 'No Contact Number';
$profileCode   = !empty($employee['employee_no']) ? htmlspecialchars($employee['employee_no']) : 'EMP----';
$deptName      = !empty($employee['department_name']) ? htmlspecialchars($employee['department_name']) : 'Unassigned';
$designation   = !empty($employee['designation']) ? htmlspecialchars($employee['designation']) : 'Staff Force';
$dateHired     = !empty($employee['date_hired']) ? date('F d, Y', strtotime($employee['date_hired'])) : 'Not Registered';
$isManager     = (isset($employee['is_manager']) && $employee['is_manager'] == 1);

/*
==========================================================
DYNAMIC AVATAR PATH RESOLUTION FIX
==========================================================
*/
// Pull stored string (e.g., "uploads/avatars/avatar_1785625517_6a6e7bad13086.jpeg")
$dbAvatar = !empty($employee['avater']) ? trim($employee['avater']) : (!empty($employee['avatar']) ? trim($employee['avatar']) : '');

$profilePhoto = null;

if (!empty($dbAvatar)) {
    // Standardize slashes
    $cleanDbPath = ltrim(str_replace('\\', '/', $dbAvatar), '/');
    
    // Check path relative to root directory
    $systemPath = __DIR__ . '/../' . $cleanDbPath;
    
    if (file_exists($systemPath)) {
        $profilePhoto = '../' . htmlspecialchars($cleanDbPath);
    }
}

// Generate Initials Placeholder
$cleanStr = preg_replace('/^(mr\.|ms\.|mrs\.|dr\.|prof\.)\s+/i', '', trim($profileName));
$words = explode(' ', $cleanStr);
$initials = strtoupper(substr(($words[0] ?? '') . ($words[1] ?? ''), 0, 2));
if(empty($initials)) $initials = 'EE';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Profile - <?= $profileName ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        
        <?php include_once '../components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Toggle Side Area Menu">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">Profile Overview</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">System Identification Verification Scope</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($userRole ?: 'Staff'); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-xs p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div class="flex items-center gap-3">
                        <a href="employees.php" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 px-3 py-1.5 rounded-md text-xs font-bold transition shadow-xs active:scale-[0.98]">
                            ← Back
                        </a>
                        <div>
                            <h2 class="text-xs font-black text-slate-950 uppercase tracking-tight">Record Actions</h2>
                            <p class="text-[10px] text-slate-500 font-semibold">Manage system configuration access</p>
                        </div>
                    </div>
                    
                    <div class="flex items-center gap-2 self-end sm:self-auto">
                        <a href="employee_edit.php?id=<?= $employeeId ?>" class="bg-slate-900 hover:bg-slate-800 text-white px-3 py-1.5 rounded-md text-xs font-bold transition border border-slate-950 shadow-xs active:scale-[0.98]">
                            Edit Record
                        </a>
                        <a href="employee_security.php?id=<?= $employeeId ?>" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 px-3 py-1.5 rounded-md text-xs font-bold transition shadow-xs active:scale-[0.98]">
                            System Access
                        </a>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    
                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-sm flex flex-col items-center text-center space-y-4 h-fit">
                        
                        <!-- EMPLOYEE AVATAR DISPLAY -->
                        <div class="w-20 h-20 rounded-xl border border-slate-300 bg-stone-100 text-slate-800 font-black text-2xl flex items-center justify-center shadow-xs overflow-hidden">
                            <?php if ($profilePhoto): ?>
                                <img src="<?= $profilePhoto ?>" alt="<?= $profileName ?>" class="w-full h-full object-cover">
                            <?php else: ?>
                                <?= $initials ?>
                            <?php endif; ?>
                        </div>
                        
                        <div class="space-y-1">
                            <div class="flex items-center justify-center gap-2 flex-wrap">
                                <h3 class="text-sm font-black text-slate-950 uppercase tracking-tight"><?= $profileName ?></h3>
                                <?php if ($isManager): ?>
                                    <span class="text-[9px] bg-slate-900 text-white px-2 py-0.5 rounded-md font-extrabold uppercase tracking-wider">Manager</span>
                                <?php endif; ?>
                            </div>
                            <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider"><?= $designation ?></p>
                        </div>

                        <div class="w-full space-y-3">
                            <div class="space-y-1 text-left">
                                <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Corporate Designation Title</label>
                                <div class="bg-stone-50/50 border border-slate-300/80 p-2.5 rounded-lg text-xs font-extrabold text-slate-900">
                                    <?= !empty($employee['designation']) ? htmlspecialchars($employee['designation']) : 'Staff Force' ?>
                                </div>
                            </div>

                            <div class="space-y-1 text-left">
                                <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Functional System Position</label>
                                <div class="bg-stone-50/50 border border-slate-300/80 p-2.5 rounded-lg text-xs font-extrabold text-slate-900">
                                    <?= !empty($employee['position']) ? htmlspecialchars($employee['position']) : 'Unspecified Position' ?>
                                </div>
                            </div>
                        </div>

                        <div class="bg-indigo-50 border border-indigo-200 text-indigo-900 font-bold text-[10px] px-3 py-2 rounded-lg font-mono tracking-wide w-full flex justify-between items-center shadow-xs">
                            <span class="text-slate-600 font-sans uppercase text-[9px] font-extrabold">ID Reference:</span> 
                            <span class="font-black text-indigo-950 text-xs"><?= $profileCode ?></span>
                        </div>

                        <div class="w-full border-t border-slate-200/80 pt-3 space-y-2 text-left text-[10px] font-semibold text-slate-500">
                            <div class="flex justify-between items-center">
                                <span class="uppercase tracking-wider font-extrabold">Operational Status</span>
                                <span class="bg-emerald-50 text-emerald-800 border border-emerald-300 px-2 py-0.5 rounded-md font-black text-[9px] uppercase tracking-wide">
                                    ● Active Baseline
                                </span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="uppercase tracking-wider font-extrabold">Onboarding Horizon</span>
                                <span class="text-slate-950 font-mono font-extrabold text-[11px]"><?= $dateHired ?></span>
                            </div>
                        </div>
                    </div>

                    <div class="lg:col-span-2 space-y-6">
                        
                        <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                            <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Personal Data Profile</h3>
                                <span class="text-xs">👤</span>
                            </div>

                            <div class="p-4 sm:p-5 grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div class="space-y-1">
                                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Full Legal Name</label>
                                    <div class="bg-stone-50/50 border border-slate-300/80 p-2.5 rounded-lg text-xs font-extrabold text-slate-950">
                                        <?= $profileName ?>
                                    </div>
                                </div>

                                <div class="space-y-1">
                                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Functional Enterprise Department</label>
                                    <div class="bg-stone-50/50 border border-slate-300/80 p-2.5 rounded-lg text-xs font-extrabold text-slate-950">
                                        <?= $deptName ?>
                                    </div>
                                </div>

                                <div class="space-y-1">
                                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Corporate Email Address</label>
                                    <div class="bg-stone-50/50 border border-slate-300/80 p-2.5 rounded-lg text-xs font-mono font-bold text-slate-950">
                                        <?= $profileEmail ?>
                                    </div>
                                </div>

                                <div class="space-y-1">
                                    <label class="block text-[9px] font-black text-slate-500 uppercase tracking-wider px-0.5">Primary Telephone Assignment</label>
                                    <div class="bg-stone-50/50 border border-slate-300/80 p-2.5 rounded-lg text-xs font-mono font-bold text-slate-950">
                                        <?= $profilePhone ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="bg-gradient-to-br from-slate-900 to-indigo-950 border border-slate-800 rounded-xl p-5 shadow-sm text-white space-y-4">
                            <div class="flex items-center justify-between">
                                <div class="space-y-0.5">
                                    <p class="text-[9px] font-black text-indigo-300 uppercase tracking-widest">Workflow Schema</p>
                                    <h3 class="text-xs font-black text-slate-100 uppercase tracking-tight">Operational Audit Data</h3>
                                </div>
                                <div class="text-lg">🛡️</div>
                            </div>
                            
                            <p class="text-[10px] text-slate-300 font-semibold leading-relaxed">
                                This file record tracks general workforce allocations. Any changes made to security privileges, role adjustments, or shift definitions will log directly to the server audit controller trails.
                            </p>
                            
                            <div class="flex flex-wrap gap-2 pt-1">
                                <span class="bg-white/10 border border-white/20 text-indigo-100 px-2.5 py-1 rounded-md font-mono text-[10px] font-bold">
                                    System ID Ref: <?= intval($employee['id']) ?>
                                </span>
                                <span class="bg-white/10 border border-white/20 text-indigo-100 px-2.5 py-1 rounded-md font-mono text-[10px] font-bold">
                                    Role Scope Flag: <?= htmlspecialchars($employee['role'] ?? 'None Specified') ?>
                                </span>
                            </div>
                        </div>

                    </div>

                </div>

            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <script src="../components/sidebar.js"></script>
    <script>
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if(sidebar) sidebar.classList.toggle('-translate-x-full');
        if(overlay) overlay.classList.toggle('hidden');
    }
    </script>
</body>
</html>