<?php

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

require '../config.php';
require_once '../includes/mailer.php';

if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
    session_write_close();
}

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$username = $_SESSION['username'] ?? 'HR Admin';
$role = $_SESSION['role'] ?? 'Administrator';

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

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

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

/*
|--------------------------------------------------------------------------
| INTERVIEWERS
|--------------------------------------------------------------------------
*/

$interviewers = $conn->query("
SELECT id, username
FROM users
ORDER BY username ASC
");

/*
|--------------------------------------------------------------------------
| SAVE INTERVIEW & SEND MAIL
|--------------------------------------------------------------------------
*/

$mailSent = null;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $date = $_POST['interview_date'] ?? '';
    $meetingLink = trim($_POST['meeting_link'] ?? '');
    
    // 1. Process selected interviewers safely
    $selectedInterviewers = $_POST['interviewers'] ?? [];
    $interviewerIds = [];

    if (is_array($selectedInterviewers)) {
        $interviewerIds = array_values(array_filter(array_map('intval', $selectedInterviewers)));
    } elseif (!empty($selectedInterviewers)) {
        $interviewerIds = [intval($selectedInterviewers)];
    }

    $interviewerString = implode(',', $interviewerIds);

    // 2. Insert interview record
    $stmt = $conn->prepare("
        INSERT INTO interviews (applicant_id, interview_date, interviewer, meeting_link)
        VALUES (?, ?, ?, ?)
    ");

    if (!$stmt) {
        die("Database Prepare Error (Interviews): " . $conn->error);
    }

    $stmt->bind_param("isss", $applicantId, $date, $interviewerString, $meetingLink);
    $stmt->execute();

    // 3. Update applicant stage
    $updateStmt = $conn->prepare("UPDATE applicants SET status = 'Interview' WHERE id = ?");
    if ($updateStmt) {
        $updateStmt->bind_param("i", $applicantId);
        $updateStmt->execute();
    }

    // 4. Prepare shared template variables
    $formattedDate = date('F j, Y - g:i A', strtotime($date));
    $jobTitle = htmlspecialchars($applicant['job_title'] ?? 'your application');
    $applicantName = htmlspecialchars($applicant['full_name'] ?? 'Candidate');

    $meetingInfo = !empty($meetingLink) 
        ? "<p style='margin: 0;'><strong>Meeting Details / Link:</strong> <a href='" . htmlspecialchars($meetingLink) . "' style='color: #4338ca; font-weight: bold;'>" . htmlspecialchars($meetingLink) . "</a></p>" 
        : "";

    // 5. Send notification to candidate
    if (!empty($applicant['email'])) {
        $candidateSubject = "Interview Scheduled - Best Western HR";
        $candidateBody = "
            <h2 style='font-size: 18px; font-weight: 800; margin-top: 0; color: #0f172a;'>Dear {$applicantName},</h2>
            <p>Your interview for the <strong>{$jobTitle}</strong> position has been successfully scheduled.</p>
            
            <div style='background-color: #f8fafc; border: 1px solid #e2e8f0; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                <p style='margin: 0 0 8px 0;'><strong>Date & Time:</strong> {$formattedDate}</p>
                {$meetingInfo}
            </div>

            <p>Please ensure you are punctual and ready prior to your scheduled time slot.</p>
            <p style='margin-bottom: 0;'>Best regards,<br><strong>Talent Acquisition Team</strong></p>
        ";

        try {
            $candidateMailer = new Mailer();
            $sentStatus = $candidateMailer->send($applicant['email'], $applicant['full_name'], $candidateSubject, $candidateBody);
            $mailSent = $sentStatus ? 1 : 0;
        } catch (Throwable $e) {
            error_log("Failed to send candidate email: " . $e->getMessage());
            $mailSent = 0;
        }
    }

    // 6. Send copies to all assigned interviewers
    if (!empty($interviewerIds)) {
        $idList = implode(',', $interviewerIds);
        
        $interviewerQuery = "SELECT username, email FROM users WHERE id IN ($idList)";
        $interviewerResults = $conn->query($interviewerQuery);

        if (!$interviewerResults) {
            error_log("Interviewer Query Failed: " . $conn->error);
        } else {
            while ($interviewer = $interviewerResults->fetch_assoc()) {
                $recipientEmail = trim($interviewer['email'] ?? '');

                if (empty($recipientEmail) || !filter_var($recipientEmail, FILTER_VALIDATE_EMAIL)) {
                    error_log("Skipping interviewer '{$interviewer['username']}': Invalid or missing email.");
                    continue;
                }

                $interviewerName = htmlspecialchars($interviewer['username']);
                $interviewerSubject = "Interview Assignment: Candidate {$applicantName}";
                
                $interviewerBody = "
                    <h2 style='font-size: 18px; font-weight: 800; margin-top: 0; color: #0f172a;'>Hello {$interviewerName},</h2>
                    <p>You have been assigned to conduct an interview for the <strong>{$jobTitle}</strong> position.</p>
                    
                    <div style='background-color: #f8fafc; border: 1px solid #e2e8f0; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                        <p style='margin: 0 0 8px 0;'><strong>Candidate Name:</strong> {$applicantName}</p>
                        <p style='margin: 0 0 8px 0;'><strong>Date & Time:</strong> {$formattedDate}</p>
                        {$meetingInfo}
                    </div>

                    <p style='margin-bottom: 0;'>Best regards,<br><strong>HR System Notification</strong></p>
                ";

                try {
                    $interviewerMailer = new Mailer();
                    $interviewerMailer->send($recipientEmail, $interviewer['username'], $interviewerSubject, $interviewerBody);
                } catch (Throwable $e) {
                    error_log("Mailer Exception for {$recipientEmail}: " . $e->getMessage());
                }
            }
        }
    }

    header("Location: applicant_profile.php?id={$applicantId}&scheduled=1&mail_sent=" . ($mailSent ?? 0));
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Schedule Interview - 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">Interview Scheduler</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-3xl 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=<?= $applicantId ?>" 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">Schedule Candidate Interview</h2>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Assign interviewers, schedule time, and configure virtual meeting details.</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: Scheduling
                    </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 Profile</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['job_title'] ?? 'Unassigned') ?></p>
                        </div>
                    </div>

                    <form method="POST" id="schedule-form" onsubmit="handleSubmit(event)" class="space-y-5">
                        
                        <div class="space-y-1">
                            <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider">Interview Date & Time <span class="text-rose-500">*</span></label>
                            <input type="datetime-local" name="interview_date" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2.5 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">Meeting Link / Location <span class="text-slate-400 font-normal">(Optional)</span></label>
                            <input type="text" name="meeting_link" placeholder="e.g. https://zoom.us/j/12345678 or Conference Room B" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2.5 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-2">
                            <label class="text-[10px] font-extrabold uppercase text-slate-600 tracking-wider block">Assigned Interviewers <span class="text-rose-500">*</span></label>
                            
                            <div class="border border-slate-300 bg-stone-50 rounded-lg p-3 max-h-48 overflow-y-auto space-y-2 divide-y divide-slate-200/60">
                                <?php if ($interviewers && $interviewers->num_rows > 0): ?>
                                    <?php while($row = $interviewers->fetch_assoc()): ?>
                                        <label class="flex items-center gap-2.5 pt-2 first:pt-0 cursor-pointer text-xs font-bold text-slate-800 hover:text-indigo-600 select-none">
                                            <input type="checkbox" name="interviewers[]" value="<?= $row['id'] ?>" class="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                                            <span><?= htmlspecialchars($row['username']) ?></span>
                                        </label>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <p class="text-xs text-slate-500">No available users found.</p>
                                <?php endif; ?>
                            </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=<?= $applicantId ?>" 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" id="submit-btn" 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 disabled:opacity-70 disabled:cursor-not-allowed">
                                <span id="btn-text">Confirm & Schedule</span>
                                <svg id="btn-icon" 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="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                                <svg id="btn-spinner" class="w-4 h-4 animate-spin hidden" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></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>
    <script>
        function handleSubmit(e) {
            const btn = document.getElementById('submit-btn');
            const btnText = document.getElementById('btn-text');
            const btnIcon = document.getElementById('btn-icon');
            const btnSpinner = document.getElementById('btn-spinner');

            btn.disabled = true;
            btnText.innerText = 'Scheduling & Sending Emails...';
            btnIcon.classList.add('hidden');
            btnSpinner.classList.remove('hidden');
        }
    </script>
</body>
</html>