<?php
// school_admission/public/admin_reject_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 reject 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. Check current status
    $stmt_check_status = $conn->prepare("SELECT status FROM applicants WHERE applicant_id = ? FOR UPDATE");
    $stmt_check_status->bind_param("i", $applicant_id);
    $stmt_check_status->execute();
    $result_check_status = $stmt_check_status->get_result();
    if ($result_check_status->num_rows === 0) {
        throw new Exception("Applicant not found.");
    }
    $current_status = $result_check_status->fetch_assoc()['status'];
    $stmt_check_status->close();

    if ($current_status !== 'pending_review') {
        throw new Exception("Application is already " . ucwords(str_replace('_', ' ', $current_status)) . ". Cannot reject.");
    }

    // 2. Update applicant status to rejected
    $status = 'rejected';
    $approval_date = date('Y-m-d H:i:s'); // Use approval_date for rejection too, or add a specific rejection_date column
    $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 to rejected: " . $stmt_update_status->error);
    }
    $stmt_update_status->close();

    $conn->commit();
    $_SESSION['message'] = "<div class='message success'>Application (ID: " . $applicant_id . ") successfully rejected.</div>";
    redirect('admin_application_details.php?id=' . $applicant_id);

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

$conn->close();
?>