<?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,
    j.department_id
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");
}

/*
|--------------------------------------------------------------------------
| DEPARTMENTS
|--------------------------------------------------------------------------
*/

$departments = $conn->query("
SELECT *
FROM departments
ORDER BY name ASC
");

/*
|--------------------------------------------------------------------------
| COMPLETE ONBOARDING
|--------------------------------------------------------------------------
*/

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

    $employeeNo = trim($_POST['employee_no']);
    $departmentId = intval($_POST['department_id']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $dateHired = $_POST['date_hired'];

    $bankName = trim($_POST['bank_name']);
    $accountNumber = trim($_POST['account_number']);
    $accountName = trim($_POST['account_name']);

    $salaryType = $_POST['salary_type'];
    $basicSalary = floatval($_POST['basic_salary']);
    $overtimeRate = floatval($_POST['overtime_rate']);
    $taxPercent = floatval($_POST['tax_percent']);
    $pensionPercent = floatval($_POST['pension_percent']);

    /*
    |--------------------------------------------------------------------------
    | CREATE EMPLOYEE
    |--------------------------------------------------------------------------
    */

    $stmt = $conn->prepare("
    INSERT INTO employees
    (
        employee_no,
        name,
        department_id,
        phone,
        email,
        date_hired,
        bank_name,
        account_number,
        account_name
    )
    VALUES
    (
        ?,?,?,?,?,?,?,?,?
    )
    ");

    $stmt->bind_param(
        "ssissssss",
        $employeeNo,
        $applicant['full_name'],
        $departmentId,
        $phone,
        $email,
        $dateHired,
        $bankName,
        $accountNumber,
        $accountName
    );

    $stmt->execute();
    $employeeId = $conn->insert_id;

    /*
    |--------------------------------------------------------------------------
    | CREATE SALARY
    |--------------------------------------------------------------------------
    */

    $salary = $conn->prepare("
    INSERT INTO employee_salary
    (
        employee_id,
        salary_type,
        basic_salary,
        overtime_rate,
        tax_percent,
        pension_percent
    )
    VALUES
    (
        ?,?,?,?,?,?
    )
    ");

    $salary->bind_param(
        "isdddd",
        $employeeId,
        $salaryType,
        $basicSalary,
        $overtimeRate,
        $taxPercent,
        $pensionPercent
    );

    $salary->execute();

    /*
    |--------------------------------------------------------------------------
    | UPDATE APPLICANT
    |--------------------------------------------------------------------------
    */

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

    header("Location: applicants.php?hired=1");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Onboarding - 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">Employee Onboarding Process</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">Onboard New Employee</h2>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Transition successful applicant into active staff registry and initialize payroll setup.</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">
                        Stage: Hiring Transition
                    </span>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl p-5 sm:p-6 shadow-sm space-y-8">
                    
                    <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 Conversion</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">Position Assigned</span>
                            <p class="text-xs font-extrabold text-slate-900"><?= htmlspecialchars($applicant['job_title'] ?? 'Unassigned') ?></p>
                        </div>
                    </div>

                    <form method="POST" class="space-y-8">
                        
                        <!-- SECTION 1: PERSONAL & EMPLOYMENT INFO -->
                        <div class="space-y-4">
                            <div class="border-b border-slate-200/80 pb-2">
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-wider flex items-center gap-2">
                                    <span class="w-2 h-2 rounded-full bg-indigo-600"></span>
                                    Employment & Identification Details
                                </h3>
                            </div>

                            <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">Employee ID No <span class="text-rose-500">*</span></label>
                                    <input type="text" name="employee_no" required value="EMP<?= rand(1000,9999) ?>" 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">Department <span class="text-rose-500">*</span></label>
                                    <select name="department_id" 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">
                                        <?php if ($departments): ?>
                                            <?php while($dept = $departments->fetch_assoc()): ?>
                                                <option value="<?= $dept['id'] ?>" <?= $dept['id'] == $applicant['department_id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($dept['name']) ?>
                                                </option>
                                            <?php endwhile; ?>
                                        <?php endif; ?>
                                    </select>
                                </div>

                                <div class="space-y-1">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Contact Phone</label>
                                    <input type="text" name="phone" value="<?= htmlspecialchars($applicant['phone']) ?>" 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-semibold">
                                </div>

                                <div class="space-y-1">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Official Email</label>
                                    <input type="email" name="email" value="<?= htmlspecialchars($applicant['email']) ?>" 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-semibold">
                                </div>

                                <div class="space-y-1 md:col-span-2">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Date Hired <span class="text-rose-500">*</span></label>
                                    <input type="date" name="date_hired" value="<?= date('Y-m-d') ?>" 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>

                        <!-- SECTION 2: BANK DETAILS -->
                        <div class="space-y-4">
                            <div class="border-b border-slate-200/80 pb-2">
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-wider flex items-center gap-2">
                                    <span class="w-2 h-2 rounded-full bg-emerald-600"></span>
                                    Banking & Disbursement Account Details
                                </h3>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div class="space-y-1">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Bank Name</label>
                                    <input type="text" name="bank_name" placeholder="e.g. Access Bank" 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-semibold placeholder-slate-400">
                                </div>

                                <div class="space-y-1">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Account Number</label>
                                    <input type="text" name="account_number" placeholder="10-digit NUBAN" 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">Account Name</label>
                                    <input type="text" name="account_name" placeholder="As registered with bank" 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-semibold placeholder-slate-400">
                                </div>
                            </div>
                        </div>

                        <!-- SECTION 3: SALARY & COMPENSATION -->
                        <div class="space-y-4">
                            <div class="border-b border-slate-200/80 pb-2">
                                <h3 class="text-xs font-black text-slate-950 uppercase tracking-wider flex items-center gap-2">
                                    <span class="w-2 h-2 rounded-full bg-indigo-600"></span>
                                    Salary Structure & Payroll Configurations
                                </h3>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                <div class="space-y-1">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Salary Structure Type</label>
                                    <select name="salary_type" 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="monthly">Monthly Fixed Rate</option>
                                        <option value="daily">Daily Wage Basis</option>
                                        <option value="hourly">Hourly Contract Rate</option>
                                    </select>
                                </div>

                                <div class="space-y-1">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Basic Salary (₦) <span class="text-rose-500">*</span></label>
                                    <input type="number" step="0.01" name="basic_salary" required placeholder="0.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">Overtime Hourly Rate (₦)</label>
                                    <input type="number" step="0.01" name="overtime_rate" value="0.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">Tax Deduction (%)</label>
                                    <input type="number" step="0.01" name="tax_percent" value="7.5" 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 lg:col-span-2">
                                    <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Pension Contribution (%)</label>
                                    <input type="number" step="0.01" name="pension_percent" value="8" 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>
                        </div>

                        <div class="pt-4 border-t border-slate-200/80 flex items-center justify-end gap-3">
                            <a href="applicant_profile.php?id=<?= $id ?>" 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="complete" class="bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white px-5 py-2.5 rounded-lg font-bold text-xs shadow-xs border border-slate-950 flex items-center gap-2">
                                <span>Complete Employee Onboarding</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="M5 13l4 4L19 7"></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 src="../components/sidebar.js"></script>
</body>
</html>