<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('roles.manage');

require_once __DIR__ . '/../config/database.php';

$roleId = (int)$_GET['id'];

/* =============================
   PROTECT SUPER ADMIN
============================= */

if ($roleId === 1) {
    die("Super Admin role cannot be deleted.");
}

/* =============================
   CHECK IF USERS EXIST
============================= */

$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE role_id = ?");
$stmt->execute([$roleId]);

$userCount = $stmt->fetchColumn();

if ($userCount > 0) {
    die("Cannot delete role. Users are assigned to this role.");
}

/* =============================
   DELETE ROLE
============================= */

$pdo->beginTransaction();

try {

    // Remove role permissions
    $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?")
        ->execute([$roleId]);

    // Delete role
    $pdo->prepare("DELETE FROM roles WHERE id = ?")
        ->execute([$roleId]);

    $pdo->commit();

    header("Location: roles.php");
    exit;

} catch (Exception $e) {

    $pdo->rollBack();
    die("Delete failed.");
}