<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}
require_once '../src/config/db.php';
require_once '../src/includes/functions.php';

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // Fetch user to check if it's the logged-in user
    $user = get_user_by_id($pdo, $id);
    
    if (!$user) {
        header('Location: users.php?error=not_found');
        exit;
    }
    
    // Prevent self-deletion
    if ($user['username'] === $_SESSION['admin_username']) {
        header('Location: users.php?error=self_delete');
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);
        header('Location: users.php?success=delete');
        exit;
    } catch (\PDOException $e) {
        die("حدث خطأ أثناء حذف المستخدم: " . $e->getMessage());
    }
} else {
    header('Location: users.php');
    exit;
}
?>
