<?php
require_once '../includes/require_admin.php';

// Only allow POST requests for deletion
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(SITE_URL . '/admin/manage_users.php');
}

// Get user ID from POST data
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;

// Validate user ID
if ($user_id <= 0) {
    $_SESSION['error_message'] = "Invalid user ID.";
    redirect(SITE_URL . '/admin/manage_users.php');
}

// Prevent users from deleting themselves
if ($user_id == $_SESSION['user_id']) {
    $_SESSION['error_message'] = "You cannot delete your own account.";
    redirect(SITE_URL . '/admin/manage_users.php');
}

try {
    // Delete the user
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    
    // Also delete any associated cart items
    $stmt = $pdo->prepare("DELETE FROM cart WHERE user_id = ?");
    $stmt->execute([$user_id]);
    
    // Also delete any associated orders (which will cascade to order_items)
    $stmt = $pdo->prepare("DELETE FROM orders WHERE user_id = ?");
    $stmt->execute([$user_id]);
    
    $_SESSION['success_message'] = "User deleted successfully.";
} catch (PDOException $e) {
    $_SESSION['error_message'] = "Error deleting user: " . $e->getMessage();
}

redirect(SITE_URL . '/admin/manage_users.php');
?>