<?php
// This is the first line of ANY secure admin page.
require_once 'includes/auth_check.php';

// Include your database and functions
require_once '../config/database.php';
require_once '../includes/functions.php';

// --- Security and Input Validation ---
// Check if the request method is POST for added security (prevents deletion via simple link click)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method.";
    header('Location: manage_users.php');
    exit;
}

// CSRF Check
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    $_SESSION['error_message'] = "Invalid security token. Please try again.";
    header('Location: manage_users.php');
    exit;
}

// Get User ID from POST data
$user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
if (!$user_id) {
    $_SESSION['error_message'] = "Invalid User ID provided.";
    header('Location: manage_users.php');
    exit;
}

// --- Deletion Logic ---
try {
    $database = new Database();
    $db = $database->getConnection();

    // It's good practice to start a transaction in case multiple tables need to be cleaned up
    $db->beginTransaction();

    // First, get the user's name for the success message before deleting
    $name_stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = :id");
    $name_stmt->execute([':id' => $user_id]);
    $user = $name_stmt->fetch(PDO::FETCH_ASSOC);
    $userName = $user ? htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) : "User #$user_id";

    // Prepare the DELETE statement
    // Because of FOREIGN KEY constraints with ON DELETE CASCADE, deleting the user
    // from the `users` table should automatically delete their related records in:
    // - account_balances
    // - activity_logs
    // - next_of_kin
    // - transactions
    // - etc.
    // This is a huge advantage of a well-designed database schema!
    $stmt = $db->prepare("DELETE FROM users WHERE id = :id AND role = 'user'");
    $stmt->bindParam(':id', $user_id, PDO::PARAM_INT);

    // Execute the deletion
    $stmt->execute();

    // Check if a row was actually deleted
    if ($stmt->rowCount() > 0) {
        // If deletion was successful, commit the transaction
        $db->commit();
        $_SESSION['success_message'] = "User '$userName' has been permanently deleted.";
    } else {
        // If no rows were affected (e.g., user ID didn't exist), rollback and set an error
        $db->rollBack();
        $_SESSION['error_message'] = "Could not delete user. The user may have already been removed.";
    }

} catch (PDOException $e) {
    // If any database error occurs, rollback the transaction
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    error_log("Delete User DB Error: " . $e->getMessage());
    $_SESSION['error_message'] = "A database error occurred while trying to delete the user.";
}

// Redirect back to the user management page
header('Location: manage_users.php');
exit;
