<?php
/**
 * Pure Chemical Admin
 * Roles Management
 *
 * Existing table:
 * roles
 *
 * Columns:
 * id, name, slug, description, is_super_admin, status,
 * created_at, updated_at
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}

/* -------------------------------------------------------
   Helpers
------------------------------------------------------- */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('verify_csrf')) {
    function verify_csrf()
    {
        $token = $_POST['csrf_token'] ?? '';

        return !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $token);
    }
}

if (!function_exists('slugify')) {
    function slugify($text)
    {
        $text = trim($text);
        $text = strtolower($text);

        $text = preg_replace('/[^a-z0-9]+/i', '-', $text);
        $text = trim($text, '-');

        return $text;
    }
}

/* -------------------------------------------------------
   Flash Messages
------------------------------------------------------- */

$success = $_SESSION['roles_success'] ?? '';
$error   = $_SESSION['roles_error'] ?? '';

unset($_SESSION['roles_success'], $_SESSION['roles_error']);

/* -------------------------------------------------------
   Current User / Role
------------------------------------------------------- */

$currentUserId = (int)(
    $_SESSION['USER_ID']
    ?? $_SESSION['user_id']
    ?? $_SESSION['ADMIN_ID']
    ?? $_SESSION['admin_id']
    ?? 0
);

/* -------------------------------------------------------
   Handle Actions
------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!verify_csrf()) {
        $_SESSION['roles_error'] = 'Security token expired. Please try again.';
        header('Location: roles.php');
        exit;
    }

    $action = $_POST['action'] ?? '';

    /* ---------------------------------------------------
       SAVE ROLE
    --------------------------------------------------- */

    if ($action === 'save') {

        $id = (int)($_POST['id'] ?? 0);

        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $description = trim($_POST['description'] ?? '');

        $isSuperAdmin = isset($_POST['is_super_admin']) ? 1 : 0;
        $status       = isset($_POST['status']) ? 1 : 0;

        if ($slug === '') {
            $slug = slugify($name);
        } else {
            $slug = slugify($slug);
        }

        if ($name === '') {
            $_SESSION['roles_error'] = 'Role name is required.';
            header('Location: roles.php');
            exit;
        }

        if (mb_strlen($name) > 100) {
            $_SESSION['roles_error'] = 'Role name cannot exceed 100 characters.';
            header('Location: roles.php');
            exit;
        }

        if ($slug === '') {
            $_SESSION['roles_error'] = 'Valid role slug is required.';
            header('Location: roles.php');
            exit;
        }

        if (mb_strlen($slug) > 120) {
            $_SESSION['roles_error'] = 'Role slug cannot exceed 120 characters.';
            header('Location: roles.php');
            exit;
        }

        if (mb_strlen($description) > 10000) {
            $_SESSION['roles_error'] = 'Description is too long.';
            header('Location: roles.php');
            exit;
        }

        /* Duplicate name */
        $stmt = $pdo->prepare("
            SELECT id
            FROM roles
            WHERE LOWER(name) = LOWER(:name)
              AND id != :id
            LIMIT 1
        ");

        $stmt->execute([
            ':name' => $name,
            ':id'   => $id
        ]);

        if ($stmt->fetch()) {
            $_SESSION['roles_error'] = 'A role with this name already exists.';
            header('Location: roles.php');
            exit;
        }

        /* Duplicate slug */
        $stmt = $pdo->prepare("
            SELECT id
            FROM roles
            WHERE LOWER(slug) = LOWER(:slug)
              AND id != :id
            LIMIT 1
        ");

        $stmt->execute([
            ':slug' => $slug,
            ':id'   => $id
        ]);

        if ($stmt->fetch()) {
            $_SESSION['roles_error'] = 'A role with this slug already exists.';
            header('Location: roles.php');
            exit;
        }

        try {

            if ($id > 0) {

                /*
                 * Existing role
                 */
                $stmt = $pdo->prepare("
                    UPDATE roles
                    SET
                        name = :name,
                        slug = :slug,
                        description = :description,
                        is_super_admin = :is_super_admin,
                        status = :status
                    WHERE id = :id
                    LIMIT 1
                ");

                $stmt->execute([
                    ':name'          => $name,
                    ':slug'          => $slug,
                    ':description'   => $description !== '' ? $description : null,
                    ':is_super_admin' => $isSuperAdmin,
                    ':status'        => $status,
                    ':id'            => $id
                ]);

                $_SESSION['roles_success'] = 'Role updated successfully.';

            } else {

                /*
                 * New role
                 */
                $stmt = $pdo->prepare("
                    INSERT INTO roles
                    (
                        name,
                        slug,
                        description,
                        is_super_admin,
                        status
                    )
                    VALUES
                    (
                        :name,
                        :slug,
                        :description,
                        :is_super_admin,
                        :status
                    )
                ");

                $stmt->execute([
                    ':name'           => $name,
                    ':slug'           => $slug,
                    ':description'    => $description !== '' ? $description : null,
                    ':is_super_admin' => $isSuperAdmin,
                    ':status'         => $status
                ]);

                $_SESSION['roles_success'] = 'Role created successfully.';
            }

        } catch (PDOException $ex) {

            error_log('Roles Save Error: ' . $ex->getMessage());

            $_SESSION['roles_error'] = 'Unable to save role. Please try again.';
        }

        header('Location: roles.php');
        exit;
    }

    /* ---------------------------------------------------
       TOGGLE STATUS
    --------------------------------------------------- */

    if ($action === 'toggle_status') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            $_SESSION['roles_error'] = 'Invalid role.';
            header('Location: roles.php');
            exit;
        }

        try {

            $stmt = $pdo->prepare("
                SELECT id, status, is_super_admin
                FROM roles
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            $role = $stmt->fetch();

            if (!$role) {
                $_SESSION['roles_error'] = 'Role not found.';
                header('Location: roles.php');
                exit;
            }

            /*
             * Super admin roles should not accidentally
             * be disabled from this screen.
             */
            if ((int)$role['is_super_admin'] === 1) {
                $_SESSION['roles_error'] =
                    'Super Admin role status cannot be changed from here.';
                header('Location: roles.php');
                exit;
            }

            $newStatus = ((int)$role['status'] === 1) ? 0 : 1;

            $stmt = $pdo->prepare("
                UPDATE roles
                SET status = :status
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':status' => $newStatus,
                ':id'     => $id
            ]);

            $_SESSION['roles_success'] =
                $newStatus
                    ? 'Role activated successfully.'
                    : 'Role deactivated successfully.';

        } catch (PDOException $ex) {

            error_log('Roles Status Error: ' . $ex->getMessage());

            $_SESSION['roles_error'] =
                'Unable to update role status.';
        }

        header('Location: roles.php');
        exit;
    }

    /* ---------------------------------------------------
       DELETE ROLE
    --------------------------------------------------- */

    if ($action === 'delete') {

        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            $_SESSION['roles_error'] = 'Invalid role.';
            header('Location: roles.php');
            exit;
        }

        try {

            /*
             * Check role
             */
            $stmt = $pdo->prepare("
                SELECT id, name, is_super_admin
                FROM roles
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            $role = $stmt->fetch();

            if (!$role) {
                $_SESSION['roles_error'] = 'Role not found.';
                header('Location: roles.php');
                exit;
            }

            /*
             * Never delete super admin role.
             */
            if ((int)$role['is_super_admin'] === 1) {
                $_SESSION['roles_error'] =
                    'Super Admin role cannot be deleted.';
                header('Location: roles.php');
                exit;
            }

            /*
             * Check users assigned to this role.
             */
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM users
                WHERE role_id = :role_id
            ");

            $stmt->execute([
                ':role_id' => $id
            ]);

            $assignedUsers = (int)$stmt->fetchColumn();

            if ($assignedUsers > 0) {

                $_SESSION['roles_error'] =
                    'This role is assigned to ' .
                    $assignedUsers .
                    ' user(s). Reassign those users before deleting the role.';

                header('Location: roles.php');
                exit;
            }

            /*
             * Check role permissions.
             */
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM role_permissions
                WHERE role_id = :role_id
            ");

            $stmt->execute([
                ':role_id' => $id
            ]);

            $permissionCount = (int)$stmt->fetchColumn();

            if ($permissionCount > 0) {

                $_SESSION['roles_error'] =
                    'This role has permissions assigned. Remove its permissions before deleting it.';

                header('Location: roles.php');
                exit;
            }

            /*
             * Delete
             */
            $stmt = $pdo->prepare("
                DELETE FROM roles
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $id
            ]);

            $_SESSION['roles_success'] =
                'Role "' . $role['name'] . '" deleted successfully.';

        } catch (PDOException $ex) {

            error_log('Roles Delete Error: ' . $ex->getMessage());

            $_SESSION['roles_error'] =
                'Unable to delete this role. It may still be referenced somewhere.';
        }

        header('Location: roles.php');
        exit;
    }
}

/* -------------------------------------------------------
   Filters
------------------------------------------------------- */

$search = trim($_GET['search'] ?? '');
$statusFilter = $_GET['status'] ?? '';
$superFilter = $_GET['super_admin'] ?? '';

/* -------------------------------------------------------
   Stats
------------------------------------------------------- */

$totalRoles = (int)$pdo
    ->query("SELECT COUNT(*) FROM roles")
    ->fetchColumn();

$activeRoles = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM roles
        WHERE status = 1
    ")
    ->fetchColumn();

$inactiveRoles = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM roles
        WHERE status = 0
    ")
    ->fetchColumn();

$superAdminRoles = (int)$pdo
    ->query("
        SELECT COUNT(*)
        FROM roles
        WHERE is_super_admin = 1
    ")
    ->fetchColumn();

/* -------------------------------------------------------
   Build Role Query
------------------------------------------------------- */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            r.name LIKE :search
            OR r.slug LIKE :search
            OR r.description LIKE :search
        )
    ";

    $params[':search'] = '%' . $search . '%';
}

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {

    $where[] = "r.status = :status";

    $params[':status'] = (int)$statusFilter;
}

if ($superFilter !== '' && in_array($superFilter, ['0', '1'], true)) {

    $where[] = "r.is_super_admin = :super_admin";

    $params[':super_admin'] = (int)$superFilter;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/*
 * Users assigned count
 */
$sql = "
    SELECT
        r.id,
        r.name,
        r.slug,
        r.description,
        r.is_super_admin,
        r.status,
        r.created_at,
        r.updated_at,
        COUNT(DISTINCT u.id) AS users_count,
        COUNT(DISTINCT rp.permission_id) AS permissions_count
    FROM roles r
    LEFT JOIN users u
        ON u.role_id = r.id
    LEFT JOIN role_permissions rp
        ON rp.role_id = r.id
    {$whereSql}
    GROUP BY
        r.id,
        r.name,
        r.slug,
        r.description,
        r.is_super_admin,
        r.status,
        r.created_at,
        r.updated_at
    ORDER BY
        r.is_super_admin DESC,
        r.status DESC,
        r.id DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$roles = $stmt->fetchAll();

/* -------------------------------------------------------
   HTML
------------------------------------------------------- */
?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Roles Management | Pure Chemical Admin</title>

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --primary: #16a34a;
            --primary-dark: #15803d;
            --primary-soft: #ecfdf3;

            --dark: #0f172a;
            --text: #334155;
            --muted: #64748b;

            --border: #e2e8f0;
            --bg: #f8fafc;
            --white: #ffffff;

            --success: #16a34a;
            --danger: #dc2626;
            --warning: #d97706;

            --shadow-sm:
                0 1px 2px rgba(15, 23, 42, .05);

            --shadow:
                0 12px 35px rgba(15, 23, 42, .08);

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background:
                radial-gradient(
                    circle at top right,
                    rgba(22, 163, 74, .06),
                    transparent 28%
                ),
                var(--bg);

            color: var(--text);
            font-family: 'Inter', sans-serif;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        /* -------------------------------------------------
           MAIN
        ------------------------------------------------- */

        .roles-page {
            margin-left: 280px;
            min-height: 100vh;
        }

        /* -------------------------------------------------
           TOPBAR
        ------------------------------------------------- */

        .topbar {
            position: sticky;
            top: 0;
            z-index: 90;

            height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 30px;

            background: rgba(255,255,255,.88);
            backdrop-filter: blur(18px);

            border-bottom: 1px solid rgba(226,232,240,.8);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-icon {
            width: 44px;
            height: 44px;

            border-radius: 13px;

            display: flex;
            align-items: center;
            justify-content: center;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #16a34a,
                    #15803d
                );

            box-shadow:
                0 8px 20px rgba(22,163,74,.20);
        }

        .topbar-title h1 {
            margin: 0;

            color: var(--dark);

            font-size: 18px;
            font-weight: 800;
        }

        .topbar-title p {
            margin: 3px 0 0;

            color: var(--muted);

            font-size: 12px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .topbar-btn {
            height: 42px;

            padding: 0 15px;

            border: 1px solid var(--border);
            border-radius: 12px;

            display: inline-flex;
            align-items: center;
            gap: 8px;

            background: #fff;

            color: var(--text);

            font-size: 13px;
            font-weight: 700;

            cursor: pointer;

            transition: .2s ease;
        }

        .topbar-btn:hover {
            border-color: #bbf7d0;
            color: var(--primary-dark);
            transform: translateY(-1px);
        }

        .topbar-btn.primary {
            border-color: transparent;
            background: var(--primary);
            color: #fff;
        }

        .topbar-btn.primary:hover {
            background: var(--primary-dark);
            color: #fff;
        }

        /* -------------------------------------------------
           CONTENT
        ------------------------------------------------- */

        .content {
            padding: 30px;
        }

        .page-heading {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;
            gap: 20px;

            margin-bottom: 25px;
        }

        .page-heading h2 {
            margin: 0;

            color: var(--dark);

            font-size: 27px;
            font-weight: 800;

            letter-spacing: -.7px;
        }

        .page-heading p {
            margin: 7px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        /* -------------------------------------------------
           ALERTS
        ------------------------------------------------- */

        .alert {
            display: flex;
            align-items: center;
            gap: 12px;

            margin-bottom: 20px;
            padding: 14px 16px;

            border-radius: 14px;

            font-size: 13px;
            font-weight: 600;
        }

        .alert.success {
            border: 1px solid #bbf7d0;
            background: #f0fdf4;
            color: #166534;
        }

        .alert.error {
            border: 1px solid #fecaca;
            background: #fef2f2;
            color: #991b1b;
        }

        /* -------------------------------------------------
           STATS
        ------------------------------------------------- */

        .stats-grid {
            display: grid;
            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 16px;

            margin-bottom: 24px;
        }

        .stat-card {
            position: relative;

            padding: 20px;

            overflow: hidden;

            background: #fff;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);
        }

        .stat-card::after {
            content: '';

            position: absolute;

            width: 80px;
            height: 80px;

            right: -25px;
            bottom: -30px;

            border-radius: 50%;

            background: var(--primary-soft);
        }

        .stat-top {
            display: flex;
            align-items: center;
            justify-content: space-between;

            margin-bottom: 13px;
        }

        .stat-icon {
            width: 42px;
            height: 42px;

            border-radius: 12px;

            display: flex;
            align-items: center;
            justify-content: center;

            background: var(--primary-soft);
            color: var(--primary);
        }

        .stat-number {
            color: var(--dark);

            font-size: 27px;
            font-weight: 800;
        }

        .stat-label {
            color: var(--muted);

            font-size: 12px;
            font-weight: 600;
        }

        /* -------------------------------------------------
           FILTER CARD
        ------------------------------------------------- */

        .filter-card {
            padding: 18px;

            margin-bottom: 20px;

            background: #fff;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);
        }

        .filter-form {
            display: grid;

            grid-template-columns:
                minmax(240px, 1fr)
                170px
                170px
                auto
                auto;

            gap: 10px;
        }

        .input-wrap {
            position: relative;
        }

        .input-wrap i {
            position: absolute;

            left: 14px;
            top: 50%;

            transform: translateY(-50%);

            color: #94a3b8;

            font-size: 13px;

            pointer-events: none;
        }

        .form-control {
            width: 100%;

            height: 44px;

            padding: 0 13px;

            border: 1px solid var(--border);
            border-radius: 12px;

            outline: none;

            background: #fff;

            color: var(--dark);

            font-size: 13px;

            transition: .2s ease;
        }

        .input-wrap .form-control {
            padding-left: 39px;
        }

        .form-control:focus {
            border-color: #86efac;

            box-shadow:
                0 0 0 4px rgba(34,197,94,.08);
        }

        select.form-control {
            cursor: pointer;
        }

        .filter-btn,
        .reset-btn {
            height: 44px;

            padding: 0 16px;

            border-radius: 12px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;

            cursor: pointer;

            font-size: 13px;
            font-weight: 700;
        }

        .filter-btn {
            border: 0;

            background: var(--dark);
            color: #fff;
        }

        .filter-btn:hover {
            background: #1e293b;
        }

        .reset-btn {
            border: 1px solid var(--border);

            background: #fff;
            color: var(--text);
        }

        /* -------------------------------------------------
           TABLE CARD
        ------------------------------------------------- */

        .table-card {
            overflow: hidden;

            background: #fff;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            box-shadow: var(--shadow);
        }

        .table-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 19px 20px;

            border-bottom: 1px solid var(--border);
        }

        .table-header h3 {
            margin: 0;

            color: var(--dark);

            font-size: 15px;
            font-weight: 800;
        }

        .result-count {
            color: var(--muted);

            font-size: 12px;
            font-weight: 600;
        }

        .table-scroll {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;

            min-width: 1000px;
        }

        th {
            padding: 13px 18px;

            background: #f8fafc;

            color: #64748b;

            border-bottom: 1px solid var(--border);

            text-align: left;

            font-size: 10px;
            font-weight: 800;

            letter-spacing: .7px;
            text-transform: uppercase;
        }

        td {
            padding: 16px 18px;

            border-bottom: 1px solid #f1f5f9;

            vertical-align: middle;

            font-size: 13px;
        }

        tbody tr {
            transition: .18s ease;
        }

        tbody tr:hover {
            background: #fbfffc;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        .role-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .role-avatar {
            width: 42px;
            height: 42px;

            flex: 0 0 42px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 12px;

            background:
                linear-gradient(
                    135deg,
                    #dcfce7,
                    #bbf7d0
                );

            color: #15803d;

            font-weight: 800;
        }

        .role-name {
            color: var(--dark);

            font-weight: 800;

            margin-bottom: 3px;
        }

        .role-slug {
            color: #94a3b8;

            font-size: 11px;
        }

        .description {
            max-width: 300px;

            color: var(--muted);

            font-size: 12px;

            line-height: 1.55;
        }

        /* -------------------------------------------------
           BADGES
        ------------------------------------------------- */

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 6px 9px;

            border-radius: 999px;

            font-size: 10px;
            font-weight: 800;
        }

        .badge.active {
            background: #dcfce7;
            color: #166534;
        }

        .badge.inactive {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge.super {
            background: #fef3c7;
            color: #92400e;
        }

        .badge.normal {
            background: #f1f5f9;
            color: #475569;
        }

        .count-pill {
            display: inline-flex;

            min-width: 30px;
            height: 28px;

            padding: 0 9px;

            align-items: center;
            justify-content: center;

            border-radius: 9px;

            background: #f1f5f9;

            color: #334155;

            font-size: 12px;
            font-weight: 800;
        }

        /* -------------------------------------------------
           ACTIONS
        ------------------------------------------------- */

        .actions {
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .action-btn {
            width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border-radius: 10px;

            border: 1px solid var(--border);

            background: #fff;

            color: #64748b;

            cursor: pointer;

            transition: .18s ease;
        }

        .action-btn:hover {
            transform: translateY(-1px);
        }

        .action-btn.edit:hover {
            color: var(--primary-dark);
            border-color: #bbf7d0;
            background: #f0fdf4;
        }

        .action-btn.status:hover {
            color: #0369a1;
            border-color: #bae6fd;
            background: #f0f9ff;
        }

        .action-btn.delete:hover {
            color: #dc2626;
            border-color: #fecaca;
            background: #fef2f2;
        }

        /* -------------------------------------------------
           EMPTY
        ------------------------------------------------- */

        .empty-state {
            padding: 70px 25px;

            text-align: center;
        }

        .empty-icon {
            width: 65px;
            height: 65px;

            margin: 0 auto 15px;

            border-radius: 18px;

            display: flex;
            align-items: center;
            justify-content: center;

            background: #f0fdf4;
            color: var(--primary);

            font-size: 25px;
        }

        .empty-state h3 {
            margin: 0 0 6px;

            color: var(--dark);

            font-size: 16px;
        }

        .empty-state p {
            margin: 0;

            color: var(--muted);

            font-size: 12px;
        }

        /* -------------------------------------------------
           MODAL
        ------------------------------------------------- */

        .modal {
            position: fixed;

            inset: 0;

            z-index: 999;

            display: none;

            align-items: center;
            justify-content: center;

            padding: 20px;

            background: rgba(15,23,42,.58);

            backdrop-filter: blur(6px);
        }

        .modal.show {
            display: flex;
        }

        .modal-box {
            width: min(620px, 100%);

            max-height: 90vh;

            overflow-y: auto;

            background: #fff;

            border-radius: 22px;

            box-shadow:
                0 30px 80px rgba(15,23,42,.25);

            animation: modalIn .2s ease;
        }

        @keyframes modalIn {
            from {
                opacity: 0;
                transform: translateY(15px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 21px 23px;

            border-bottom: 1px solid var(--border);
        }

        .modal-title {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .modal-title-icon {
            width: 40px;
            height: 40px;

            border-radius: 11px;

            display: flex;
            align-items: center;
            justify-content: center;

            background: #ecfdf5;
            color: var(--primary);
        }

        .modal-header h3 {
            margin: 0;

            color: var(--dark);

            font-size: 16px;
            font-weight: 800;
        }

        .modal-header p {
            margin: 3px 0 0;

            color: var(--muted);

            font-size: 11px;
        }

        .modal-close {
            width: 36px;
            height: 36px;

            border: 0;
            border-radius: 10px;

            background: #f8fafc;

            color: #64748b;

            cursor: pointer;
        }

        .modal-close:hover {
            background: #fee2e2;
            color: #dc2626;
        }

        .modal-body {
            padding: 23px;
        }

        .form-grid {
            display: grid;

            grid-template-columns: 1fr 1fr;

            gap: 16px;
        }

        .field.full {
            grid-column: 1 / -1;
        }

        .field label {
            display: block;

            margin-bottom: 7px;

            color: #334155;

            font-size: 12px;
            font-weight: 700;
        }

        .required {
            color: #dc2626;
        }

        textarea.form-control {
            min-height: 115px;

            height: auto;

            padding: 12px 13px;

            resize: vertical;
        }

        .checkbox-row {
            display: flex;
            align-items: center;
            gap: 10px;

            padding: 13px;

            border: 1px solid var(--border);
            border-radius: 12px;

            background: #f8fafc;
        }

        .checkbox-row input {
            width: 17px;
            height: 17px;

            accent-color: var(--primary);
        }

        .checkbox-content strong {
            display: block;

            color: var(--dark);

            font-size: 12px;
        }

        .checkbox-content span {
            display: block;

            margin-top: 2px;

            color: var(--muted);

            font-size: 10px;
        }

        .modal-footer {
            display: flex;
            align-items: center;
            justify-content: flex-end;

            gap: 9px;

            padding: 17px 23px;

            border-top: 1px solid var(--border);
        }

        .btn {
            min-height: 42px;

            padding: 0 17px;

            border-radius: 11px;

            border: 1px solid var(--border);

            background: #fff;

            color: var(--text);

            font-size: 12px;
            font-weight: 800;

            cursor: pointer;
        }

        .btn.primary {
            border-color: transparent;

            background: var(--primary);
            color: #fff;
        }

        .btn.primary:hover {
            background: var(--primary-dark);
        }

        .btn.cancel:hover {
            background: #f8fafc;
        }

        .danger-text {
            color: #dc2626;
        }

        /* -------------------------------------------------
           RESPONSIVE
        ------------------------------------------------- */

        @media (max-width: 1200px) {

            .stats-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .filter-form {
                grid-template-columns:
                    1fr 1fr;
            }
        }

        @media (max-width: 1100px) {

            .roles-page {
                margin-left: 0;
            }
        }

        @media (max-width: 700px) {

            .topbar {
                height: auto;

                padding: 13px 15px;

                align-items: flex-start;
            }

            .topbar-right .topbar-btn span {
                display: none;
            }

            .topbar-btn {
                width: 42px;
                padding: 0;

                justify-content: center;
            }

            .content {
                padding: 18px 14px;
            }

            .page-heading {
                align-items: flex-start;
                flex-direction: column;
            }

            .page-heading h2 {
                font-size: 23px;
            }

            .stats-grid {
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }

            .stat-card {
                padding: 15px;
            }

            .stat-number {
                font-size: 22px;
            }

            .filter-form {
                grid-template-columns: 1fr;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .field.full {
                grid-column: auto;
            }

            .modal {
                padding: 10px;
            }

            .modal-box {
                border-radius: 18px;
            }
        }

        @media (max-width: 430px) {

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .topbar-title p {
                display: none;
            }
        }

    </style>

</head>

<body>

<?php
/*
 * IMPORTANT:
 * Existing sidebar is included separately.
 */
require_once __DIR__ . '/sidebar.php';
?>

<div class="roles-page">

    <!-- TOPBAR -->
    <header class="topbar">

        <div class="topbar-left">

            <div class="page-icon">
                <i class="fa-solid fa-user-shield"></i>
            </div>

            <div class="topbar-title">

                <h1>Roles Management</h1>

                <p>
                    Manage user roles and access levels
                </p>

            </div>

        </div>

        <div class="topbar-right">

            <button
                type="button"
                class="topbar-btn primary"
                onclick="openAddModal()"
            >
                <i class="fa-solid fa-plus"></i>
                <span>New Role</span>
            </button>

        </div>

    </header>


    <!-- CONTENT -->
    <main class="content">

        <div class="page-heading">

            <div>

                <h2>Roles</h2>

                <p>
                    Create and manage roles assigned to your website users.
                </p>

            </div>

        </div>


        <!-- ALERTS -->

        <?php if ($success): ?>

            <div class="alert success">

                <i class="fa-solid fa-circle-check"></i>

                <span>
                    <?= e($success) ?>
                </span>

            </div>

        <?php endif; ?>


        <?php if ($error): ?>

            <div class="alert error">

                <i class="fa-solid fa-circle-exclamation"></i>

                <span>
                    <?= e($error) ?>
                </span>

            </div>

        <?php endif; ?>


        <!-- STATS -->

        <section class="stats-grid">

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-user-shield"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($totalRoles) ?>
                </div>

                <div class="stat-label">
                    Total Roles
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-check"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($activeRoles) ?>
                </div>

                <div class="stat-label">
                    Active Roles
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-circle-pause"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($inactiveRoles) ?>
                </div>

                <div class="stat-label">
                    Inactive Roles
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-icon">
                        <i class="fa-solid fa-crown"></i>
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($superAdminRoles) ?>
                </div>

                <div class="stat-label">
                    Super Admin Roles
                </div>

            </div>

        </section>


        <!-- FILTERS -->

        <section class="filter-card">

            <form
                method="get"
                class="filter-form"
            >

                <div class="input-wrap">

                    <i class="fa-solid fa-magnifying-glass"></i>

                    <input
                        type="text"
                        name="search"
                        class="form-control"
                        placeholder="Search role, slug or description..."
                        value="<?= e($search) ?>"
                    >

                </div>


                <select
                    name="status"
                    class="form-control"
                >

                    <option value="">
                        All Status
                    </option>

                    <option
                        value="1"
                        <?= $statusFilter === '1' ? 'selected' : '' ?>
                    >
                        Active
                    </option>

                    <option
                        value="0"
                        <?= $statusFilter === '0' ? 'selected' : '' ?>
                    >
                        Inactive
                    </option>

                </select>


                <select
                    name="super_admin"
                    class="form-control"
                >

                    <option value="">
                        All Role Types
                    </option>

                    <option
                        value="1"
                        <?= $superFilter === '1' ? 'selected' : '' ?>
                    >
                        Super Admin
                    </option>

                    <option
                        value="0"
                        <?= $superFilter === '0' ? 'selected' : '' ?>
                    >
                        Normal Role
                    </option>

                </select>


                <button
                    type="submit"
                    class="filter-btn"
                >
                    <i class="fa-solid fa-filter"></i>
                    Filter
                </button>


                <a
                    href="roles.php"
                    class="reset-btn"
                >
                    <i class="fa-solid fa-rotate-left"></i>
                    Reset
                </a>

            </form>

        </section>


        <!-- TABLE -->

        <section class="table-card">

            <div class="table-header">

                <h3>
                    All Roles
                </h3>

                <div class="result-count">

                    <?= number_format(count($roles)) ?>

                    result<?= count($roles) !== 1 ? 's' : '' ?>

                </div>

            </div>


            <?php if (!empty($roles)): ?>

                <div class="table-scroll">

                    <table>

                        <thead>

                            <tr>

                                <th>Role</th>

                                <th>Description</th>

                                <th>Type</th>

                                <th>Users</th>

                                <th>Permissions</th>

                                <th>Status</th>

                                <th>Created</th>

                                <th>Actions</th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($roles as $role): ?>

                            <tr>

                                <!-- ROLE -->

                                <td>

                                    <div class="role-info">

                                        <div class="role-avatar">

                                            <?php
                                            $roleInitial =
                                                strtoupper(
                                                    mb_substr(
                                                        $role['name'],
                                                        0,
                                                        1
                                                    )
                                                );
                                            ?>

                                            <?= e($roleInitial) ?>

                                        </div>

                                        <div>

                                            <div class="role-name">
                                                <?= e($role['name']) ?>
                                            </div>

                                            <div class="role-slug">
                                                <?= e($role['slug']) ?>
                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <!-- DESCRIPTION -->

                                <td>

                                    <?php if (!empty($role['description'])): ?>

                                        <div class="description">

                                            <?= e($role['description']) ?>

                                        </div>

                                    <?php else: ?>

                                        <span class="role-slug">
                                            No description
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- TYPE -->

                                <td>

                                    <?php if ((int)$role['is_super_admin'] === 1): ?>

                                        <span class="badge super">

                                            <i class="fa-solid fa-crown"></i>

                                            Super Admin

                                        </span>

                                    <?php else: ?>

                                        <span class="badge normal">

                                            <i class="fa-solid fa-user"></i>

                                            Normal

                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- USERS -->

                                <td>

                                    <span class="count-pill">

                                        <?= number_format(
                                            (int)$role['users_count']
                                        ) ?>

                                    </span>

                                </td>


                                <!-- PERMISSIONS -->

                                <td>

                                    <span class="count-pill">

                                        <?= number_format(
                                            (int)$role['permissions_count']
                                        ) ?>

                                    </span>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <?php if ((int)$role['status'] === 1): ?>

                                        <span class="badge active">

                                            <i class="fa-solid fa-circle"></i>

                                            Active

                                        </span>

                                    <?php else: ?>

                                        <span class="badge inactive">

                                            <i class="fa-solid fa-circle"></i>

                                            Inactive

                                        </span>

                                    <?php endif; ?>

                                </td>


                                <!-- CREATED -->

                                <td>

                                    <span class="role-slug">

                                        <?= !empty($role['created_at'])
                                            ? e(
                                                date(
                                                    'd M Y',
                                                    strtotime(
                                                        $role['created_at']
                                                    )
                                                )
                                            )
                                            : '-'
                                        ?>

                                    </span>

                                </td>


                                <!-- ACTIONS -->

                                <td>

                                    <div class="actions">

                                        <!-- EDIT -->

                                        <button
                                            type="button"
                                            class="action-btn edit"
                                            title="Edit Role"
                                            onclick='openEditModal(
                                                <?= json_encode(
                                                    [
                                                        'id' => (int)$role['id'],
                                                        'name' => $role['name'],
                                                        'slug' => $role['slug'],
                                                        'description' => $role['description'] ?? '',
                                                        'is_super_admin' => (int)$role['is_super_admin'],
                                                        'status' => (int)$role['status']
                                                    ],
                                                    JSON_HEX_TAG |
                                                    JSON_HEX_APOS |
                                                    JSON_HEX_AMP |
                                                    JSON_HEX_QUOT
                                                ) ?>
                                            )'
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </button>


                                        <!-- STATUS -->

                                        <?php if ((int)$role['is_super_admin'] !== 1): ?>

                                            <form
                                                method="post"
                                                style="display:inline;"
                                                onsubmit="return confirm(
                                                    'Are you sure you want to change this role status?'
                                                );"
                                            >

                                                <?= csrf_field() ?>

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="toggle_status"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="id"
                                                    value="<?= (int)$role['id'] ?>"
                                                >

                                                <button
                                                    type="submit"
                                                    class="action-btn status"
                                                    title="<?= (int)$role['status'] === 1 ? 'Deactivate' : 'Activate' ?>"
                                                >

                                                    <?php if ((int)$role['status'] === 1): ?>

                                                        <i class="fa-solid fa-toggle-on"></i>

                                                    <?php else: ?>

                                                        <i class="fa-solid fa-toggle-off"></i>

                                                    <?php endif; ?>

                                                </button>

                                            </form>

                                        <?php endif; ?>


                                        <!-- DELETE -->

                                        <?php if (
                                            (int)$role['is_super_admin'] !== 1
                                            && (int)$role['users_count'] === 0
                                            && (int)$role['permissions_count'] === 0
                                        ): ?>

                                            <form
                                                method="post"
                                                style="display:inline;"
                                                onsubmit="return confirm(
                                                    'Delete this role permanently?'
                                                );"
                                            >

                                                <?= csrf_field() ?>

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="delete"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="id"
                                                    value="<?= (int)$role['id'] ?>"
                                                >

                                                <button
                                                    type="submit"
                                                    class="action-btn delete"
                                                    title="Delete Role"
                                                >

                                                    <i class="fa-solid fa-trash"></i>

                                                </button>

                                            </form>

                                        <?php endif; ?>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">

                        <i class="fa-solid fa-user-shield"></i>

                    </div>

                    <h3>
                        No roles found
                    </h3>

                    <p>
                        Create your first role to start managing user access.
                    </p>

                </div>

            <?php endif; ?>

        </section>

    </main>

</div>


<!-- =====================================================
     ADD / EDIT MODAL
===================================================== -->

<div
    class="modal"
    id="roleModal"
>

    <div class="modal-box">

        <form
            method="post"
            id="roleForm"
        >

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="save"
            >

            <input
                type="hidden"
                name="id"
                id="role_id"
                value="0"
            >


            <div class="modal-header">

                <div class="modal-title">

                    <div class="modal-title-icon">

                        <i class="fa-solid fa-user-shield"></i>

                    </div>

                    <div>

                        <h3 id="modalTitle">
                            Create New Role
                        </h3>

                        <p>
                            Configure role access and availability.
                        </p>

                    </div>

                </div>

                <button
                    type="button"
                    class="modal-close"
                    onclick="closeModal()"
                >

                    <i class="fa-solid fa-xmark"></i>

                </button>

            </div>


            <div class="modal-body">

                <div class="form-grid">

                    <!-- NAME -->

                    <div class="field">

                        <label>
                            Role Name
                            <span class="required">*</span>
                        </label>

                        <input
                            type="text"
                            name="name"
                            id="role_name"
                            class="form-control"
                            placeholder="e.g. Content Manager"
                            maxlength="100"
                            required
                        >

                    </div>


                    <!-- SLUG -->

                    <div class="field">

                        <label>
                            Role Slug
                            <span class="required">*</span>
                        </label>

                        <input
                            type="text"
                            name="slug"
                            id="role_slug"
                            class="form-control"
                            placeholder="content-manager"
                            maxlength="120"
                            required
                        >

                    </div>


                    <!-- DESCRIPTION -->

                    <div class="field full">

                        <label>
                            Description
                        </label>

                        <textarea
                            name="description"
                            id="role_description"
                            class="form-control"
                            placeholder="Describe what this role is allowed to manage..."
                        ></textarea>

                    </div>


                    <!-- SUPER ADMIN -->

                    <div class="field">

                        <label>
                            Role Type
                        </label>

                        <label class="checkbox-row">

                            <input
                                type="checkbox"
                                name="is_super_admin"
                                id="role_super_admin"
                                value="1"
                            >

                            <span class="checkbox-content">

                                <strong>
                                    Super Admin
                                </strong>

                                <span>
                                    Full system-level access.
                                </span>

                            </span>

                        </label>

                    </div>


                    <!-- STATUS -->

                    <div class="field">

                        <label>
                            Status
                        </label>

                        <label class="checkbox-row">

                            <input
                                type="checkbox"
                                name="status"
                                id="role_status"
                                value="1"
                                checked
                            >

                            <span class="checkbox-content">

                                <strong>
                                    Active Role
                                </strong>

                                <span>
                                    Users can use this role when active.
                                </span>

                            </span>

                        </label>

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn cancel"
                    onclick="closeModal()"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn primary"
                >

                    <i class="fa-solid fa-check"></i>

                    <span id="saveButtonText">
                        Create Role
                    </span>

                </button>

            </div>

        </form>

    </div>

</div>


<script>

    /* ---------------------------------------------------
       Modal
    --------------------------------------------------- */

    const roleModal = document.getElementById('roleModal');

    const roleForm = document.getElementById('roleForm');

    const roleId = document.getElementById('role_id');

    const roleName = document.getElementById('role_name');

    const roleSlug = document.getElementById('role_slug');

    const roleDescription =
        document.getElementById('role_description');

    const roleSuperAdmin =
        document.getElementById('role_super_admin');

    const roleStatus =
        document.getElementById('role_status');

    const modalTitle =
        document.getElementById('modalTitle');

    const saveButtonText =
        document.getElementById('saveButtonText');


    function openAddModal() {

        roleForm.reset();

        roleId.value = '0';

        roleName.value = '';

        roleSlug.value = '';

        roleDescription.value = '';

        roleSuperAdmin.checked = false;

        roleStatus.checked = true;

        modalTitle.textContent = 'Create New Role';

        saveButtonText.textContent = 'Create Role';

        roleModal.classList.add('show');

        setTimeout(function () {
            roleName.focus();
        }, 100);
    }


    function openEditModal(role) {

        roleId.value = role.id;

        roleName.value = role.name || '';

        roleSlug.value = role.slug || '';

        roleDescription.value =
            role.description || '';

        roleSuperAdmin.checked =
            Number(role.is_super_admin) === 1;

        roleStatus.checked =
            Number(role.status) === 1;

        modalTitle.textContent = 'Edit Role';

        saveButtonText.textContent = 'Update Role';

        roleModal.classList.add('show');

        setTimeout(function () {
            roleName.focus();
        }, 100);
    }


    function closeModal() {

        roleModal.classList.remove('show');
    }


    roleModal.addEventListener('click', function (event) {

        if (event.target === roleModal) {
            closeModal();
        }

    });


    document.addEventListener('keydown', function (event) {

        if (event.key === 'Escape') {
            closeModal();
        }

    });


    /* ---------------------------------------------------
       Auto Slug
    --------------------------------------------------- */

    let slugManuallyChanged = false;

    roleSlug.addEventListener('input', function () {
        slugManuallyChanged = true;
    });


    roleName.addEventListener('input', function () {

        if (roleId.value !== '0') {
            return;
        }

        if (slugManuallyChanged) {
            return;
        }

        let value = roleName.value
            .toLowerCase()
            .trim()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');

        roleSlug.value = value;
    });


    roleModal.addEventListener('transitionend', function () {
        if (!roleModal.classList.contains('show')) {
            slugManuallyChanged = false;
        }
    });

</script>

</body>
</html>