<?php
require __DIR__ . '/_bootstrap.php';
require_admin();

// CSRF check
$posted = $_POST['csrf'] ?? '';
$sessionToken = $_SESSION['csrf_token'] ?? $_SESSION['csrf'] ?? null;
if (!$sessionToken || !hash_equals($sessionToken, $posted)) {
  http_response_code(403);
  header('Location: ' . url_for('/admin/admins.php?msg=' . urlencode('❌ Invalid CSRF. Please try again.')));
  exit;
}

$id = (int)($_POST['id'] ?? 0);
$currentAdminId = (int)($_SESSION['admin']['id'] ?? 0);

// Prevent deleting yourself
if ($id === $currentAdminId) {
  header('Location: ' . url_for('/admin/admins.php?msg=' . urlencode('❌ You cannot delete your own admin account.')));
  exit;
}

// Prevent deleting the last admin
$total = (int)$pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();
if ($total <= 1) {
  header('Location: ' . url_for('/admin/admins.php?msg=' . urlencode('❌ Cannot delete the last admin account.')));
  exit;
}

// Proceed
if ($id > 0) {
  $del = $pdo->prepare("DELETE FROM admins WHERE id=?");
  $del->execute([$id]);
}

header('Location: ' . url_for('/admin/admins.php?msg=' . urlencode('✅ Admin deleted.')));
exit;
