<?php

error_reporting(E_ALL);
ini_set('display_errors',1);

require '../config.php';

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

$stmt = $conn->prepare("
SELECT

j.*,
d.name department

FROM jobs j

LEFT JOIN departments d
ON d.id=j.department_id

WHERE j.id=?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$job = $stmt->get_result()->fetch_assoc();

if(!$job){
    die("Job not found");
}

/*
|--------------------------------------------------------------------------
| APPLY
|--------------------------------------------------------------------------
*/

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

    $fullName = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $coverLetter = trim($_POST['cover_letter']);

    $resume = '';

    if(
        isset($_FILES['resume'])
        &&
        $_FILES['resume']['error']==0
    ){

        $ext = strtolower(
            pathinfo(
                $_FILES['resume']['name'],
                PATHINFO_EXTENSION
            )
        );

        $allowed = [
            'pdf',
            'doc',
            'docx'
        ];

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

            $resume = time().'_'.basename($_FILES['resume']['name']);

            move_uploaded_file(
                $_FILES['resume']['tmp_name'],
                "../uploads/resumes/".$resume
            );
        }
    }

    $stmt = $conn->prepare("
    INSERT INTO applicants
    (
        job_id,
        full_name,
        email,
        phone,
        resume,
        cover_letter
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ");

    $stmt->bind_param(
        "isssss",
        $id,
        $fullName,
        $email,
        $phone,
        $resume,
        $coverLetter
    );

    $stmt->execute();

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apply for <?= htmlspecialchars($job['title']) ?> - 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>
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans 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">
            <a href="careers.php" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Back to Jobs">
                <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>
                <h1 class="text-sm font-black tracking-tight text-slate-950">Job Application Portal</h1>
                <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Position Intake</p>
            </div>
        </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">
            Ref #<?= $id ?>
        </span>
    </header>

    <main class="flex-1 p-4 sm:p-6 max-w-4xl w-full mx-auto space-y-6">

        <?php if(isset($_GET['success'])): ?>
        <div id="success-msg" 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">Application Submitted Successfully</h3>
                <p class="text-[11px] text-emerald-700 font-semibold leading-tight">Your application profile and attachments have been recorded into our recruiting system.</p>
            </div>
        </div>
        <?php endif; ?>

        <div class="bg-white border border-slate-300/80 rounded-xl p-5 sm:p-6 shadow-sm space-y-4">
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-200/80 pb-4">
                <div class="space-y-1">
                    <span class="text-[9px] font-extrabold text-indigo-700 uppercase tracking-widest bg-indigo-50 border border-indigo-200 px-2 py-0.5 rounded font-mono">
                        <?= htmlspecialchars($job['department'] ?? 'General') ?>
                    </span>
                    <h2 class="text-xl sm:text-2xl font-black tracking-tight text-slate-950">
                        <?= htmlspecialchars($job['title']) ?>
                    </h2>
                </div>
                <div class="flex items-center gap-2">
                    <span class="bg-stone-100 text-slate-700 border border-slate-300 px-2.5 py-1 rounded-md font-black text-[10px] font-mono">
                        <?= htmlspecialchars($job['employment_type'] ?? 'Full-Time') ?>
                    </span>
                    <span class="bg-emerald-50 text-emerald-800 border border-emerald-200 px-2.5 py-1 rounded-md font-black text-[10px] font-mono">
                        <?= (int)($job['vacancies'] ?? 1) ?> Vacancy
                    </span>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
                <div class="space-y-1.5">
                    <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Job Description</h3>
                    <div class="bg-stone-50 border border-slate-200/80 p-3.5 rounded-lg text-xs font-semibold text-slate-700 leading-relaxed max-h-56 overflow-y-auto">
                        <?= nl2br(htmlspecialchars($job['description'])) ?>
                    </div>
                </div>

                <div class="space-y-1.5">
                    <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Role Requirements</h3>
                    <div class="bg-stone-50 border border-slate-200/80 p-3.5 rounded-lg text-xs font-semibold text-slate-700 leading-relaxed max-h-56 overflow-y-auto">
                        <?= nl2br(htmlspecialchars($job['requirements'] ?? 'No specific requirements listed.')) ?>
                    </div>
                </div>
            </div>
        </div>

        <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</h3>
                    <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Please fill out all required attributes accurately.</p>
                </div>
                <span class="text-[9px] font-extrabold text-indigo-700 uppercase">Step 1 of 1</span>
            </div>

            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="space-y-1">
                        <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Full Name <span class="text-rose-500">*</span></label>
                        <input type="text" name="full_name" required placeholder="John Doe" 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 placeholder-slate-400">
                    </div>

                    <div class="space-y-1">
                        <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Email Address <span class="text-rose-500">*</span></label>
                        <input type="email" name="email" required placeholder="candidate@example.com" 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 placeholder-slate-400">
                    </div>

                    <div class="space-y-1">
                        <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Phone Number <span class="text-rose-500">*</span></label>
                        <input type="text" name="phone" required placeholder="+1 (555) 000-0000" 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 placeholder-slate-400">
                    </div>

                    <div class="space-y-1">
                        <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Resume / CV Document <span class="text-rose-500">*</span></label>
                        <input type="file" name="resume" required accept=".pdf,.doc,.docx" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-2.5 py-1.5 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-bold file:mr-3 file:py-1 file:px-2.5 file:rounded-md file:border-0 file:text-[10px] file:font-black file:bg-slate-900 file:text-white hover:file:bg-slate-800 file:cursor-pointer">
                        <p class="text-[9px] text-slate-500 font-semibold">Accepted formats: PDF, DOC, DOCX</p>
                    </div>
                </div>

                <div class="space-y-1 pt-1">
                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Cover Letter <span class="text-rose-500">*</span></label>
                    <textarea name="cover_letter" rows="5" required placeholder="Detail your background, key qualifications, and why you are interested in this position..." 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-2 flex items-center justify-end gap-3">
                    <a href="careers.php" class="px-4 py-2 rounded-lg text-xs font-bold text-slate-600 hover:bg-slate-200/70 transition">
                        Cancel
                    </a>
                    <button type="submit" name="apply" 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>Submit Application</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>

</body>
</html>