<?php
/**
 * Pure Chemical Admin
 * role_permissions.php
 *
 * Existing tables used:
 * - roles
 * - permissions
 * - role_permissions
 *
 * No new table required.
 */

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): string
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token(): string
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(
                random_bytes(32)
            );
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field(): string
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('verify_csrf')) {
    function verify_csrf(): void
    {
        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($token) ||
            empty($_SESSION['csrf_token']) ||
            !hash_equals(
                $_SESSION['csrf_token'],
                $token
            )
        ) {
            http_response_code(419);
            exit('Invalid CSRF token.');
        }
    }
}

/* =========================================================
   PAGE
========================================================= */

$self = basename($_SERVER['PHP_SELF']);

$success = $_SESSION['role_permission_success'] ?? '';
$error   = $_SESSION['role_permission_error'] ?? '';

unset(
    $_SESSION['role_permission_success'],
    $_SESSION['role_permission_error']
);

/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    verify_csrf();

    $action = $_POST['action'] ?? '';

    try {

        /* =================================================
           ASSIGN PERMISSIONS TO ROLE
        ================================================= */

        if ($action === 'save') {

            $roleId = (int)($_POST['role_id'] ?? 0);

            $permissionIds =
                $_POST['permission_ids'] ?? [];

            if ($roleId <= 0) {
                throw new Exception(
                    'Please select a valid role.'
                );
            }

            if (!is_array($permissionIds)) {
                $permissionIds = [];
            }

            $permissionIds = array_values(
                array_unique(
                    array_filter(
                        array_map(
                            'intval',
                            $permissionIds
                        ),
                        function ($id) {
                            return $id > 0;
                        }
                    )
                )
            );

            /* Check role */

            $stmt = $pdo->prepare("
                SELECT
                    id,
                    name,
                    slug,
                    is_super_admin,
                    status
                FROM roles
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':id' => $roleId
            ]);

            $role = $stmt->fetch();

            if (!$role) {
                throw new Exception(
                    'Selected role does not exist.'
                );
            }

            /* Check permissions */

            if (!empty($permissionIds)) {

                $placeholders = implode(
                    ',',
                    array_fill(
                        0,
                        count($permissionIds),
                        '?'
                    )
                );

                $stmt = $pdo->prepare("
                    SELECT COUNT(*)
                    FROM permissions
                    WHERE id IN ($placeholders)
                ");

                $stmt->execute($permissionIds);

                $validCount = (int)$stmt->fetchColumn();

                if (
                    $validCount !==
                    count($permissionIds)
                ) {
                    throw new Exception(
                        'One or more selected permissions are invalid.'
                    );
                }
            }

            /* =================================================
               TRANSACTION
            ================================================= */

            $pdo->beginTransaction();

            /*
             * Replace current role permissions
             * with selected permissions.
             */

            $stmt = $pdo->prepare("
                DELETE FROM role_permissions
                WHERE role_id = :role_id
            ");

            $stmt->execute([
                ':role_id' => $roleId
            ]);

            if (!empty($permissionIds)) {

                $stmt = $pdo->prepare("
                    INSERT INTO role_permissions
                    (
                        role_id,
                        permission_id
                    )
                    VALUES
                    (
                        :role_id,
                        :permission_id
                    )
                ");

                foreach ($permissionIds as $permissionId) {

                    $stmt->execute([
                        ':role_id'       => $roleId,
                        ':permission_id' => $permissionId
                    ]);
                }
            }

            $pdo->commit();

            $_SESSION['role_permission_success'] =
                'Permissions updated successfully for "' .
                $role['name'] .
                '".';

            header(
                'Location: ' .
                $self .
                '?role_id=' .
                $roleId
            );

            exit;
        }

        /* =================================================
           REMOVE SINGLE PERMISSION
        ================================================= */

        if ($action === 'remove') {

            $roleId = (int)($_POST['role_id'] ?? 0);

            $permissionId =
                (int)($_POST['permission_id'] ?? 0);

            if (
                $roleId <= 0 ||
                $permissionId <= 0
            ) {
                throw new Exception(
                    'Invalid role or permission.'
                );
            }

            $stmt = $pdo->prepare("
                DELETE FROM role_permissions
                WHERE role_id = :role_id
                  AND permission_id = :permission_id
                LIMIT 1
            ");

            $stmt->execute([
                ':role_id'       => $roleId,
                ':permission_id' => $permissionId
            ]);

            $_SESSION['role_permission_success'] =
                'Permission removed from the role.';

            header(
                'Location: ' .
                $self .
                '?role_id=' .
                $roleId
            );

            exit;
        }

    } catch (Throwable $ex) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $_SESSION['role_permission_error'] =
            $ex->getMessage();

        header(
            'Location: ' .
            $self .
            (
                !empty($_POST['role_id'])
                    ? '?role_id=' .
                      (int)$_POST['role_id']
                    : ''
            )
        );

        exit;
    }
}

/* =========================================================
   SELECTED ROLE
========================================================= */

$selectedRoleId =
    (int)($_GET['role_id'] ?? 0);

/* =========================================================
   SEARCH
========================================================= */

$search =
    trim($_GET['search'] ?? '');

$moduleFilter =
    trim($_GET['module'] ?? '');

$actionFilter =
    trim($_GET['permission_action'] ?? '');

/* =========================================================
   ROLES
========================================================= */

$stmt = $pdo->query("
    SELECT
        r.id,
        r.name,
        r.slug,
        r.description,
        r.is_super_admin,
        r.status,

        COUNT(
            DISTINCT rp.permission_id
        ) AS permissions_count,

        COUNT(
            DISTINCT u.id
        ) AS users_count

    FROM roles r

    LEFT JOIN role_permissions rp
        ON rp.role_id = r.id

    LEFT JOIN users u
        ON u.role_id = r.id

    GROUP BY
        r.id,
        r.name,
        r.slug,
        r.description,
        r.is_super_admin,
        r.status

    ORDER BY
        r.is_super_admin DESC,
        r.status DESC,
        r.name ASC
");

$roles = $stmt->fetchAll();

/* =========================================================
   SELECTED ROLE DETAILS
========================================================= */

$selectedRole = null;

if ($selectedRoleId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            name,
            slug,
            description,
            is_super_admin,
            status
        FROM roles
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $selectedRoleId
    ]);

    $selectedRole = $stmt->fetch();

    if (!$selectedRole) {
        $selectedRoleId = 0;
    }
}

/* =========================================================
   AUTO SELECT FIRST ROLE
========================================================= */

if (
    $selectedRoleId <= 0 &&
    !empty($roles)
) {
    $selectedRoleId =
        (int)$roles[0]['id'];

    $selectedRole =
        $roles[0];
}

/* =========================================================
   ALL MODULES
========================================================= */

$stmt = $pdo->query("
    SELECT DISTINCT module
    FROM permissions
    WHERE module IS NOT NULL
      AND module <> ''
    ORDER BY module ASC
");

$modules = $stmt->fetchAll();

/* =========================================================
   ALL ACTIONS
========================================================= */

$stmt = $pdo->query("
    SELECT DISTINCT action
    FROM permissions
    WHERE action IS NOT NULL
      AND action <> ''
    ORDER BY action ASC
");

$actions = $stmt->fetchAll();

/* =========================================================
   SELECTED ROLE PERMISSION IDS
========================================================= */

$assignedPermissionIds = [];

if ($selectedRoleId > 0) {

    $stmt = $pdo->prepare("
        SELECT permission_id
        FROM role_permissions
        WHERE role_id = :role_id
    ");

    $stmt->execute([
        ':role_id' => $selectedRoleId
    ]);

    $assignedPermissionIds =
        array_map(
            'intval',
            $stmt->fetchAll(
                PDO::FETCH_COLUMN
            )
        );
}

/* =========================================================
   PERMISSIONS
========================================================= */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            p.name LIKE :search
            OR p.slug LIKE :search
            OR p.module LIKE :search
            OR p.action LIKE :search
            OR p.description LIKE :search
        )
    ";

    $params[':search'] =
        '%' . $search . '%';
}

if ($moduleFilter !== '') {

    $where[] =
        "p.module = :module";

    $params[':module'] =
        $moduleFilter;
}

if ($actionFilter !== '') {

    $where[] =
        "p.action = :permission_action";

    $params[':permission_action'] =
        $actionFilter;
}

$whereSql = '';

if (!empty($where)) {

    $whereSql =
        'WHERE ' .
        implode(
            ' AND ',
            $where
        );
}

$sql = "
    SELECT
        p.id,
        p.name,
        p.slug,
        p.module,
        p.action,
        p.description,
        p.created_at,

        CASE
            WHEN rp.role_id IS NULL
            THEN 0
            ELSE 1
        END AS is_assigned

    FROM permissions p

    LEFT JOIN role_permissions rp
        ON rp.permission_id = p.id
        AND rp.role_id = :role_id

    {$whereSql}

    ORDER BY
        is_assigned DESC,
        CASE
            WHEN p.module IS NULL
              OR p.module = ''
            THEN 1
            ELSE 0
        END ASC,
        p.module ASC,
        p.name ASC,
        p.id DESC
";

$params[':role_id'] =
    $selectedRoleId;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$permissions =
    $stmt->fetchAll();

/* =========================================================
   STATS
========================================================= */

$totalRoles =
    count($roles);

$totalPermissions =
    count($permissions);

$assignedCount =
    count($assignedPermissionIds);

$unassignedCount =
    max(
        0,
        $totalPermissions -
        $assignedCount
    );

$roleUsersCount = 0;

if ($selectedRoleId > 0) {

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM users
        WHERE role_id = :role_id
    ");

    $stmt->execute([
        ':role_id' =>
            $selectedRoleId
    ]);

    $roleUsersCount =
        (int)$stmt->fetchColumn();
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Role Permissions | Pure Chemical Admin
    </title>

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <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: #0f766e;
            --primary-dark: #115e59;
            --primary-soft: #ecfdf5;

            --text: #172033;
            --muted: #64748b;

            --border: #e5e7eb;

            --bg: #f6f8fb;
            --white: #ffffff;

            --success: #15803d;
            --success-bg: #f0fdf4;

            --danger: #dc2626;
            --danger-bg: #fef2f2;

            --warning: #d97706;
            --warning-bg: #fffbeb;

            --shadow:
                0 12px 35px rgba(
                    15,
                    23,
                    42,
                    .07
                );

            --radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        body {

            margin: 0;

            background:
                radial-gradient(
                    circle at top right,
                    rgba(
                        15,
                        118,
                        110,
                        .07
                    ),
                    transparent 28%
                ),
                var(--bg);

            color: var(--text);

            font-family:
                Inter,
                system-ui,
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                sans-serif;
        }

        button,
        input,
        select {
            font: inherit;
        }

        a {
            text-decoration: none;
            color: inherit;
        }

        /* =================================================
           LAYOUT
        ================================================= */

        .page-shell {

            margin-left: 280px;

            min-height: 100vh;
        }

        .page-container {

            max-width: 1800px;

            padding:
                24px
                28px
                55px;
        }

        /* =================================================
           TOPBAR
        ================================================= */

        .topbar {

            position: sticky;

            top: 0;

            z-index: 90;

            min-height: 74px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 20px;

            padding:
                14px
                28px;

            background:
                rgba(
                    255,
                    255,
                    255,
                    .88
                );

            border-bottom:
                1px solid
                rgba(
                    226,
                    232,
                    240,
                    .9
                );

            backdrop-filter:
                blur(18px);
        }

        .topbar-left {

            display: flex;

            align-items: center;

            gap: 14px;
        }

        .mobile-menu {

            width: 42px;
            height: 42px;

            display: none;

            align-items: center;
            justify-content: center;

            border:
                1px solid
                var(--border);

            border-radius: 12px;

            background: #fff;

            cursor: pointer;
        }

        .topbar-title {

            font-size: 19px;

            font-weight: 800;

            letter-spacing: -.03em;
        }

        .topbar-subtitle {

            margin-top: 2px;

            color: var(--muted);

            font-size: 12px;
        }

        .admin-chip {

            display: flex;

            align-items: center;

            gap: 10px;

            padding:
                7px
                12px
                7px
                7px;

            background: #fff;

            border:
                1px solid
                var(--border);

            border-radius: 999px;
        }

        .admin-avatar {

            width: 34px;
            height: 34px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 50%;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #14b8a6
                );

            font-size: 13px;

            font-weight: 800;
        }

        .admin-chip-text strong {

            display: block;

            font-size: 12px;
        }

        .admin-chip-text span {

            color: var(--muted);

            font-size: 10px;
        }

        /* =================================================
           BREADCRUMB
        ================================================= */

        .breadcrumb {

            display: flex;

            align-items: center;

            gap: 8px;

            margin-bottom: 9px;

            color: var(--muted);

            font-size: 12px;
        }

        .breadcrumb .active {

            color: var(--text);

            font-weight: 700;
        }

        /* =================================================
           HEADER
        ================================================= */

        .page-header {

            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 20px;

            margin-bottom: 22px;
        }

        .page-header h1 {

            margin: 0;

            font-size:
                clamp(
                    25px,
                    3vw,
                    34px
                );

            line-height: 1.1;

            letter-spacing: -.045em;

            font-weight: 800;
        }

        .page-header p {

            max-width: 700px;

            margin:
                9px
                0
                0;

            color: var(--muted);

            font-size: 13px;

            line-height: 1.7;
        }

        /* =================================================
           BUTTONS
        ================================================= */

        .btn {

            min-height: 42px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            padding:
                0
                15px;

            border: 0;

            border-radius: 12px;

            cursor: pointer;

            font-size: 12px;

            font-weight: 700;

            transition: .2s ease;
        }

        .btn:hover {

            transform:
                translateY(-1px);
        }

        .btn-primary {

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #0d9488
                );

            box-shadow:
                0 10px 22px
                rgba(
                    15,
                    118,
                    110,
                    .18
                );
        }

        .btn-light {

            color: var(--text);

            background: #fff;

            border:
                1px solid
                var(--border);
        }

        .btn-danger {

            color: #fff;

            background:
                var(--danger);
        }

        /* =================================================
           ALERT
        ================================================= */

        .alert {

            display: flex;

            align-items: flex-start;

            gap: 10px;

            padding:
                14px
                16px;

            margin-bottom: 18px;

            border-radius: 14px;

            font-size: 13px;
        }

        .alert-success {

            color: #166534;

            background:
                var(--success-bg);

            border:
                1px solid
                #bbf7d0;
        }

        .alert-danger {

            color: #991b1b;

            background:
                var(--danger-bg);

            border:
                1px solid
                #fecaca;
        }

        /* =================================================
           ROLE SELECTOR
        ================================================= */

        .role-panel {

            display: grid;

            grid-template-columns:
                minmax(260px, 330px)
                minmax(0, 1fr);

            gap: 18px;

            margin-bottom: 18px;
        }

        .role-list-card {

            overflow: hidden;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            background: #fff;

            box-shadow:
                var(--shadow);
        }

        .role-list-head {

            padding:
                18px;

            border-bottom:
                1px solid
                var(--border);
        }

        .role-list-head h2 {

            margin: 0;

            font-size: 14px;

            font-weight: 800;
        }

        .role-list-head span {

            display: block;

            margin-top: 5px;

            color: var(--muted);

            font-size: 10px;
        }

        .roles {

            max-height: 540px;

            overflow-y: auto;
        }

        .role-item {

            display: flex;

            align-items: center;

            gap: 11px;

            width: 100%;

            padding:
                13px
                16px;

            border: 0;

            border-bottom:
                1px solid
                #eef2f7;

            background: #fff;

            text-align: left;

            cursor: pointer;

            transition: .18s ease;
        }

        .role-item:hover {

            background:
                #f8fffd;
        }

        .role-item.active {

            background:
                var(--primary-soft);

            box-shadow:
                inset 3px 0 0
                var(--primary);
        }

        .role-icon {

            width: 38px;
            height: 38px;

            flex: 0 0 38px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 11px;

            color: var(--primary);

            background:
                var(--primary-soft);
        }

        .role-info {

            min-width: 0;

            flex: 1;
        }

        .role-info strong {

            display: block;

            overflow: hidden;

            color: var(--text);

            font-size: 12px;

            white-space: nowrap;

            text-overflow: ellipsis;
        }

        .role-info small {

            display: block;

            margin-top: 4px;

            color: var(--muted);

            font-size: 10px;
        }

        .role-count {

            color: var(--primary);

            font-size: 10px;

            font-weight: 800;
        }

        /* =================================================
           SELECTED ROLE SUMMARY
        ================================================= */

        .summary-card {

            position: relative;

            overflow: hidden;

            padding: 22px;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            background:
                linear-gradient(
                    135deg,
                    #ffffff,
                    #f8fffd
                );

            box-shadow:
                var(--shadow);
        }

        .summary-card::after {

            content: "";

            position: absolute;

            width: 180px;
            height: 180px;

            right: -90px;
            top: -90px;

            border-radius: 50%;

            background:
                rgba(
                    15,
                    118,
                    110,
                    .07
                );
        }

        .summary-top {

            position: relative;

            z-index: 1;

            display: flex;

            align-items: flex-start;

            justify-content: space-between;

            gap: 15px;

            margin-bottom: 20px;
        }

        .summary-role {

            display: flex;

            align-items: center;

            gap: 13px;
        }

        .summary-role-icon {

            width: 50px;
            height: 50px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 15px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #14b8a6
                );

            box-shadow:
                0 10px 20px
                rgba(
                    15,
                    118,
                    110,
                    .18
                );
        }

        .summary-role h2 {

            margin: 0;

            font-size: 18px;

            font-weight: 800;
        }

        .summary-role p {

            margin: 5px 0 0;

            color: var(--muted);

            font-size: 11px;
        }

        .super-badge {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding:
                7px
                10px;

            border-radius: 999px;

            color: #92400e;

            background:
                #fef3c7;

            font-size: 10px;

            font-weight: 800;
        }

        .summary-stats {

            position: relative;

            z-index: 1;

            display: grid;

            grid-template-columns:
                repeat(3, 1fr);

            gap: 10px;
        }

        .summary-stat {

            padding:
                13px;

            border:
                1px solid
                #e2e8f0;

            border-radius: 13px;

            background:
                rgba(
                    255,
                    255,
                    255,
                    .72
                );
        }

        .summary-stat strong {

            display: block;

            font-size: 21px;

            font-weight: 800;
        }

        .summary-stat span {

            display: block;

            margin-top: 4px;

            color: var(--muted);

            font-size: 10px;
        }

        /* =================================================
           FILTER
        ================================================= */

        .filter-card {

            padding:
                16px;

            margin-bottom:
                18px;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            background: #fff;

            box-shadow:
                var(--shadow);
        }

        .filter-form {

            display: grid;

            grid-template-columns:
                minmax(230px, 1.7fr)
                minmax(150px, 1fr)
                minmax(150px, 1fr)
                auto
                auto;

            gap: 10px;

            align-items: end;
        }

        .field label {

            display: block;

            margin-bottom: 7px;

            color: #475569;

            font-size: 11px;

            font-weight: 700;
        }

        .input,
        .select {

            width: 100%;

            height: 42px;

            padding:
                0
                12px;

            border:
                1px solid
                #dbe1e8;

            border-radius: 11px;

            outline: none;

            background: #fff;

            color: var(--text);

            transition: .2s ease;
        }

        .input:focus,
        .select:focus {

            border-color:
                rgba(
                    15,
                    118,
                    110,
                    .55
                );

            box-shadow:
                0 0 0 4px
                rgba(
                    15,
                    118,
                    110,
                    .08
                );
        }

        /* =================================================
           PERMISSION CARD
        ================================================= */

        .permission-card {

            overflow: hidden;

            border:
                1px solid
                var(--border);

            border-radius:
                var(--radius);

            background: #fff;

            box-shadow:
                var(--shadow);
        }

        .permission-head {

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            padding:
                18px 20px;

            border-bottom:
                1px solid
                var(--border);
        }

        .permission-head h2 {

            margin: 0;

            font-size: 15px;

            font-weight: 800;
        }

        .permission-head span {

            display: block;

            margin-top: 4px;

            color: var(--muted);

            font-size: 10px;
        }

        .permission-body {

            padding: 0;
        }

        .permission-grid {

            display: grid;

            grid-template-columns:
                repeat(
                    auto-fill,
                    minmax(
                        290px,
                        1fr
                    )
                );

            gap: 12px;

            padding: 18px;
        }

        .permission-item {

            position: relative;

            display: flex;

            align-items: flex-start;

            gap: 11px;

            min-height: 112px;

            padding: 14px;

            border:
                1px solid
                #e2e8f0;

            border-radius: 14px;

            background: #fff;

            cursor: pointer;

            transition:
                border-color .2s ease,
                background .2s ease,
                transform .2s ease;
        }

        .permission-item:hover {

            border-color:
                #99f6e4;

            background:
                #fbfffe;

            transform:
                translateY(-1px);
        }

        .permission-item.assigned {

            border-color:
                #99f6e4;

            background:
                #f0fdfa;
        }

        .permission-checkbox {

            position: relative;

            width: 20px;
            height: 20px;

            flex: 0 0 20px;

            margin-top: 1px;
        }

        .permission-checkbox input {

            position: absolute;

            opacity: 0;

            width: 0;
            height: 0;
        }

        .checkmark {

            width: 20px;
            height: 20px;

            display: flex;

            align-items: center;
            justify-content: center;

            border:
                1.5px solid
                #cbd5e1;

            border-radius: 6px;

            color: #fff;

            background: #fff;

            transition: .2s ease;
        }

        .permission-checkbox input:checked
        + .checkmark {

            border-color:
                var(--primary);

            background:
                var(--primary);
        }

        .checkmark i {

            opacity: 0;

            font-size: 10px;
        }

        .permission-checkbox input:checked
        + .checkmark i {

            opacity: 1;
        }

        .permission-info {

            min-width: 0;

            flex: 1;
        }

        .permission-info strong {

            display: block;

            color: var(--text);

            font-size: 12px;

            font-weight: 800;
        }

        .permission-info small {

            display: block;

            margin-top: 5px;

            overflow: hidden;

            color: var(--muted);

            font-size: 10px;

            line-height: 1.5;

            display: -webkit-box;

            -webkit-line-clamp: 2;

            -webkit-box-orient: vertical;
        }

        .permission-meta {

            display: flex;

            flex-wrap: wrap;

            gap: 5px;

            margin-top: 9px;
        }

        .module-badge,
        .action-badge {

            display: inline-flex;

            align-items: center;

            padding:
                5px
                7px;

            border-radius: 999px;

            font-size: 9px;

            font-weight: 700;
        }

        .module-badge {

            color: #115e59;

            background:
                #ccfbf1;
        }

        .action-badge {

            color: #92400e;

            background:
                #fef3c7;
        }

        .assigned-mark {

            position: absolute;

            top: 10px;
            right: 10px;

            color:
                var(--primary);

            font-size: 11px;
        }

        /* =================================================
           SAVE BAR
        ================================================= */

        .save-bar {

            position: sticky;

            bottom: 15px;

            z-index: 20;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            margin-top: 18px;

            padding:
                13px 16px;

            border:
                1px solid
                rgba(
                    15,
                    118,
                    110,
                    .15
                );

            border-radius: 16px;

            background:
                rgba(
                    255,
                    255,
                    255,
                    .94
                );

            box-shadow:
                0 15px 40px
                rgba(
                    15,
                    23,
                    42,
                    .12
                );

            backdrop-filter:
                blur(15px);
        }

        .selected-info {

            display: flex;

            align-items: center;

            gap: 10px;

            color: var(--muted);

            font-size: 11px;
        }

        .selected-info strong {

            color: var(--text);

            font-size: 13px;
        }

        .save-actions {

            display: flex;

            gap: 8px;
        }

        /* =================================================
           EMPTY
        ================================================= */

        .empty-state {

            padding:
                65px
                20px;

            text-align: center;
        }

        .empty-icon {

            width: 62px;
            height: 62px;

            margin:
                0 auto
                15px;

            display: flex;

            align-items: center;
            justify-content: center;

            border-radius: 18px;

            color:
                var(--primary);

            background:
                var(--primary-soft);

            font-size: 24px;
        }

        .empty-state h3 {

            margin:
                0
                0
                7px;

            font-size: 16px;
        }

        .empty-state p {

            max-width: 450px;

            margin: 0 auto;

            color: var(--muted);

            font-size: 12px;

            line-height: 1.7;
        }

        /* =================================================
           RESPONSIVE
        ================================================= */

        @media (max-width: 1250px) {

            .role-panel {

                grid-template-columns:
                    280px
                    minmax(0, 1fr);
            }

            .filter-form {

                grid-template-columns:
                    repeat(
                        2,
                        minmax(0, 1fr)
                    );
            }

            .filter-form
            .search-field {

                grid-column:
                    1 / -1;
            }
        }

        @media (max-width: 1100px) {

            .page-shell {

                margin-left: 0;
            }

            .mobile-menu {

                display: flex;
            }

            .role-panel {

                grid-template-columns: 1fr;
            }

            .roles {

                max-height: 260px;
            }
        }

        @media (max-width: 700px) {

            .topbar {

                padding:
                    12px
                    15px;
            }

            .page-container {

                padding:
                    18px
                    15px
                    45px;
            }

            .topbar-subtitle,
            .admin-chip-text {

                display: none;
            }

            .page-header {

                align-items: stretch;

                flex-direction: column;
            }

            .page-header .btn {

                width: 100%;
            }

            .filter-form {

                grid-template-columns:
                    1fr;
            }

            .filter-form
            .search-field {

                grid-column: auto;
            }

            .summary-top {

                flex-direction: column;
            }

            .summary-stats {

                grid-template-columns:
                    1fr;
            }

            .permission-grid {

                grid-template-columns:
                    1fr;

                padding:
                    13px;
            }

            .save-bar {

                align-items: stretch;

                flex-direction: column;
            }

            .save-actions {

                width: 100%;
            }

            .save-actions .btn {

                flex: 1;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing Admin Sidebar
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="page-shell">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <button
                type="button"
                class="mobile-menu"
                onclick="toggleSidebar()"
                aria-label="Toggle sidebar"
            >
                <i class="fa-solid fa-bars"></i>
            </button>

            <div>

                <div class="topbar-title">
                    Role Permissions
                </div>

                <div class="topbar-subtitle">
                    Manage role based access control
                </div>

            </div>

        </div>


        <?php

        $adminName =
            $_SESSION['ADMIN_NAME']
            ?? $_SESSION['admin_name']
            ?? 'Administrator';

        $adminInitial =
            strtoupper(
                mb_substr(
                    trim($adminName),
                    0,
                    1
                )
            );

        ?>

        <div class="admin-chip">

            <div class="admin-avatar">
                <?= e($adminInitial ?: 'A') ?>
            </div>

            <div class="admin-chip-text">

                <strong>
                    <?= e($adminName) ?>
                </strong>

                <span>
                    Administrator
                </span>

            </div>

        </div>

    </header>


    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="page-container">

        <div class="breadcrumb">

            <span>
                Admin
            </span>

            <i class="fa-solid fa-chevron-right"></i>

            <span class="active">
                Role Permissions
            </span>

        </div>


        <section class="page-header">

            <div>

                <h1>
                    Role Permission Control
                </h1>

                <p>
                    Select a role and control exactly which
                    permissions are available to that role.
                </p>

            </div>

        </section>


        <!-- =================================================
             ALERTS
        ================================================== -->

        <?php if ($success): ?>

            <div class="alert alert-success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?= e($success) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if ($error): ?>

            <div class="alert alert-danger">

                <i class="fa-solid fa-circle-exclamation"></i>

                <div>
                    <?= e($error) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if (empty($roles)): ?>

            <section class="permission-card">

                <div class="empty-state">

                    <div class="empty-icon">

                        <i class="fa-solid fa-user-shield"></i>

                    </div>

                    <h3>
                        No roles available
                    </h3>

                    <p>
                        Create a role first before assigning
                        permissions.
                    </p>

                </div>

            </section>

        <?php else: ?>


            <!-- =================================================
                 ROLE + SUMMARY
            ================================================== -->

            <section class="role-panel">


                <!-- ROLE LIST -->

                <div class="role-list-card">

                    <div class="role-list-head">

                        <h2>
                            Select Role
                        </h2>

                        <span>
                            <?= number_format($totalRoles) ?>
                            role<?= $totalRoles === 1 ? '' : 's' ?>
                            available
                        </span>

                    </div>


                    <div class="roles">

                        <?php foreach ($roles as $role): ?>

                            <a
                                href="<?= e($self) ?>?role_id=<?= (int)$role['id'] ?>"
                                class="role-item <?= (int)$role['id'] === $selectedRoleId ? 'active' : '' ?>"
                            >

                                <div class="role-icon">

                                    <i class="fa-solid
                                        <?= (int)$role['is_super_admin']
                                            ? 'fa-crown'
                                            : 'fa-user-shield'
                                        ?>
                                    "></i>

                                </div>


                                <div class="role-info">

                                    <strong>
                                        <?= e($role['name']) ?>
                                    </strong>

                                    <small>

                                        <?= number_format(
                                            (int)$role['permissions_count']
                                        ) ?>

                                        permission<?= (int)$role['permissions_count'] === 1 ? '' : 's' ?>

                                        ·

                                        <?= number_format(
                                            (int)$role['users_count']
                                        ) ?>

                                        user<?= (int)$role['users_count'] === 1 ? '' : 's' ?>

                                    </small>

                                </div>


                                <div class="role-count">

                                    <i class="fa-solid fa-chevron-right"></i>

                                </div>

                            </a>

                        <?php endforeach; ?>

                    </div>

                </div>


                <!-- ROLE SUMMARY -->

                <?php if ($selectedRole): ?>

                    <div class="summary-card">

                        <div class="summary-top">

                            <div class="summary-role">

                                <div class="summary-role-icon">

                                    <i class="fa-solid
                                        <?= (int)$selectedRole['is_super_admin']
                                            ? 'fa-crown'
                                            : 'fa-user-shield'
                                        ?>
                                    "></i>

                                </div>

                                <div>

                                    <h2>
                                        <?= e($selectedRole['name']) ?>
                                    </h2>

                                    <p>
                                        <?= e($selectedRole['slug']) ?>
                                    </p>

                                </div>

                            </div>


                            <?php if (
                                (int)$selectedRole['is_super_admin'] === 1
                            ): ?>

                                <span class="super-badge">

                                    <i class="fa-solid fa-crown"></i>

                                    Super Admin

                                </span>

                            <?php endif; ?>

                        </div>


                        <div class="summary-stats">

                            <div class="summary-stat">

                                <strong>
                                    <?= number_format($assignedCount) ?>
                                </strong>

                                <span>
                                    Assigned Permissions
                                </span>

                            </div>


                            <div class="summary-stat">

                                <strong>
                                    <?= number_format($unassignedCount) ?>
                                </strong>

                                <span>
                                    Available Permissions
                                </span>

                            </div>


                            <div class="summary-stat">

                                <strong>
                                    <?= number_format($roleUsersCount) ?>
                                </strong>

                                <span>
                                    Users With This Role
                                </span>

                            </div>

                        </div>

                    </div>

                <?php endif; ?>

            </section>


            <!-- =================================================
                 FILTERS
            ================================================== -->

            <section class="filter-card">

                <form
                    method="GET"
                    class="filter-form"
                >

                    <input
                        type="hidden"
                        name="role_id"
                        value="<?= $selectedRoleId ?>"
                    >


                    <div
                        class="field search-field"
                    >

                        <label>
                            Search Permission
                        </label>

                        <input
                            type="search"
                            name="search"
                            class="input"
                            value="<?= e($search) ?>"
                            placeholder="Search name, slug, module, action..."
                        >

                    </div>


                    <div class="field">

                        <label>
                            Module
                        </label>

                        <select
                            name="module"
                            class="select"
                        >

                            <option value="">
                                All Modules
                            </option>

                            <?php foreach ($modules as $item): ?>

                                <option
                                    value="<?= e($item['module']) ?>"
                                    <?= $moduleFilter === $item['module']
                                        ? 'selected'
                                        : ''
                                    ?>
                                >
                                    <?= e($item['module']) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <div class="field">

                        <label>
                            Action
                        </label>

                        <select
                            name="permission_action"
                            class="select"
                        >

                            <option value="">
                                All Actions
                            </option>

                            <?php foreach ($actions as $item): ?>

                                <option
                                    value="<?= e($item['action']) ?>"
                                    <?= $actionFilter === $item['action']
                                        ? 'selected'
                                        : ''
                                    ?>
                                >
                                    <?= e($item['action']) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <button
                        type="submit"
                        class="btn btn-primary"
                    >

                        <i class="fa-solid fa-filter"></i>

                        Filter

                    </button>


                    <a
                        href="<?= e($self) ?>?role_id=<?= $selectedRoleId ?>"
                        class="btn btn-light"
                    >

                        <i class="fa-solid fa-rotate-left"></i>

                        Reset

                    </a>

                </form>

            </section>


            <!-- =================================================
                 PERMISSION FORM
            ================================================== -->

            <form
                method="POST"
                action="<?= e($self) ?>"
                id="permissionForm"
            >

                <?= csrf_field() ?>

                <input
                    type="hidden"
                    name="action"
                    value="save"
                >

                <input
                    type="hidden"
                    name="role_id"
                    value="<?= $selectedRoleId ?>"
                >


                <section class="permission-card">

                    <div class="permission-head">

                        <div>

                            <h2>
                                Available Permissions
                            </h2>

                            <span>
                                Tick permissions that should
                                belong to this role.
                            </span>

                        </div>


                        <div>

                            <button
                                type="button"
                                class="btn btn-light"
                                onclick="toggleAllPermissions()"
                            >

                                <i class="fa-solid fa-check-double"></i>

                                Select All

                            </button>

                        </div>

                    </div>


                    <div class="permission-body">

                        <?php if (!empty($permissions)): ?>

                            <div class="permission-grid">

                                <?php foreach ($permissions as $permission): ?>

                                    <?php
                                    $permissionId =
                                        (int)$permission['id'];

                                    $isAssigned =
                                        in_array(
                                            $permissionId,
                                            $assignedPermissionIds,
                                            true
                                        );
                                    ?>

                                    <label
                                        class="permission-item <?= $isAssigned ? 'assigned' : '' ?>"
                                        data-permission-card
                                    >

                                        <div class="permission-checkbox">

                                            <input
                                                type="checkbox"
                                                name="permission_ids[]"
                                                value="<?= $permissionId ?>"
                                                <?= $isAssigned ? 'checked' : '' ?>
                                                onchange="updatePermissionCard(this)"
                                            >

                                            <span class="checkmark">

                                                <i class="fa-solid fa-check"></i>

                                            </span>

                                        </div>


                                        <div class="permission-info">

                                            <strong>
                                                <?= e($permission['name']) ?>
                                            </strong>


                                            <small>

                                                <?php

                                                $description =
                                                    trim(
                                                        (string)(
                                                            $permission['description']
                                                            ?? ''
                                                        )
                                                    );

                                                echo e(
                                                    $description !== ''
                                                        ? $description
                                                        : $permission['slug']
                                                );

                                                ?>

                                            </small>


                                            <div class="permission-meta">

                                                <?php if (
                                                    !empty(
                                                        $permission['module']
                                                    )
                                                ): ?>

                                                    <span class="module-badge">

                                                        <i
                                                            class="fa-solid fa-layer-group"
                                                            style="margin-right:4px;"
                                                        ></i>

                                                        <?= e(
                                                            $permission['module']
                                                        ) ?>

                                                    </span>

                                                <?php endif; ?>


                                                <?php if (
                                                    !empty(
                                                        $permission['action']
                                                    )
                                                ): ?>

                                                    <span class="action-badge">

                                                        <?= e(
                                                            $permission['action']
                                                        ) ?>

                                                    </span>

                                                <?php endif; ?>

                                            </div>

                                        </div>


                                        <?php if ($isAssigned): ?>

                                            <span
                                                class="assigned-mark"
                                                title="Currently assigned"
                                            >

                                                <i class="fa-solid fa-circle-check"></i>

                                            </span>

                                        <?php endif; ?>

                                    </label>

                                <?php endforeach; ?>

                            </div>

                        <?php else: ?>

                            <div class="empty-state">

                                <div class="empty-icon">

                                    <i class="fa-solid fa-key"></i>

                                </div>

                                <h3>
                                    No permissions found
                                </h3>

                                <p>
                                    No permissions match your
                                    current search or filters.
                                </p>

                            </div>

                        <?php endif; ?>

                    </div>

                </section>


                <!-- =================================================
                     SAVE BAR
                ================================================== -->

                <div class="save-bar">

                    <div class="selected-info">

                        <i class="fa-solid fa-shield-halved"></i>

                        <span>

                            Selected:

                            <strong
                                id="selectedPermissionCount"
                            >
                                <?= number_format($assignedCount) ?>
                            </strong>

                            permission<?= $assignedCount === 1 ? '' : 's' ?>

                        </span>

                    </div>


                    <div class="save-actions">

                        <button
                            type="button"
                            class="btn btn-light"
                            onclick="clearAllPermissions()"
                        >

                            <i class="fa-solid fa-eraser"></i>

                            Clear All

                        </button>


                        <button
                            type="submit"
                            class="btn btn-primary"
                        >

                            <i class="fa-solid fa-floppy-disk"></i>

                            Save Permissions

                        </button>

                    </div>

                </div>

            </form>

        <?php endif; ?>

    </main>

</div>


<script>

/* =========================================================
   SIDEBAR
========================================================= */

function toggleSidebar() {

    const sidebar =
        document.querySelector('.sidebar') ||
        document.querySelector('.admin-sidebar');

    if (sidebar) {

        sidebar.classList.toggle(
            'mobile-open'
        );
    }
}


/* =========================================================
   PERMISSION CARDS
========================================================= */

function updatePermissionCard(checkbox) {

    const card =
        checkbox.closest(
            '[data-permission-card]'
        );

    if (!card) {
        return;
    }

    if (checkbox.checked) {

        card.classList.add(
            'assigned'
        );

    } else {

        card.classList.remove(
            'assigned'
        );
    }

    updateSelectedCount();
}


/* =========================================================
   SELECTED COUNT
========================================================= */

function updateSelectedCount() {

    const checked =
        document.querySelectorAll(
            '#permissionForm input[name="permission_ids[]"]:checked'
        );

    const counter =
        document.getElementById(
            'selectedPermissionCount'
        );

    if (counter) {

        counter.textContent =
            checked.length.toLocaleString();
    }
}


/* =========================================================
   SELECT ALL
========================================================= */

function toggleAllPermissions() {

    const checkboxes =
        document.querySelectorAll(
            '#permissionForm input[name="permission_ids[]"]'
        );

    if (!checkboxes.length) {
        return;
    }

    let allChecked = true;

    checkboxes.forEach(
        function (checkbox) {

            if (!checkbox.checked) {
                allChecked = false;
            }

        }
    );

    checkboxes.forEach(
        function (checkbox) {

            checkbox.checked =
                !allChecked;

            updatePermissionCard(
                checkbox
            );

        }
    );

    updateSelectedCount();
}


/* =========================================================
   CLEAR ALL
========================================================= */

function clearAllPermissions() {

    const checkboxes =
        document.querySelectorAll(
            '#permissionForm input[name="permission_ids[]"]:checked'
        );

    if (!checkboxes.length) {
        return;
    }

    const confirmed =
        confirm(
            'Are you sure you want to remove all permissions from this role?'
        );

    if (!confirmed) {
        return;
    }

    checkboxes.forEach(
        function (checkbox) {

            checkbox.checked = false;

            updatePermissionCard(
                checkbox
            );

        }
    );

    updateSelectedCount();
}


/* =========================================================
   CONFIRM SAVE
========================================================= */

document
    .getElementById('permissionForm')
    ?.addEventListener(
        'submit',
        function (event) {

            const selected =
                document.querySelectorAll(
                    '#permissionForm input[name="permission_ids[]"]:checked'
                ).length;

            const roleName =
                <?= json_encode(
                    $selectedRole['name'] ?? 'selected role',
                    JSON_HEX_TAG |
                    JSON_HEX_APOS |
                    JSON_HEX_QUOT |
                    JSON_HEX_AMP
                ) ?>;

            if (selected === 0) {

                const confirmed =
                    confirm(
                        'No permissions are selected for "' +
                        roleName +
                        '". This will remove all permissions from this role. Continue?'
                    );

                if (!confirmed) {

                    event.preventDefault();

                    return;
                }
            }

        }
    );


/* =========================================================
   ALERT AUTO HIDE
========================================================= */

setTimeout(
    function () {

        document
            .querySelectorAll(
                '.alert'
            )
            .forEach(
                function (alert) {

                    alert.style.transition =
                        'opacity .35s ease';

                    alert.style.opacity =
                        '0';

                    setTimeout(
                        function () {
                            alert.remove();
                        },
                        400
                    );

                }
            );

    },
    4500
);

</script>

</body>
</html>