<?php
// school_admission/public/admin_approve_application_action.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['super_admin']); // Only Super Admin can approve applications

$applicant_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$admin_user_id = $_SESSION['user_id'];

if ($applicant_id === 0) {
    $_SESSION['message'] = "<div class='message error'>Invalid applicant ID.</div>";
    redirect('admin_view_applications.php');
}

$conn->begin_transaction();
try {
    // 1. Fetch applicant data to generate letter
    $stmt_applicant_data = $conn->prepare("
        SELECT
            a.*,
            c.course_name,
            c.description AS course_description,
            b.branch_name,
            b.location AS branch_location
        FROM
            applicants a
        JOIN
            courses c ON a.course_id = c.course_id
        JOIN
            branches b ON a.branch_id = b.branch_id
        WHERE
            a.applicant_id = ?
        FOR UPDATE
    "); // LOCK THE ROW
    $stmt_applicant_data->bind_param("i", $applicant_id);
    $stmt_applicant_data->execute();
    $result_applicant_data = $stmt_applicant_data->get_result();
    if ($result_applicant_data->num_rows === 0) {
        throw new Exception("Applicant not found.");
    }
    $applicant_data = $result_applicant_data->fetch_assoc();
    $stmt_applicant_data->close();

    if ($applicant_data['status'] !== 'pending_review') {
        throw new Exception("Application is already " . ucwords(str_replace('_', ' ', $applicant_data['status'])) . ". Cannot approve again.");
    }

    // 2. Update applicant status
    $status = 'approved';
    $approval_date = date('Y-m-d H:i:s');
    $stmt_update_status = $conn->prepare("UPDATE applicants SET status = ?, approved_by_user_id = ?, approval_date = ? WHERE applicant_id = ?");
    $stmt_update_status->bind_param("sisi", $status, $admin_user_id, $approval_date, $applicant_id);
    if (!$stmt_update_status->execute()) {
        throw new Exception("Failed to update applicant status: " . $stmt_update_status->error);
    }
    $stmt_update_status->close();

    // 3. Generate Admission Letter
    // Fetch registrar's name (assuming super_admin is the registrar for simplicity, or have a specific registrar user)
    $registrar_name = "Saidu Kabiru"; // Hardcoded for now, or fetch from users table for 'registrar' role

    ob_start(); // Start output buffering
    include __DIR__ . '/../views/templates/admission_letter_template.php'; // Include the template
    $letter_content = ob_get_clean(); // Get the HTML content

    // 4. Save letter content to database
    $stmt_insert_letter = $conn->prepare("INSERT INTO admission_letters (applicant_id, letter_content, generated_by_user_id) VALUES (?, ?, ?)");
    $stmt_insert_letter->bind_param("isi", $applicant_id, $letter_content, $admin_user_id);
    if (!$stmt_insert_letter->execute()) {
        throw new Exception("Failed to save admission letter: " . $stmt_insert_letter->error);
    }
    $stmt_insert_letter->close();

    // 5. Update applicant status again to indicate letter generated
    $status_letter_generated = 'admission_letter_generated';
    $stmt_update_status_letter = $conn->prepare("UPDATE applicants SET status = ? WHERE applicant_id = ?");
    $stmt_update_status_letter->bind_param("si", $status_letter_generated, $applicant_id);
    if (!$stmt_update_status_letter->execute()) {
        throw new Exception("Failed to update applicant status to letter generated: " . $stmt_update_status_letter->error);
    }
    $stmt_update_status_letter->close();

    $conn->commit();
    $_SESSION['message'] = "<div class='message success'>Application for <strong>" . htmlspecialchars($applicant_data['first_name'] . ' ' . $applicant_data['last_name']) . "</strong> approved and admission letter generated successfully!</div>";
    redirect('admin_application_details.php?id=' . $applicant_id);

} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['message'] = "<div class='message error'>Approval failed: " . $e->getMessage() . "</div>";
    error_log("Approval failed for applicant " . $applicant_id . ": " . $e->getMessage());
    redirect('admin_application_details.php?id=' . $applicant_id);
}

$conn->close();
?>