<?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.id AS job_id,
    j.title
FROM applicants a
LEFT JOIN jobs j ON j.id = a.job_id
WHERE a.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$applicant = $stmt->get_result()->fetch_assoc();

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

/*
|--------------------------------------------------------------------------
| LOAD DEFAULT TEMPLATE
|--------------------------------------------------------------------------
*/

$templateQuery = $conn->query("
SELECT *
FROM offer_templates
ORDER BY id ASC
LIMIT 1
");
$template = $templateQuery ? $templateQuery->fetch_assoc() : null;

$templateText = '';

if($template && !empty($template['template_text'])){
    $templateText = $template['template_text'];
}else{
    $templateText = "Dear {NAME},

We are pleased to offer you employment with Best Western Plus Yenagoa as {POSITION}.

Your monthly salary shall be {SALARY}.

Your resumption date is {DATE}.

Congratulations.

Human Resources Department
Best Western Plus Yenagoa";
}

/*
|--------------------------------------------------------------------------
| SAVE OFFER
|--------------------------------------------------------------------------
*/

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

    $salary = floatval($_POST['salary']);
    $resumption = $_POST['resumption_date'];
    $offerText = trim($_POST['offer_text']);
    $createdBy = intval($_SESSION['user_id']);

    $stmt = $conn->prepare("
    INSERT INTO job_offers
    (
        applicant_id,
        job_id,
        offer_date,
        salary,
        resumption_date,
        offer_text,
        created_by
    )
    VALUES
    (
        ?, ?,
        CURDATE(),
        ?, ?, ?, ?
    )
    ");

    $stmt->bind_param(
        "iidssi",
        $id,
        $applicant['job_id'],
        $salary,
        $resumption,
        $offerText,
        $createdBy
    );

    $stmt->execute();

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

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Offer Letter - 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 Generator</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-5xl w-full mx-auto space-y-6">

                <div class="flex items-center justify-between gap-4 bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm">
                    <div class="flex items-center gap-3">
                        <a href="applicant_profile.php?id=<?= $id ?>" 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>
                            <h2 class="text-base font-black text-slate-950 uppercase tracking-tight">Draft Offer Letter</h2>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Configure compensation terms and generate an official employment letter.</p>
                        </div>
                    </div>
                    <span class="bg-emerald-50 text-emerald-800 border border-emerald-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                        Stage: Offer
                    </span>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl p-5 sm:p-6 shadow-sm space-y-6">
                    
                    <div class="bg-stone-50 border border-slate-200/80 p-4 rounded-lg flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                        <div class="space-y-0.5">
                            <span class="text-[9px] font-black text-indigo-700 uppercase tracking-widest block">Candidate Recipient</span>
                            <h3 class="text-base font-black text-slate-950"><?= htmlspecialchars($applicant['full_name']) ?></h3>
                            <p class="text-xs font-semibold text-slate-600"><?= htmlspecialchars($applicant['email']) ?></p>
                        </div>
                        <div class="text-left sm:text-right border-t sm:border-t-0 border-slate-200 pt-2 sm:pt-0">
                            <span class="text-[9px] font-black text-slate-500 uppercase tracking-wider block">Target Position</span>
                            <p class="text-xs font-extrabold text-slate-900"><?= htmlspecialchars($applicant['title'] ?? 'Unassigned') ?></p>
                        </div>
                    </div>

                    <form method="POST" id="offerForm" class="space-y-6">
                        <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" id="salary" required placeholder="e.g. 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 placeholder-slate-400">
                            </div>

                            <div class="space-y-1">
                                <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Resumption Date <span class="text-rose-500">*</span></label>
                                <input type="date" name="resumption_date" id="resumption_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">
                            <div class="flex items-center justify-between mb-1">
                                <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Offer Letter Content Body <span class="text-rose-500">*</span></label>
                                <button type="button" onclick="generateLetter()" class="text-[10px] font-extrabold text-indigo-700 hover:text-indigo-900 uppercase tracking-wider underline">
                                    Sync Input Values
                                </button>
                            </div>
                            <textarea name="offer_text" id="offer_text" rows="14" required class="w-full border border-slate-300 bg-stone-50 rounded-lg p-3.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono leading-relaxed placeholder-slate-400"><?= 
                                htmlspecialchars(
                                    str_replace(
                                        ['{NAME}','{POSITION}','{SALARY}','{DATE}'],
                                        [
                                            $applicant['full_name'],
                                            $applicant['title'],
                                            '________________',
                                            '________________'
                                        ],
                                        $templateText
                                    )
                                )
                            ?></textarea>
                        </div>

                        <div class="pt-3 border-t border-slate-200/80 flex items-center justify-end gap-3">
                            <button type="button" onclick="generateLetter()" class="bg-stone-100 hover:bg-stone-200 text-slate-700 border border-slate-300 active:scale-[0.98] transition px-4 py-2 rounded-lg font-bold text-xs shadow-xs">
                                Preview Values
                            </button>
                            <button type="submit" name="save" 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>Generate & Issue 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>

            </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>
        const originalTemplate = `<?= addslashes(
            str_replace(
                ['{NAME}','{POSITION}'],
                [
                    $applicant['full_name'],
                    $applicant['title']
                ],
                $templateText
            )
        ) ?>`;

        function generateLetter(){
            let salary = document.getElementById('salary').value;
            let date = document.getElementById('resumption_date').value;

            let formattedSalary = salary ? '₦' + Number(salary).toLocaleString('en-US', {minimumFractionDigits: 2}) : '________________';
            let formattedDate = date ? date : '________________';

            let letter = originalTemplate
                .replaceAll('{SALARY}', formattedSalary)
                .replaceAll('{DATE}', formattedDate);

            document.getElementById('offer_text').value = letter;
        }
    </script>
    <script src="../components/sidebar.js"></script>
</body>
</html>