<?php
// ============================================================
//  user_delete.php — Single User Delete Handler
//  Place in: /admin/user_delete.php
//  Called via GET link with CSRF token, redirects back to users
// ============================================================
require_once 'includes/auth_check.php';

$user_id    = (int)($_GET['id'] ?? 0);
$csrf_token = $_GET['csrf'] ?? '';

// Validate CSRF
if ($csrf_token !== ($_SESSION['csrf_token'] ?? '')) {
    $_SESSION['flash_error'] = 'Invalid request token.';
    header('Location: users.php');
    exit;
}

if ($user_id <= 0) {
    $_SESSION['flash_error'] = 'Invalid user ID.';
    header('Location: users.php');
    exit;
}

// Fetch user for logging
$user = db_fetch_one("SELECT id, full_name, email FROM users WHERE id = ?", [$user_id]);

if (!$user) {
    $_SESSION['flash_error'] = 'User not found.';
    header('Location: users.php');
    exit;
}

// Delete the user
db_execute("DELETE FROM users WHERE id = ?", [$user_id]);

// Log activity
db_execute(
    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
     VALUES (?, 'deleted_user', 'user', ?, ?, ?, ?)",
    [
        $current_admin['id'],
        $user_id,
        $user['full_name'],
        "Deleted user: {$user['full_name']} ({$user['email']})",
        $_SERVER['REMOTE_ADDR']
    ]
);

$_SESSION['flash_success'] = "User \"{$user['full_name']}\" was permanently deleted.";
header('Location: users.php');
exit;
