<?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;
}

$userId = intval($_SESSION['user_id']);
$username = $_SESSION['username'] ?? 'HR Admin';
$role = $_SESSION['role'] ?? 'Administrator';

/*
|--------------------------------------------------------------------------
| CREATE OFFER
|--------------------------------------------------------------------------
*/

if(isset($_POST['create_offer'])){

    $applicantId = intval($_POST['applicant_id']);
    $jobId = intval($_POST['job_id']);
    $salary = floatval($_POST['salary']);
    $startDate = $_POST['start_date'];
    $terms = trim($_POST['offer_terms']);

    $stmt = $conn->prepare("
    INSERT INTO offer_letters
    (
        applicant_id,
        job_id,
        salary,
        start_date,
        offer_terms,
        created_by
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ");

    $stmt->bind_param(
        "iidssi",
        $applicantId,
        $jobId,
        $salary,
        $startDate,
        $terms,
        $userId
    );

    $stmt->execute();

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

    header("Location: offer_letter.php?created=1");
    exit;
}

/*
|--------------------------------------------------------------------------
| LOAD INTERVIEW PASSED APPLICANTS
|--------------------------------------------------------------------------
*/

$applicants = $conn->query("
SELECT
    a.*,
    j.title AS job_title,
    i.score
FROM applicants a
LEFT JOIN jobs j ON j.id = a.job_id
LEFT JOIN interviews i ON i.applicant_id = a.id
WHERE a.status IN ('Interview', 'Shortlisted')
ORDER BY i.score DESC
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Offer Letter 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">Recruitment Portal</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Offer Letter Management</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">

                <?php if(isset($_GET['created'])): ?>
                <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">Offer Letter Created Successfully</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight">The employment offer letter has been recorded and candidate status updated.</p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm">
                    <div>
                        <h2 class="text-base font-black text-slate-950 uppercase tracking-tight">Candidate Offer Pipeline</h2>
                        <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Select qualified applicants from shortlisted or interview stages to generate offers.</p>
                    </div>
                </div>

                <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">Eligible Candidates</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">List of candidates ready for employment offers.</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">
                            <?= $applicants ? $applicants->num_rows : 0 ?> Pending
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[700px] 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">Candidate Info</th>
                                    <th class="p-3 text-left">Applied Position</th>
                                    <th class="p-3 text-center">Interview Score</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 (!$applicants || $applicants->num_rows === 0): ?>
                            <tr>
                                <td colspan="4" 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 Eligible Applicants Found</h4>
                                        <p class="text-[10px] text-slate-600 max-w-xs">Candidates must be in 'Shortlisted' or 'Interview' status to appear here.</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                                <?php 
                                $rows = [];
                                while($row = $applicants->fetch_assoc()): 
                                    $rows[] = $row;
                                ?>
                                    <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                        <td class="p-3 whitespace-nowrap">
                                            <div class="space-y-0.5">
                                                <p class="font-extrabold text-slate-900 leading-tight"><?= htmlspecialchars($row['full_name']) ?></p>
                                                <p class="text-[10px] text-slate-500 font-semibold"><?= htmlspecialchars($row['email']) ?></p>
                                            </div>
                                        </td>

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

                                        <td class="p-3 text-center whitespace-nowrap font-mono">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-black bg-indigo-50 border border-indigo-200 text-indigo-800">
                                                <?= intval($row['score']) ?>
                                            </span>
                                        </td>

                                        <td class="p-3 text-center whitespace-nowrap">
                                            <button onclick="openModal('offerModal<?= $row['id'] ?>')" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-3 py-1.5 rounded-lg font-bold text-[11px] shadow-xs border border-slate-950 inline-flex items-center gap-1.5">
                                                <span>Generate Offer</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="M12 4.5v15m7.5-7.5h-15"></path>
                                                </svg>
                                            </button>
                                        </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>

    <!-- MODALS RENDER AREA -->
    <?php if (!empty($rows)): ?>
        <?php foreach($rows as $row): ?>
        <div id="offerModal<?= $row['id'] ?>" class="hidden fixed inset-0 bg-slate-900/50 backdrop-blur-xs flex items-center justify-center z-50 p-4 transition-opacity">
            <div class="bg-white border border-slate-300 rounded-xl shadow-xl w-full max-w-2xl overflow-hidden space-y-4">
                
                <div class="px-5 py-4 border-b border-slate-200/80 flex items-center justify-between bg-stone-50">
                    <div>
                        <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Generate Offer Specification</h3>
                        <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Issuing offer for: <span class="text-slate-900 font-bold"><?= htmlspecialchars($row['full_name']) ?></span> (<?= htmlspecialchars($row['job_title']) ?>)</p>
                    </div>
                    <button type="button" onclick="closeModal('offerModal<?= $row['id'] ?>')" class="text-slate-400 hover:text-slate-600 p-1">
                        <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="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>

                <form method="POST" class="p-5 space-y-4">
                    <input type="hidden" name="applicant_id" value="<?= $row['id'] ?>">
                    <input type="hidden" name="job_id" value="<?= $row['job_id'] ?>">

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="space-y-1">
                            <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Monthly Salary (₦) <span class="text-rose-500">*</span></label>
                            <input type="number" step="0.01" name="salary" required placeholder="250000.00" 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-mono font-bold">
                        </div>

                        <div class="space-y-1">
                            <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Start Date <span class="text-rose-500">*</span></label>
                            <input type="date" name="start_date" required 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">
                        </div>
                    </div>

                    <div class="space-y-1">
                        <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Offer Terms & Conditions <span class="text-rose-500">*</span></label>
                        <textarea name="offer_terms" rows="5" required placeholder="Specify probationary period, work schedule, benefits, and contingencies..." class="w-full border border-slate-300 bg-stone-50 rounded-lg p-3 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-semibold placeholder-slate-400"></textarea>
                    </div>

                    <div class="pt-3 border-t border-slate-200/80 flex items-center justify-end gap-3">
                        <button type="button" onclick="closeModal('offerModal<?= $row['id'] ?>')" class="px-4 py-2 rounded-lg text-xs font-bold text-slate-600 hover:bg-slate-200/70 transition">
                            Cancel
                        </button>
                        <button type="submit" name="create_offer" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-5 py-2 rounded-lg font-bold text-xs shadow-xs border border-slate-950 flex items-center gap-2">
                            <span>Create Offer</span>
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3 21l18-9L3 3l3 9zm0 0h7.5"></path>
                            </svg>
                        </button>
                    </div>
                </form>

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

    <script>
        function openModal(id) {
            document.getElementById(id).classList.remove('hidden');
        }
        function closeModal(id) {
            document.getElementById(id).classList.add('hidden');
        }
    </script>
    <script src="../components/sidebar.js"></script>
</body>
</html>