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

require '../config.php';

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

$userId = intval($_SESSION['user_id']);

// 1. Map user_id to employee_id first to ensure perfect relational mapping
$empQuery = $conn->prepare("SELECT id FROM employees WHERE user_id = ? LIMIT 1");
$empQuery->bind_param("i", $userId);
$empQuery->execute();
$empResult = $empQuery->get_result()->fetch_assoc();
$empQuery->close();

$employeeId = $empResult ? intval($empResult['id']) : 0;

// Initialize metrics
$leaveCount = 0;
$loanCount = 0;
$payslipCount = 0;

// 2. Fetch metrics using the true mapped employee_id
if ($employeeId > 0) {
    $currentDate = date('Y-m-d');

    // Dynamically query approval stages to ensure we only count leaves that have successfully passed all steps
    $stagesRes = $conn->query("SELECT checking_column FROM leave_approval_stages");
    $stageConditions = [];
    if ($stagesRes && $stagesRes->num_rows > 0) {
        while ($sRow = $stagesRes->fetch_assoc()) {
            $stageConditions[] = "lr.{$sRow['checking_column']} = 'Approved'";
        }
    } else {
        // Fallback default conditions if no dynamic stages are configured yet
        $stageConditions[] = "lr.manager_status = 'Approved'";
        $stageConditions[] = "lr.hr_status = 'Approved'";
    }
    $stagesSqlCondition = implode(' AND ', $stageConditions);

    // Leave Requests count: Only count APPROVED leaves that are actively happening TODAY
    $leaveQuery = $conn->prepare("
        SELECT COUNT(*) as total 
        FROM leave_requests lr
        WHERE lr.employee_id = ? 
          AND {$stagesSqlCondition}
          AND ? BETWEEN lr.start_date AND lr.end_date
    ");
    $leaveQuery->bind_param("is", $employeeId, $currentDate);
    $leaveQuery->execute();
    $leaveCount = $leaveQuery->get_result()->fetch_assoc()['total'] ?? 0;
    $leaveQuery->close();

    // Active Loans count: Only count loans that are genuinely 'Active' or 'Overdue'
    $loanQuery = $conn->prepare("
        SELECT COUNT(*) as total 
        FROM employee_loans 
        WHERE employee_id = ? 
          AND status IN ('Active', 'Overdue')
    ");
    $loanQuery->bind_param("i", $employeeId);
    $loanQuery->execute();
    $loanCount = $loanQuery->get_result()->fetch_assoc()['total'] ?? 0;
    $loanQuery->close();

    // Payslips Issued count
    $payslipQuery = $conn->prepare("SELECT COUNT(*) as total FROM payroll_details WHERE employee_id = ? AND payroll_status = 'Disbursed'");
    $payslipQuery->bind_param("i", $employeeId);
    $payslipQuery->execute();
    $payslipCount = $payslipQuery->get_result()->fetch_assoc()['total'] ?? 0;
    $payslipQuery->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Portal - Core Self Service</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100 min-h-screen text-slate-800 antialiased font-sans">

    <div class="flex">
        
        <?php include __DIR__ . '/../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 uppercase">Dashboard</h1>
                        <p class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Employee Self Service</p>
                    </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 p-5 rounded-xl shadow-xs flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <h2 class="text-sm font-black text-slate-950 uppercase tracking-tight">Welcome to Self Service Control</h2>
                        <p class="text-[11px] text-slate-500 font-medium mt-0.5">Central operations hub, metrics verification layer, and internal historical records monitoring panels.</p>
                    </div>
                </div>

                <!-- Metrics Workspace Panels -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div class="bg-white border border-slate-300/80 p-4 rounded-xl shadow-xs flex items-center gap-4">
                        <div class="w-10 h-10 rounded-lg bg-stone-100 border border-slate-200 text-lg flex items-center justify-center shrink-0">🌴</div>
                        <div>
                            <span class="text-[10px] font-black text-slate-400 uppercase tracking-wider block">Active Leaves Today</span>
                            <div class="text-xl font-black text-slate-950 font-mono tracking-tight"><?= $leaveCount ?></div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 p-4 rounded-xl shadow-xs flex items-center gap-4">
                        <div class="w-10 h-10 rounded-lg bg-stone-100 border border-slate-200 text-lg flex items-center justify-center shrink-0">💵</div>
                        <div>
                            <span class="text-[10px] font-black text-slate-400 uppercase tracking-wider block">Active Loans Ledger</span>
                            <div class="text-xl font-black text-slate-950 font-mono tracking-tight"><?= $loanCount ?></div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 p-4 rounded-xl shadow-xs flex items-center gap-4 sm:col-span-2 lg:col-span-1">
                        <div class="w-10 h-10 rounded-lg bg-stone-100 border border-slate-200 text-lg flex items-center justify-center shrink-0">🧾</div>
                        <div>
                            <span class="text-[10px] font-black text-slate-400 uppercase tracking-wider block">Disbursed Payslips</span>
                            <div class="text-xl font-black text-slate-950 font-mono tracking-tight"><?= $payslipCount ?></div>
                        </div>
                    </div>
                </div>

                <!-- Core Navigation Workspace Matrix -->
                <div class="space-y-2">
                    <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider px-1">Quick Access Operations Hub</h3>
                    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
                        <?php
                        $links = [
                            'my_profile.php'   => ['label' => 'My Profile', 'icon' => '👤'],
                            'my_attendance.php'=> ['label' => 'Attendance Tracker', 'icon' => '⏱️'],
                            'my_schedule.php'  => ['label' => 'Shift Schedules', 'icon' => '📅'],
                            'my_leave.php'     => ['label' => 'Leave Requests', 'icon' => '🌴'],
                            'my_overtime.php'  => ['label' => 'Overtime Logs', 'icon' => '🚀'],
                            'my_payslips.php'  => ['label' => 'Payslips Vault', 'icon' => '🧾'],
                            'my_loans.php'     => ['label' => 'Loans History', 'icon' => '💵'],
                            'my_assets.php'    => ['label' => 'Assets Assigned', 'icon' => '💻']
                        ];
                        foreach ($links as $url => $data): ?>
                            <a href="<?= $url ?>" class="bg-white p-4 border border-slate-300/80 hover:border-slate-500 rounded-xl shadow-xs transition duration-150 flex flex-col items-center justify-center text-center gap-2 group outline-none focus:bg-stone-50">
                                <span class="text-lg group-hover:scale-105 transition duration-150"><?= $data['icon'] ?></span>
                                <span class="text-[11px] font-black uppercase text-slate-700 tracking-tight transition group-hover:text-slate-950">
                                    <?= $data['label'] ?>
                                </span>
                            </a>
                        <?php endforeach; ?>
                    </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>
</body>
</html>