<?php
// school_admission/public/admin_delete_branch_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 delete branches

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

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

// Check if there are any users or applicants associated with this branch first
$can_delete = true;
$error_reason = "";

$stmt_check_users = $conn->prepare("SELECT COUNT(*) FROM users WHERE branch_id = ?");
$stmt_check_users->bind_param("i", $branch_id);
$stmt_check_users->execute();
$stmt_check_users->bind_result($user_count);
$stmt_check_users->fetch();
$stmt_check_users->close();

if ($user_count > 0) {
    $can_delete = false;
    $error_reason = "There are " . $user_count . " users (branch representatives) associated with this branch. Please reassign or delete them first.";
}

if ($can_delete) {
    $stmt_check_applicants = $conn->prepare("SELECT COUNT(*) FROM applicants WHERE branch_id = ?");
    $stmt_check_applicants->bind_param("i", $branch_id);
    $stmt_check_applicants->execute();
    $stmt_check_applicants->bind_result($applicant_count);
    $stmt_check_applicants->fetch();
    $stmt_check_applicants->close();

    if ($applicant_count > 0) {
        $can_delete = false;
        $error_reason = "There are " . $applicant_count . " applicants associated with this branch. You cannot delete a branch with active applications.";
    }
}


if ($can_delete) {
    $stmt = $conn->prepare("DELETE FROM branches WHERE branch_id = ?");
    $stmt->bind_param("i", $branch_id);

    if ($stmt->execute()) {
        $_SESSION['message'] = "<div class='message success'>Branch deleted successfully!</div>";
    } else {
        $_SESSION['message'] = "<div class='message error'>Error deleting branch: " . $stmt->error . "</div>";
    }
    $stmt->close();
} else {
    $_SESSION['message'] = "<div class='message error'>Cannot delete branch: " . $error_reason . "</div>";
}


redirect('admin_manage_branches.php');
$conn->close();
?>