<?php
// employee_add.php
session_start();
session_write_close();
date_default_timezone_set('Africa/Lagos');
require '../config.php';

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

$userRole = strtolower(trim($_SESSION['role'] ?? ''));
if (!in_array($userRole, ['admin', 'superadmin','hr'])) {
    die("Access Denied");
}

/* Data pool arrays mapping */
$departments = [];
$deptRes = $conn->query("SELECT id, name FROM departments ORDER BY name");
if ($deptRes) {
    while ($row = $deptRes->fetch_assoc()) { $departments[$row['id']] = $row['name']; }
}

$positionsList = [];
$posRes = $conn->query("SELECT name FROM positions ORDER BY name");
if ($posRes) {
    while ($row = $posRes->fetch_assoc()) { $positionsList[] = $row['name']; }
}

$designationsList = [];
$desgRes = $conn->query("SELECT name FROM designations ORDER BY name");
if ($desgRes) {
    while ($row = $desgRes->fetch_assoc()) { $designationsList[] = $row['name']; }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Employee Profile - HR System</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">
            
            <!-- Context Header Panel Component -->
            <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 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 rounded-md font-bold text-xs transition shadow-xs active:scale-[0.98]">
                            ← Back to Directory
                        </a>
                        <div class="hidden sm:block border-l border-slate-300 h-5"></div>
                        <div>
                            <h1 class="text-sm font-black tracking-tight text-slate-950">Initialize Data Node</h1>
                            <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Appending segmented variables into repository</p>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Operational Error Banner -->
            <?php if (isset($_GET['error'])): ?>
                <div class="px-4 pt-4 sm:px-6 max-w-7xl w-full mx-auto">
                    <div class="bg-rose-50 border border-rose-300 text-rose-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                        <div class="text-base leading-none mt-0.5">❌</div>
                        <div class="space-y-0.5">
                            <h3 class="font-black text-xs text-rose-950">Profile Setup Aborted</h3>
                            <p class="text-[11px] text-rose-700 font-semibold leading-tight">Confirm necessary field baseline constraints are satisfied.</p>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto grid grid-cols-1 lg:grid-cols-3 gap-6">
                
                <!-- Sidebar Workspace Component -->
                <div class="space-y-6">
                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-xs flex flex-col items-center text-center space-y-4 sticky top-20">
                        <div id="avatar-preview-container" class="w-20 h-20 rounded-xl border border-slate-300 bg-stone-100 text-slate-400 font-black text-2xl flex items-center justify-center shadow-xs overflow-hidden transition-all duration-200 select-none">
                            <span id="avatar-placeholder-icon">＋</span>
                            <img id="avatar-preview-img" src="" alt="Avatar Preview" class="w-full h-full object-cover hidden">
                        </div>
                        <div class="space-y-0.5">
                            <h2 class="text-xs font-black text-slate-950 uppercase tracking-tight">New Staff Profile</h2>
                            <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider font-mono">Awaiting Form Initialization</p>
                        </div>
                        <div class="w-full border-t border-slate-200/80 pt-3 text-left text-[10px] text-slate-500 font-semibold leading-relaxed">
                            <p>💡 Fragmenting records into unified logical blocks provides an isolated debugging layer for payroll compliance and tax tracking modules.</p>
                        </div>
                    </div>
                </div>

                <!-- Form Elements Frame -->
                <div class="lg:col-span-2 space-y-6">
                    <form method="POST" action="employee_add_script.php" enctype="multipart/form-data" class="space-y-6">
                        
                        <?php include 'components/forms/basic_info.php'; ?>

                        <?php include 'components/forms/employee_details.php'; ?>

                        <?php include 'components/forms/contact_info.php'; ?>
                                                                                                                                                                                
                        <?php include 'components/forms/banking_info.php'; ?>

                        <?php include 'components/forms/medical_info.php'; ?>

                        <?php include 'components/forms/education_info.php'; ?>

                        <?php include 'components/forms/documents.php'; ?>

                        <!-- Action Triggers Footer -->
                        <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-xs flex items-center justify-end gap-2">
                            <a href="employees.php" class="bg-white hover:bg-stone-50 border border-slate-300 text-slate-700 font-bold text-xs px-4 py-2 rounded-md text-center transition shadow-xs active:scale-[0.98]">
                                Cancel Setup
                            </a>
                            <button type="submit" class="bg-slate-900 hover:bg-slate-800 text-white font-bold text-xs px-4 py-2 rounded-md transition border border-slate-950 shadow-xs active:scale-[0.98]">
                                Instantiate New Node Asset
                            </button>
                        </div>
                    </form>
                </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');
    }

    // Run immediately rather than waiting for DOMContentLoaded -- this script
    // tag only ever executes once the surrounding markup already exists,
    // whether that's on a normal page load or after an AJAX navigation swap
    // (DOMContentLoaded only ever fires once per real browser page load).
    (function () {
        const avatarInput = document.querySelector('input[name="avatar"]');
        const previewContainer = document.getElementById('avatar-preview-container');
        const placeholderIcon = document.getElementById('avatar-placeholder-icon');
        const previewImg = document.getElementById('avatar-preview-img');

        if (avatarInput) {
            avatarInput.addEventListener('change', function () {
                const file = this.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        previewImg.src = e.target.result;
                        previewImg.classList.remove('hidden');
                        placeholderIcon.classList.add('hidden');
                        previewContainer.classList.remove('bg-stone-100');
                        previewContainer.classList.add('bg-white');
                    }
                    reader.readAsDataURL(file);
                } else {
                    previewImg.src = "";
                    previewImg.classList.add('hidden');
                    placeholderIcon.classList.remove('hidden');
                    previewContainer.classList.add('bg-stone-100');
                    previewContainer.classList.remove('bg-white');
                }
            });
        }
    })();
    </script>
</body>
</html>