<?php
// school_admission/public/admin_delete_user_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 users

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

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

if ($user_id_to_delete === $logged_in_user_id) {
    $_SESSION['message'] = "<div class='message error'>You cannot delete your own account while logged in.</div>";
    redirect('admin_manage_users.php');
}

// Optional: Check if the user to be deleted is the *last* super_admin
// This prevents accidental lockout if you delete all super_admin accounts
$stmt_check_super_admins = $conn->prepare("SELECT COUNT(*) FROM users WHERE role = 'super_admin'");
$stmt_check_super_admins->execute();
$stmt_check_super_admins->bind_result($super_admin_count);
$stmt_check_super_admins->fetch();
$stmt_check_super_admins->close();

$stmt_get_role = $conn->prepare("SELECT role FROM users WHERE user_id = ?");
$stmt_get_role->bind_param("i", $user_id_to_delete);
$stmt_get_role->execute();
$stmt_get_role->bind_result($deleted_user_role);
$stmt_get_role->fetch();
$stmt_get_role->close();

if ($deleted_user_role === 'super_admin' && $super_admin_count <= 1) {
    $_SESSION['message'] = "<div class='message error'>Cannot delete the last Super Admin account. Create another Super Admin first if you need to remove this one.</div>";
    redirect('admin_manage_users.php');
}


// Check for associated records before deletion
$can_delete = true;
$error_reason = "";

// Check if this user approved any applications
$stmt_check_approved_apps = $conn->prepare("SELECT COUNT(*) FROM applicants WHERE approved_by_user_id = ?");
$stmt_check_approved_apps->bind_param("i", $user_id_to_delete);
$stmt_check_approved_apps->execute();
$stmt_check_approved_apps->bind_result($approved_apps_count);
$stmt_check_approved_apps->fetch();
$stmt_check_approved_apps->close();

if ($approved_apps_count > 0) {
    // If a user approved applications, consider if you want to allow deletion (setting approved_by_user_id to NULL)
    // Or prevent it, or reassign. For simplicity here, we'll set to NULL.
    $stmt_null_approvals = $conn->prepare("UPDATE applicants SET approved_by_user_id = NULL WHERE approved_by_user_id = ?");
    $stmt_null_approvals->bind_param("i", $user_id_to_delete);
    $stmt_null_approvals->execute();
    $stmt_null_approvals->close();
    $error_reason .= "User approved " . $approved_apps_count . " applications. Their approval records have been unlinked. ";
}

// Check if this user recorded any payments
$stmt_check_payments = $conn->prepare("SELECT COUNT(*) FROM payments WHERE recorded_by_user_id = ?");
$stmt_check_payments->bind_param("i", $user_id_to_delete);
$stmt_check_payments->execute();
$stmt_check_payments->bind_result($payments_count);
$stmt_check_payments->fetch();
$stmt_check_payments->close();

if ($payments_count > 0) {
    // If a user recorded payments, consider if you want to allow deletion (setting recorded_by_user_id to NULL)
    // Or prevent it, or reassign. For simplicity here, we'll set to NULL.
    $stmt_null_payments = $conn->prepare("UPDATE payments SET recorded_by_user_id = NULL WHERE recorded_by_user_id = ?");
    $stmt_null_payments->bind_param("i", $user_id_to_delete);
    $stmt_null_payments->execute();
    $stmt_null_payments->close();
    $error_reason .= "User recorded " . $payments_count . " payments. Their payment records have been unlinked. ";
}


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

    if ($stmt->execute()) {
        $_SESSION['message'] = "<div class='message success'>User deleted successfully!" . (!empty($error_reason) ? "<br>" . $error_reason : "") . "</div>";
    } else {
        $_SESSION['message'] = "<div class='message error'>Error deleting user: " . $stmt->error . "</div>";
    }
    $stmt->close();
} else {
    // This branch is mostly for the 'last super admin' check now.
    $_SESSION['message'] = "<div class='message error'>Cannot delete user: " . $error_reason . "</div>";
}

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