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

require 'department_settings_script.php';

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

$userRole = strtolower(trim($_SESSION['role'] ?? ''));
$myDeptId = $_SESSION['department_id'] ?? null;
$myDept = $departments[$myDeptId] ?? null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Department Staff Management - 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 '../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">Department Workspace</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Staff Allocation & Overrides</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs uppercase tracking-wider">
                        🏢 <?= htmlspecialchars($myDept['name'] ?? 'Division Control') ?>
                    </div>
                </div>
            </header>

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

                <?php if(isset($_GET['saved'])): ?>
                <div class="bg-emerald-50 border border-emerald-300 text-emerald-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-emerald-950">Configuration Synchronized</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight">Structural workspace configuration revisions updated successfully.</p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">

                    <!-- Left Workspace Focus Column -->
                    <div class="lg:col-span-1 bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-4 lg:sticky lg:top-20">
                        <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                            <div>
                                <p class="text-[9px] font-black text-indigo-700 uppercase tracking-widest">Focus Context</p>
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight mt-0.5">🏢 <?= htmlspecialchars($myDept['name'] ?? 'Selected Unit') ?></h3>
                            </div>
                            <span class="bg-stone-100 text-slate-700 border border-slate-300 px-2 py-0.5 rounded font-black text-[9px] font-mono uppercase tracking-wider">
                                Active Pool
                            </span>
                        </div>

                        <form method="POST" class="space-y-4">
                            <input type="hidden" name="action_update_department_staff" value="1">
                            
                            <div class="space-y-3 max-h-[450px] overflow-y-auto pr-1 custom-scrollbar" id="myDeptContainer">
                                <?php foreach ($employees as $emp): ?>
                                    <?php if ($emp['department_id'] != $myDeptId) continue; ?>

                                    <div class="flex flex-col sm:flex-row sm:items-center justify-between bg-stone-50/60 p-3 rounded-xl border border-slate-200/80 gap-3 transition hover:border-indigo-400" data-employee-id="<?= $emp['id'] ?>">
                                        <div class="flex items-center gap-2.5">
                                            <div class="w-1.5 h-1.5 rounded-full bg-emerald-500 shadow-[0_0_6px_2px_rgba(16,185,129,0.2)]"></div>
                                            <div>
                                                <p class="font-extrabold text-slate-900 text-xs leading-tight"><?= htmlspecialchars($emp['name']) ?></p>
                                                <p class="text-[9px] text-slate-500 font-mono mt-0.5">ID: #<?= $emp['id'] ?></p>
                                            </div>
                                        </div>

                                        <div class="w-full sm:w-auto">
                                            <select name="employee_shift_override[<?= $emp['id'] ?>]" class="w-full sm:w-auto bg-white border border-slate-300 rounded-lg px-2 py-1 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-[11px] text-slate-800 font-bold shadow-2xs cursor-pointer">
                                                <option value="">Default Rotation</option>
                                                <?php foreach ($shifts as $shift): ?>
                                                <option value="<?= $shift['id'] ?>">
                                                    <?= htmlspecialchars($shift['name']) ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <button type="submit" class="w-full bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg font-bold py-2.5 text-xs shadow-sm border border-slate-950 uppercase tracking-wider">
                                Commit Changes
                            </button>
                        </form>
                    </div>

                    <!-- Right Complete Register Column -->
                    <div class="lg:col-span-2 bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden flex flex-col">
                        
                        <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                            <div>
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">👥 Complete Employee Register</h3>
                                <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Filter and allocate system operational staff profiles across standard domains.</p>
                            </div>
                            <div class="relative w-full sm:w-64">
                                <span class="absolute inset-y-0 left-2.5 flex items-center text-xs text-slate-400 select-none">🔍</span>
                                <input type="text" id="search" placeholder="Filter staff or division..." class="w-full border border-slate-300 bg-white pl-7 pr-3 py-1.5 rounded-lg focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 placeholder-slate-400 font-bold" onkeyup="filterStaff()">
                            </div>
                        </div>

                        <div class="p-4 space-y-3 max-h-[600px] overflow-y-auto custom-scrollbar">
                            <?php foreach ($employees as $emp): ?>
                                <?php if ($emp['department_id'] == $myDeptId) continue; ?>

                                <?php $currDeptName = $departments[$emp['department_id']]['name'] ?? 'Unassigned'; ?>
                                
                                <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between bg-white p-3 rounded-xl border border-slate-200 hover:border-slate-300 transition-all gap-4 staff-item" data-name="<?= strtolower($emp['name']) ?>" data-dept="<?= strtolower($currDeptName) ?>">
                                    
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 text-slate-700 flex items-center justify-center font-black text-xs select-none uppercase">
                                            <?= substr(trim($emp['name']), 0, 2) ?>
                                        </div>
                                        <div class="space-y-0.5">
                                            <p class="font-extrabold text-slate-900 text-xs leading-tight"><?= htmlspecialchars($emp['name']) ?></p>
                                            <div class="flex items-center gap-1.5 mt-0.5">
                                                <span class="text-[9px] font-black text-slate-400 uppercase tracking-wider">Current Sector:</span>
                                                <span class="bg-indigo-50 text-indigo-800 border border-indigo-100/70 px-1.5 py-0.2 rounded text-[10px] font-bold">
                                                    <?= htmlspecialchars($currDeptName) ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <button type="button" onclick="addStaff(<?= $emp['id'] ?>, '<?= htmlspecialchars(addslashes($emp['name'])) ?>')" class="w-full sm:w-auto bg-white hover:bg-slate-900 text-slate-800 hover:text-white border border-slate-300 hover:border-slate-900 px-3 py-1.5 rounded-lg text-[11px] font-black tracking-wider uppercase transition-all shadow-2xs active:scale-95">
                                        + Reallocate Here
                                    </button>
                                </div>
                            <?php endforeach; ?>
                        </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 filterStaff(){
        const search = document.getElementById('search').value.toLowerCase();
        const items = document.querySelectorAll('.staff-item');

        items.forEach(item => {
            const name = item.dataset.name;
            const dept = item.dataset.dept;
            
            if (name.includes(search) || dept.includes(search)) {
                item.style.setProperty('display', 'flex', 'important');
            } else {
                item.style.setProperty('display', 'none', 'important');
            }
        });
    }

    function addStaff(empId, empName) {
        const container = document.getElementById("myDeptContainer");

        if (container.querySelector(`[data-employee-id="${empId}"]`)) {
            alert("This record configuration is already attached to this workspace stack layout.");
            return;
        }

        const html = `
        <div class="flex flex-col sm:flex-row sm:items-center justify-between bg-white p-3 rounded-xl border-2 border-dashed border-emerald-300 gap-3 animation-pop relative overflow-hidden" data-employee-id="${empId}">
            <input type="hidden" name="allocated_staff_ids[]" value="${empId}">
            
            <div class="flex items-center gap-2.5">
                <div class="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse shadow-[0_0_6px_2px_rgba(245,158,11,0.2)]"></div>
                <div>
                    <p class="font-extrabold text-slate-900 text-xs leading-tight">${empName}</p>
                    <span class="bg-emerald-50 text-emerald-800 border border-emerald-200 px-1.5 py-0.2 rounded font-black text-[9px] uppercase tracking-wider mt-0.5 inline-block">Pending Sync</span>
                </div>
            </div>

            <div class="w-full sm:w-auto">
                <select name="employee_shift_override[${empId}]" class="w-full sm:w-auto bg-stone-50 border border-slate-300 rounded-lg px-2 py-1 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-[11px] text-slate-800 font-bold shadow-2xs cursor-pointer">
                    <option value="">Default Rotation</option>
                    <?php foreach ($shifts as $shift): ?>
                    <option value="<?= $shift['id'] ?>">
                        <?= htmlspecialchars($shift['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>`;

        container.insertAdjacentHTML('beforeend', html);
        
        const targetElement = container.lastElementChild;
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
    </script>

    <style>
    .custom-scrollbar::-webkit-scrollbar {
        height: 5px;
        width: 5px;
    }
    .custom-scrollbar::-webkit-scrollbar-track {
        background: transparent;
    }
    .custom-scrollbar::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.06);
        border-radius: 99px;
    }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 0, 0, 0.14);
    }

    @keyframes pop {
        0% { transform: scale(0.96); opacity: 0; }
        100% { transform: scale(1); opacity: 1; }
    }
    .animation-pop {
        animation: pop 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }
    </style>
</body>
</html>