<?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'] ?? 'HR Admin';
$role = $_SESSION['role'] ?? 'Administrator';

$id = intval($_GET['id'] ?? 0);

$stmt = $conn->prepare("
SELECT
    a.*,
    j.title AS job_title,
    d.name AS department
FROM applicants a
LEFT JOIN jobs j ON j.id = a.job_id
LEFT JOIN departments d ON d.id = j.department_id
WHERE a.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$applicant = $stmt->get_result()->fetch_assoc();

if(!$applicant){
    die("Applicant not found");
}

/*
|--------------------------------------------------------------------------
| STATUS UPDATE
|--------------------------------------------------------------------------
*/

if(isset($_GET['status'])){

    $status = $_GET['status'];

    $allowed = [
        'Applied',
        'Shortlisted',
        'Interview',
        'Offered',
        'Hired',
        'Rejected'
    ];

    if(in_array($status, $allowed)){

        $updateStmt = $conn->prepare("UPDATE applicants SET status = ? WHERE id = ?");
        $updateStmt->bind_param("si", $status, $id);
        $updateStmt->execute();

        header("Location: applicant_profile.php?id=$id");
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| INTERVIEWS
|--------------------------------------------------------------------------
*/

$intStmt = $conn->prepare("
SELECT
    i.*,
    COALESCE(e.name, u.username) AS interviewer_name
FROM interviews i
LEFT JOIN users u ON u.id = i.interviewer
LEFT JOIN employees e ON e.user_id = u.id
WHERE i.applicant_id = ?
ORDER BY i.interview_date DESC
");
$intStmt->bind_param("i", $id);
$intStmt->execute();
$interviews = $intStmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Applicant Profile - <?= htmlspecialchars($applicant['full_name']) ?></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">Recruitment Portal</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Candidate Dossier</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 ?: '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">

                <!-- HEADER BAR -->
                <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-4 bg-white border border-slate-300/80 rounded-xl p-4 sm:p-5 shadow-sm">
                    <div class="flex items-center gap-3">
                        <a href="job_positions.php" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Back">
                            <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="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"></path>
                            </svg>
                        </a>
                        <div>
                            <div class="flex items-center gap-2">
                                <h2 class="text-lg sm:text-xl font-black text-slate-950 tracking-tight"><?= htmlspecialchars($applicant['full_name']) ?></h2>
                                <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2 py-0.5 rounded font-black text-[9px] uppercase tracking-wider font-mono">
                                    ID #<?= $applicant['id'] ?>
                                </span>
                            </div>
                            <p class="text-[11px] text-slate-600 font-bold mt-0.5">
                                Position: <span class="text-slate-900"><?= htmlspecialchars($applicant['job_title'] ?? 'Unassigned') ?></span>
                            </p>
                        </div>
                    </div>

                    <div class="flex flex-wrap items-center gap-2 pt-2 lg:pt-0 border-t lg:border-t-0 border-slate-200">
                        <a href="schedule_interview.php?id=<?= $id ?>" class="bg-indigo-600 hover:bg-indigo-700 active:scale-[0.98] transition text-white px-3 py-2 rounded-lg font-bold text-xs shadow-xs flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"></path>
                            </svg>
                            <span>Schedule Interview</span>
                        </a>

                        <a href="generate_offer.php?id=<?= $id ?>" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-3 py-2 rounded-lg font-bold text-xs shadow-xs border border-slate-950 flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"></path>
                            </svg>
                            <span>Generate Offer</span>
                        </a>

                        <?php if($applicant['status'] == 'Offered'): ?>
                        <a href="onboarding.php?id=<?= $id ?>" class="bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] transition text-white px-3 py-2 rounded-lg font-bold text-xs shadow-xs flex items-center gap-1.5">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"></path>
                            </svg>
                            <span>Start Onboarding</span>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- APPLICANT PROFILE DETAILS -->
                <div class="bg-white border border-slate-300/80 rounded-xl p-5 sm:p-6 shadow-sm space-y-4">
                    <div class="border-b border-slate-200/80 pb-3 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Candidate Profile Attributes</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Contact details, department mapping, and attached documents.</p>
                        </div>
                        <?php
                            $statusClasses = [
                                'Applied' => 'bg-slate-100 text-slate-800 border-slate-300',
                                'Shortlisted' => 'bg-amber-50 text-amber-800 border-amber-300',
                                'Interview' => 'bg-indigo-50 text-indigo-800 border-indigo-300',
                                'Offered' => 'bg-emerald-50 text-emerald-800 border-emerald-300',
                                'Hired' => 'bg-emerald-100 text-emerald-950 border-emerald-400',
                                'Rejected' => 'bg-rose-50 text-rose-800 border-rose-300'
                            ];
                            $badgeStyle = $statusClasses[$applicant['status']] ?? 'bg-stone-100 text-slate-700 border-slate-300';
                        ?>
                        <span class="px-2.5 py-1 border rounded-md font-black text-[10px] font-mono tracking-wide uppercase <?= $badgeStyle ?>">
                            <?= htmlspecialchars($applicant['status']) ?>
                        </span>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="bg-stone-50 border border-slate-200/80 p-3.5 rounded-lg space-y-1">
                            <span class="text-[9px] font-black text-slate-500 uppercase tracking-wider block">Email Address</span>
                            <p class="text-xs font-extrabold text-slate-900 break-all"><?= htmlspecialchars($applicant['email']) ?></p>
                        </div>

                        <div class="bg-stone-50 border border-slate-200/80 p-3.5 rounded-lg space-y-1">
                            <span class="text-[9px] font-black text-slate-500 uppercase tracking-wider block">Phone Number</span>
                            <p class="text-xs font-extrabold text-slate-900"><?= htmlspecialchars($applicant['phone']) ?></p>
                        </div>

                        <div class="bg-stone-50 border border-slate-200/80 p-3.5 rounded-lg space-y-1">
                            <span class="text-[9px] font-black text-slate-500 uppercase tracking-wider block">Department Target</span>
                            <p class="text-xs font-extrabold text-indigo-700 uppercase tracking-wider"><?= htmlspecialchars($applicant['department'] ?? 'General') ?></p>
                        </div>
                    </div>

                    <?php if(!empty($applicant['resume'])): ?>
                    <div class="pt-2 flex items-center justify-between bg-indigo-50/50 border border-indigo-100 p-3.5 rounded-lg">
                        <div class="flex items-center gap-2.5">
                            <div class="p-2 bg-indigo-100 text-indigo-800 rounded-md">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"></path>
                                </svg>
                            </div>
                            <div>
                                <p class="text-xs font-black text-slate-900">Attached Resume File</p>
                                <p class="text-[10px] text-slate-500 font-mono leading-tight"><?= htmlspecialchars($applicant['resume']) ?></p>
                            </div>
                        </div>
                        <a href="../uploads/resumes/<?= htmlspecialchars($applicant['resume']) ?>" target="_blank" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-[11px] shadow-xs border border-slate-950 inline-flex items-center gap-1.5">
                            <span>View Resume</span>
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"></path>
                            </svg>
                        </a>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- COVER LETTER -->
                <div class="bg-white border border-slate-300/80 rounded-xl p-5 sm:p-6 shadow-sm space-y-3">
                    <div class="border-b border-slate-200/80 pb-3">
                        <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Cover Letter</h3>
                        <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Submitted statement from candidate during job intake.</p>
                    </div>
                    <div class="bg-stone-50 border border-slate-200/80 p-4 rounded-lg text-xs font-semibold text-slate-700 leading-relaxed max-h-72 overflow-y-auto">
                        <?= nl2br(htmlspecialchars($applicant['cover_letter'] ?? 'No cover letter submitted.')) ?>
                    </div>
                </div>

                <!-- RECRUITMENT ACTIONS -->
                <div class="bg-white border border-slate-300/80 rounded-xl p-5 sm:p-6 shadow-sm space-y-4">
                    <div class="border-b border-slate-200/80 pb-3">
                        <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Recruitment Pipeline Transition</h3>
                        <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Change application stage or trigger operational actions.</p>
                    </div>

                    <div class="flex flex-wrap gap-2">
                        <a href="?id=<?= $id ?>&status=Shortlisted" class="bg-amber-500 hover:bg-amber-600 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-xs shadow-xs">
                            Shortlist
                        </a>
                        <a href="?id=<?= $id ?>&status=Interview" class="bg-indigo-600 hover:bg-indigo-700 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-xs shadow-xs">
                            Set Interview Stage
                        </a>
                        <a href="generate_offer.php?id=<?= $id ?>" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-xs shadow-xs border border-slate-950">
                            Generate Offer
                        </a>
                        <?php if($applicant['status'] == 'Offered'): ?>
                        <a href="onboarding.php?id=<?= $id ?>" class="bg-purple-600 hover:bg-purple-700 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-xs shadow-xs">
                            Start Onboarding
                        </a>
                        <?php endif; ?>
                        <a href="?id=<?= $id ?>&status=Hired" class="bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-xs shadow-xs">
                            Mark as Hired
                        </a>
                        <a href="?id=<?= $id ?>&status=Rejected" class="bg-rose-600 hover:bg-rose-700 active:scale-[0.98] transition text-white px-3.5 py-1.5 rounded-lg font-extrabold text-xs shadow-xs">
                            Reject Applicant
                        </a>
                    </div>
                </div>

                <!-- INTERVIEW HISTORY -->
                <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">Interview Records</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Logged sessions, evaluations, and interviewer details.</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">
                            <?= $interviews ? $interviews->num_rows : 0 ?> Logged
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[600px] 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">Date & Time</th>
                                    <th class="p-3 text-left">Interviewer</th>
                                    <th class="p-3 text-center">Score / Rating</th>
                                    <th class="p-3 text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                            <?php if (!$interviews || $interviews->num_rows === 0): ?>
                            <tr>
                                <td colspan="4" class="text-center py-8">
                                    <p class="text-xs font-extrabold text-slate-600">No interviews logged for this candidate.</p>
                                </td>
                            </tr>
                            <?php else: ?>
                                <?php while($row = $interviews->fetch_assoc()): ?>
                                    <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                        <td class="p-3 whitespace-nowrap font-mono text-[11px]">
                                            <?= date('d M Y, H:i', strtotime($row['interview_date'])) ?>
                                        </td>
                                        <td class="p-3 whitespace-nowrap text-slate-900 font-extrabold">
                                            <?= htmlspecialchars($row['interviewer_name'] ?? 'Unassigned') ?>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap font-mono">
                                            <span class="bg-stone-100 text-slate-800 border border-slate-300 px-2 py-0.5 rounded text-[10px] font-black">
                                                <?= htmlspecialchars($row['score'] ?? 'N/A') ?>
                                            </span>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2 py-0.5 rounded font-black text-[10px] font-mono">
                                                <?= htmlspecialchars($row['status'] ?? 'Scheduled') ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php endif; ?>
                            </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>