<?php
// school_admission/public/branch_delete_applicant_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(['branch_admin']); // Only Branch Admin can delete applicants

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

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

$conn->begin_transaction();
try {
    // 1. Fetch applicant details to verify ownership and status
    $stmt_check = $conn->prepare("SELECT branch_id, status FROM applicants WHERE applicant_id = ? FOR UPDATE"); // Lock row
    $stmt_check->bind_param("i", $applicant_id);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows === 0) {
        throw new Exception("Applicant not found.");
    }
    $applicant_data = $result_check->fetch_assoc();
    $stmt_check->close();

    // Verify applicant belongs to this branch admin's branch
    if ($applicant_data['branch_id'] != $current_branch_id) {
        throw new Exception("You do not have permission to delete this applicant.");
    }

    // Only allow deletion if the application status is 'pending_review'
    if ($applicant_data['status'] !== 'pending_review') {
        throw new Exception("Cannot delete application with status '<strong>" . ucwords(str_replace('_', ' ', $applicant_data['status'])) . "</strong>'. Only 'Pending Review' applications can be deleted.");
    }

    // 2. Delete the applicant record.
    // Due to ON DELETE CASCADE rules in the database, related records in
    // academic_records, uploaded_documents, payments, and admission_letters
    // tables will automatically be deleted.
    $stmt_delete = $conn->prepare("DELETE FROM applicants WHERE applicant_id = ?");
    $stmt_delete->bind_param("i", $applicant_id);

    if (!$stmt_delete->execute()) {
        throw new Exception("Failed to delete applicant: " . $stmt_delete->error);
    }
    $stmt_delete->close();

    $conn->commit();
    $_SESSION['message'] = "<div class='message success'>Applicant (ID: " . $applicant_id . ") and all associated records deleted successfully.</div>";
    redirect('branch_view_applicants.php');

} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['message'] = "<div class='message error'>Deletion failed: " . htmlspecialchars($e->getMessage()) . "</div>";
    error_log("Applicant deletion failed for applicant " . $applicant_id . " by user " . $_SESSION['user_id'] . ": " . $e->getMessage());
    redirect('branch_view_applicants.php');
}

$conn->close();
?>