<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$currentUserId = (int)($_SESSION['user_id'] ?? 0);

if ($id <= 0) {
    die("Invalid user ID.");
}

if ($id === $currentUserId) {
    die("You cannot delete your own account.");
}

try {
    $checkStmt = $db->prepare("SELECT id FROM users WHERE id = :id LIMIT 1");
    $checkStmt->bindParam(':id', $id, PDO::PARAM_INT);
    $checkStmt->execute();

    if (!$checkStmt->fetch(PDO::FETCH_ASSOC)) {
        die("User not found.");
    }

    $deleteStmt = $db->prepare("DELETE FROM users WHERE id = :id");
    $deleteStmt->bindParam(':id', $id, PDO::PARAM_INT);
    $deleteStmt->execute();

    header("Location: users.php?deleted=1");
    exit;
} catch (PDOException $e) {
    die("Delete failed: " . $e->getMessage());
}