<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['role_id'])) {
    $role_id = $_POST['role_id'];

    try {
        // Check if role has any users
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM user_roles WHERE role_id = ?");
        $stmt->bind_param("i", $role_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();

        if ($row['count'] > 0) {
            $_SESSION['error'] = "Cannot delete role: Users are still assigned to this role";
            header("Location: all_roles.php");
            exit();
        }

        // Delete the role
        $stmt = $conn->prepare("DELETE FROM user_role WHERE role_id = ?");
        $stmt->bind_param("i", $role_id);

        if ($stmt->execute()) {
            $_SESSION['success'] = "Role deleted successfully";
        } else {
            throw new Exception($stmt->error);
        }
    } catch (Exception $e) {
        $_SESSION['error'] = "Error deleting role: " . $e->getMessage();
    }
} else {
    $_SESSION['error'] = "Invalid request";
}

header("Location: all_roles.php");
exit();
?>