<?php
/**
 * Admin - Delete User
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'admin/users.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'admin/users.php', 'error', 'Invalid security token');
}

$user_id = intval($_POST['user_id'] ?? 0);

if (!$user_id) {
    redirect(BASE_URL . 'admin/users.php', 'error', 'Invalid user ID');
}

try {
    // Check if user exists
    $stmt = db()->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    if (!$stmt->fetch()) {
        redirect(BASE_URL . 'admin/users.php', 'error', 'User not found');
    }
    
    // Delete user's related data (subscriptions, transactions, etc.)
    db()->beginTransaction();
    
    // Delete user subscriptions
    $stmt = db()->prepare("DELETE FROM user_subscriptions WHERE user_id = ?");
    $stmt->execute([$user_id]);
    
    // Delete user transactions
    $stmt = db()->prepare("DELETE FROM transactions WHERE user_id = ?");
    $stmt->execute([$user_id]);
    
    // Delete user notifications
    $stmt = db()->prepare("DELETE FROM user_notifications WHERE user_id = ?");
    $stmt->execute([$user_id]);
    
    // Delete user
    $stmt = db()->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    
    db()->commit();
    
    // Log activity
    log_activity('user_deleted', "Deleted user ID: $user_id", $_SESSION['admin_id'], 'admin');
    
    redirect(BASE_URL . 'admin/users.php', 'success', 'User deleted successfully');
    
} catch (PDOException $e) {
    db()->rollBack();
    error_log("Delete user error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/users.php', 'error', 'Failed to delete user');
}
