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

require '../config.php';
session_start();
session_write_close();

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

$username = $_SESSION['username'] ?? 'User';
$role = $_SESSION['role'] ?? 'Staff';

$jobFilter = intval($_GET['job'] ?? 0);
$statusFilter = trim($_GET['status'] ?? '');

$where = [];

if($jobFilter > 0){
    $where[] = "a.job_id=".$jobFilter;
}

if($statusFilter != ''){
    $where[] = "a.status='".$conn->real_escape_string($statusFilter)."'";
}

$whereSql = '';

if(count($where)){
    $whereSql = "WHERE ".implode(' AND ',$where);
}

$applicants = $conn->query("
SELECT 
a.*,
j.title job_title,
d.name department
FROM applicants a
LEFT JOIN jobs j ON j.id=a.job_id
LEFT JOIN departments d ON d.id=j.department_id
$whereSql
ORDER BY a.created_at DESC
");

$applicantList = [];
if ($applicants) {
    while($row = $applicants->fetch_assoc()) {
        $applicantList[] = $row;
    }
}

$jobs = $conn->query("
SELECT id,title
FROM jobs
ORDER BY title
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Applicants - 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">Applicant Management</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Recruitment Overview</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($role); ?></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">

                <!-- STAT CARDS -->
                <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 rounded-xl p-4 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Total Candidates</p>
                                <h4 class="text-2xl font-black tracking-tight text-slate-950"><?= count($applicantList); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Active applicants matching parameters.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center text-sm shrink-0">👥</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-slate-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Current Date</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950 mt-0.5"><?= date('d M Y'); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Active processing server timestamp.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 flex items-center justify-center text-sm shrink-0">🕒</div>
                        </div>
                    </div>

                    <div class="bg-gradient-to-br from-slate-900 to-indigo-950 border border-slate-800 rounded-xl p-4 shadow-sm text-white sm:col-span-2 lg:col-span-1 flex flex-col justify-between">
                        <div class="flex items-center justify-between gap-4">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-black text-indigo-300 uppercase tracking-widest">Recruitment Pipeline</p>
                                <h4 class="text-xs font-bold text-slate-100">Filtered View Active</h4>
                            </div>
                            <div class="text-lg">🎯</div>
                        </div>
                        <div class="mt-3.5">
                            <a href="applicants.php" class="w-full bg-white/10 hover:bg-white/15 transition px-3 py-2 rounded-lg font-bold text-xs flex items-center justify-center gap-2 border border-white/10 active:scale-[0.98] text-white">
                                Reset All Parameters
                            </a>
                        </div>
                    </div>
                </div>

                <!-- FILTERS -->
                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-3">
                    <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                        <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Data Filters</h3>
                        <span class="text-[9px] font-bold text-indigo-700 uppercase">Apply recruitment parameters</span>
                    </div>
                    <form method="GET" class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        <div>
                            <select name="job" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                                <option value="">All Job Positions</option>
                                <?php while($job = $jobs->fetch_assoc()): ?>
                                    <option value="<?= $job['id'] ?>" <?= $jobFilter == $job['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($job['title']) ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div>
                            <select name="status" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold">
                                <option value="">All Statuses</option>
                                <option value="Applied" <?= $statusFilter == 'Applied' ? 'selected' : '' ?>>Applied</option>
                                <option value="Shortlisted" <?= $statusFilter == 'Shortlisted' ? 'selected' : '' ?>>Shortlisted</option>
                                <option value="Interview" <?= $statusFilter == 'Interview' ? 'selected' : '' ?>>Interview</option>
                                <option value="Offered" <?= $statusFilter == 'Offered' ? 'selected' : '' ?>>Offered</option>
                                <option value="Hired" <?= $statusFilter == 'Hired' ? 'selected' : '' ?>>Hired</option>
                                <option value="Rejected" <?= $statusFilter == 'Rejected' ? 'selected' : '' ?>>Rejected</option>
                            </select>
                        </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 text-xs shadow-sm border border-slate-950">
                            Apply Parameters
                        </button>
                    </form>
                </div>

                <!-- TABLE -->
                <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">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Applicant Roster</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Detailed view of current recruitment records.</p>
                        </div>
                        <span 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">
                            <?= count($applicantList); ?> Loaded
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[900px] border-collapse">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="p-3 text-left w-[250px]">Applicant Details</th>
                                    <th class="p-3 text-left">Target Position</th>
                                    <th class="p-3 text-left">Department</th>
                                    <th class="p-3 text-left">Contact Info</th>
                                    <th class="p-3 text-center">Applied Date</th>
                                    <th class="p-3 text-center">Status</th>
                                    <th class="p-3 text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">

                            <?php if (empty($applicantList)): ?>
                            <tr>
                                <td colspan="7" class="text-center py-12">
                                    <div class="flex flex-col items-center justify-center space-y-2">
                                        <div class="text-3xl">📭</div>
                                        <h4 class="text-xs font-extrabold text-slate-800">No Applicant Records Found</h4>
                                        <p class="text-[10px] text-slate-600 max-w-xs">Adjust search parameters or clear filters to view candidates.</p>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>

                            <?php foreach ($applicantList as $row): ?>
                            <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                <!-- APPLICANT DETAILS -->
                                <td class="p-3 whitespace-nowrap">
                                    <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">
                                            <?= strtoupper(substr($row['full_name'], 0, 1)); ?>
                                        </div>
                                        <div class="space-y-0.5">
                                            <p class="font-extrabold text-slate-900 leading-tight"><?= htmlspecialchars($row['full_name']); ?></p>
                                            <p class="text-[9px] text-slate-500 uppercase tracking-wider font-black">ID: #<?= sprintf('%04d', $row['id']); ?></p>
                                        </div>
                                    </div>
                                </td>

                                <!-- JOB TITLE -->
                                <td class="p-3 whitespace-nowrap">
                                    <span class="text-slate-900 font-extrabold">
                                        <?= htmlspecialchars($row['job_title'] ?? 'N/A'); ?>
                                    </span>
                                </td>

                                <!-- DEPARTMENT -->
                                <td class="p-3 whitespace-nowrap">
                                    <span class="text-slate-600 font-bold text-[11px]">
                                        <?= htmlspecialchars($row['department'] ?? 'General'); ?>
                                    </span>
                                </td>

                                <!-- CONTACT -->
                                <td class="p-3 whitespace-nowrap">
                                    <div class="space-y-0.5 text-[11px]">
                                        <p class="text-slate-800 font-semibold"><?= htmlspecialchars($row['email']); ?></p>
                                        <p class="text-[10px] font-mono text-slate-500"><?= htmlspecialchars($row['phone']); ?></p>
                                    </div>
                                </td>

                                <!-- APPLIED DATE -->
                                <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                    <?= date('d M Y', strtotime($row['created_at'])); ?>
                                </td>

                                <!-- STATUS -->
                                <td class="p-3 text-center whitespace-nowrap">
                                    <?php
                                        $statusClass = 'bg-stone-100 text-slate-700 border-slate-300';

                                        switch($row['status']) {
                                            case 'Applied':
                                                $statusClass = 'bg-sky-50 text-sky-900 border-sky-300';
                                                break;
                                            case 'Shortlisted':
                                                $statusClass = 'bg-amber-50 text-amber-900 border-amber-300';
                                                break;
                                            case 'Interview':
                                                $statusClass = 'bg-indigo-50 text-indigo-900 border-indigo-300';
                                                break;
                                            case 'Offered':
                                                $statusClass = 'bg-purple-50 text-purple-900 border-purple-300';
                                                break;
                                            case 'Hired':
                                                $statusClass = 'bg-emerald-50 text-emerald-800 border-emerald-300';
                                                break;
                                            case 'Rejected':
                                                $statusClass = 'bg-rose-50 text-rose-900 border-rose-300';
                                                break;
                                        }
                                    ?>
                                    <span class="<?= $statusClass; ?> border px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">
                                        <?= htmlspecialchars($row['status']); ?>
                                    </span>
                                </td>

                                <!-- ACTION -->
                                <td class="p-3 text-center whitespace-nowrap">
                                    <a href="applicant_profile.php?id=<?= $row['id'] ?>" class="inline-flex items-center justify-center bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-[10px] px-3 py-1.5 rounded-lg border border-slate-950 shadow-xs active:scale-95 transition">
                                        View Profile
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </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>