<?php
require_once '../../includes/auth.php';
require_once '../../db.php';

if (($_SESSION['user_role'] ?? '') !== 'admin') {
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    header('Location: index.php');
    exit;
}

$role = $conn->query("SELECT * FROM roles WHERE id = $id")->fetch_assoc();
if (!$role) {
    header('Location: index.php');
    exit;
}

// System roles cannot be deleted
if ($role['is_system']) {
    header('Location: index.php?error=system_role');
    exit;
}

// Reassign users to NULL before deleting role
$conn->query("UPDATE users SET role_id = NULL WHERE role_id = $id");

// Delete (role_permissions cascade via FK)
$conn->query("DELETE FROM roles WHERE id = $id");

header('Location: index.php?deleted=1');
exit;
