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

if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
    session_write_close();
}

require 'leave_script.php';
require '../config.php';

// 1. Fetch all configured roles from the dynamic setup
$allowedRoles = ['admin', 'superadmin', 'hr'];
$stageRes = $conn->query("SELECT DISTINCT LOWER(role_allowed) AS role_name FROM leave_approval_stages");
if ($stageRes) {
    while ($sRow = $stageRes->fetch_assoc()) {
        $allowedRoles[] = $sRow['role_name'];
    }
}

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

// 2. Adaptive Gatekeeper Security Check
if (!in_array($userRole, $allowedRoles)) {
    die("Access Denied: Administrative Clearance Required.");
}

$selectedYear = intval($_GET['year'] ?? date('Y'));

// 3. Complete Cross-Join Matrix Mapping Pipeline Execution
$stmt = $conn->prepare("
    SELECT 
        e.id AS employee_id,
        e.name AS employee_name,
        d.name AS department,
        lt.name AS leave_type,
        COALESCE(lb.allocated_days, 0.00) AS allocated_days,
        COALESCE(lb.carry_forward, 0.00) AS carry_forward,
        COALESCE(lb.used_days, 0.00) AS used_days,
        (COALESCE(lb.allocated_days, 0.00) + COALESCE(lb.carry_forward, 0.00) - COALESCE(lb.used_days, 0.00)) AS remaining_days
    FROM employees e
    CROSS JOIN leave_types lt
    LEFT JOIN departments d ON d.id = e.department_id
    LEFT JOIN leave_balances lb ON lb.employee_id = e.id 
        AND lb.leave_type_id = lt.id 
        AND lb.year = ?
    ORDER BY e.name ASC, lt.name ASC
");
$stmt->bind_param("i", $selectedYear);
$stmt->execute();
$res = $stmt->get_result();

$employeeCards = [];
while ($row = $res->fetch_assoc()) {
    $empId = $row['employee_id'];
    if (!isset($employeeCards[$empId])) {
        $employeeCards[$empId] = [
            'name' => $row['employee_name'],
            'department' => $row['department'] ?? 'Unassigned',
            'leaves' => []
        ];
    }
    $employeeCards[$empId]['leaves'][] = [
        'type' => $row['leave_type'],
        'allocated' => $row['allocated_days'],
        'carry_forward' => $row['carry_forward'],
        'used' => $row['used_days'],
        'remaining' => $row['remaining_days']
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Balances - 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">Leave Balances</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Human Resource Allocation Audits</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">

                <!-- Configuration/Filter/Search Panel -->
                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-4">
                    <div class="flex items-center justify-between border-b border-slate-100 pb-2">
                        <div>
                            <p class="text-[9px] font-black text-indigo-700 uppercase tracking-widest">Parameters</p>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight mt-0.5">Select Audit Matrix Cycle</h3>
                        </div>
                        <span class="text-[9px] bg-indigo-50 border border-indigo-200 text-indigo-700 px-2 py-0.5 rounded font-bold uppercase">Clearance Context: <?= htmlspecialchars($userRole) ?></span>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-3">
                        <!-- Year Selector Form Component -->
                        <form method="GET" class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 lg:col-span-2">
                            <div class="relative flex-1">
                                <span class="absolute left-3 top-2.5 text-[10px] font-black text-slate-400 uppercase tracking-wider">Fiscal Year:</span>
                                <input 
                                    type="number" 
                                    name="year" 
                                    value="<?= $selectedYear ?>" 
                                    required
                                    class="w-full border border-slate-300 bg-stone-50 rounded-lg pl-24 pr-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                            </div>
                            <button type="submit" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg font-bold py-1.5 px-5 text-xs border border-slate-950 uppercase tracking-wider whitespace-nowrap">
                                Load Cycle
                            </button>
                        </form>

                        <!-- Live Profile Metric Search Bar Input -->
                        <div class="relative">
                            <span class="absolute left-3 top-2.5 text-slate-400 select-none">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                            </span>
                            <input 
                                type="text" 
                                id="matrixSearchInput" 
                                onkeyup="filterEmployeeMatrixCards()" 
                                placeholder="Search employee name or department..." 
                                class="w-full border border-slate-300 bg-stone-50 rounded-lg pl-9 pr-3 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold placeholder:text-slate-400">
                        </div>
                    </div>
                </div>

                <!-- Matrix Section Label -->
                <div class="flex justify-between items-center px-1">
                    <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Employee Balance Portfolios</h3>
                    <span class="text-[10px] bg-indigo-50 border border-slate-200 text-indigo-700 px-2 py-0.5 rounded font-mono font-bold">Cycle Loop: <?= $selectedYear ?></span>
                </div>

                <!-- Empty State Block -->
                <div id="emptyMatrixStateBlock" class="bg-white border border-slate-300/80 rounded-xl p-8 text-center shadow-sm hidden">
                    <p class="text-xs text-slate-400 font-bold uppercase tracking-wider">No record entries matches your matrix filter constraints.</p>
                </div>

                <?php if (empty($employeeCards)): ?>
                    <div class="bg-white border border-slate-300/80 rounded-xl p-8 text-center shadow-sm">
                        <p class="text-xs text-slate-400 font-bold uppercase tracking-wider">No record entries returned for this balance segment.</p>
                    </div>
                <?php endif; ?>

                <!-- Balanced Ledger Metrics Cards Grid -->
                <div id="employeeMatrixGridContainer" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    <?php foreach ($employeeCards as $empId => $data): ?>
                        <div class="employee-portfolio-card bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm flex flex-col justify-between transition hover:border-slate-400" 
                             data-name="<?= htmlspecialchars(strtolower($data['name'])) ?>" 
                             data-dept="<?= htmlspecialchars(strtolower($data['department'])) ?>">
                            
                            <div>
                                <div class="flex items-center justify-between gap-3 border-b border-slate-100 pb-2.5 mb-3">
                                    <div class="min-w-0">
                                        <h4 class="font-black text-sm text-slate-950 tracking-tight truncate search-target-name"><?= htmlspecialchars($data['name']) ?></h4>
                                        <span class="inline-block mt-0.5 text-[9px] font-black tracking-wider text-indigo-700 uppercase bg-indigo-50/60 border border-indigo-100 px-1.5 py-0.5 rounded truncate max-w-full search-target-dept">
                                            <?= htmlspecialchars($data['department']) ?>
                                        </span>
                                    </div>
                                    <div class="w-8 h-8 bg-slate-100 border border-slate-200 text-slate-700 rounded-lg flex items-center justify-center font-black text-xs select-none uppercase shrink-0">
                                        <?= mb_strtoupper(mb_substr($data['name'], 0, 2)) ?>
                                    </div>
                                </div>

                                <div class="space-y-2">
                                    <?php foreach ($data['leaves'] as $leave): ?>
                                        <div class="bg-stone-50/60 border border-slate-200/60 rounded-lg p-2.5 space-y-2">
                                            
                                            <div class="flex justify-between items-center gap-2 text-[10px]">
                                                <span class="bg-white border border-slate-200 text-slate-800 px-1.5 py-0.5 rounded font-extrabold truncate">
                                                    <?= htmlspecialchars($leave['type']) ?>
                                                </span>
                                                <span class="px-2 py-0.5 rounded font-black shrink-0 <?= $leave['remaining'] > 0 ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-slate-100 text-slate-600 border border-slate-200' ?>">
                                                    <?= number_format($leave['remaining'], 1) ?> Remaining
                                                </span>
                                            </div>

                                            <div class="grid grid-cols-3 gap-1.5 text-center text-[10px]">
                                                <div class="bg-white p-1 rounded border border-slate-200/80">
                                                    <div class="text-[8px] font-bold text-slate-400 uppercase tracking-wide">Allocated</div>
                                                    <div class="font-extrabold text-slate-800 mt-0.5"><?= number_format($leave['allocated'], 1) ?></div>
                                                </div>
                                                <div class="bg-white p-1 rounded border border-slate-200/80">
                                                    <div class="text-[8px] font-bold text-slate-400 uppercase tracking-wide">Carry Fwd</div>
                                                    <div class="font-extrabold text-amber-600 mt-0.5"><?= number_format($leave['carry_forward'], 1) ?></div>
                                                </div>
                                                <div class="bg-white p-1 rounded border border-slate-200/80">
                                                    <div class="text-[8px] font-bold text-slate-400 uppercase tracking-wide">Consumed</div>
                                                    <div class="font-extrabold text-rose-600 mt-0.5"><?= number_format($leave['used'], 1) ?></div>
                                                </div>
                                            </div>

                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                        </div>
                    <?php endforeach; ?>
                </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>
    // Safeguard to prevent dual overlay triggering if sidebar.js has missing elements
    if (typeof toggleSidebar === 'undefined') {
        window.toggleSidebar = function() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebar-overlay');
            if (sidebar && overlay) {
                sidebar.classList.toggle('-translate-x-full');
                overlay.classList.toggle('hidden');
            }
        };
    }

    // Dynamic Matrix Portfolio Card Client Search Engine
    function filterEmployeeMatrixCards() {
        const query = document.getElementById('matrixSearchInput').value.toLowerCase().trim();
        const cards = document.getElementsByClassName('employee-portfolio-card');
        const emptyBlock = document.getElementById('emptyMatrixStateBlock');
        let visibleCount = 0;

        for (let i = 0; i < cards.length; i++) {
            const cardName = cards[i].getAttribute('data-name') || '';
            const cardDept = cards[i].getAttribute('data-dept') || '';

            if (cardName.includes(query) || cardDept.includes(query)) {
                cards[i].style.display = "";
                visibleCount++;
            } else {
                cards[i].style.display = "none";
            }
        }

        if (emptyBlock) {
            if (visibleCount === 0 && query !== "") {
                emptyBlock.classList.remove('hidden');
            } else {
                emptyBlock.classList.add('hidden');
            }
        }
    }
    </script>
</body>
</html>