<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'User Permissions';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'role_permissions', 'approve');
    }
}

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

if (!function_exists('up_flash')) {
    function up_flash(string $type, string $message): void {
        $_SESSION['user_permissions_flash'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('up_get_flash')) {
    function up_get_flash(): array {
        $items = $_SESSION['user_permissions_flash'] ?? [];
        unset($_SESSION['user_permissions_flash']);
        return $items;
    }
}

if (!function_exists('up_table_exists')) {
    function up_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table
        ");
        $stmt->execute([':table' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('role_key_from_user_role')) {
    function role_key_from_user_role(int $userRole): string
    {
        $map = [
            1 => 'super_admin',
            2 => 'admin',
            3 => 'manager',
            4 => 'frontdesk',
            5 => 'cashier',
            6 => 'stores',
            7 => 'accounts',
            8 => 'housekeeping',
            9 => 'owner',
        ];
        return $map[$userRole] ?? 'user';
    }
}

if (!function_exists('role_label_from_user_role')) {
    function role_label_from_user_role(int $userRole): string
    {
        $map = [
            1 => 'Super Admin',
            2 => 'Admin',
            3 => 'Manager',
            4 => 'Front Desk',
            5 => 'Cashier',
            6 => 'Stores',
            7 => 'Accounts',
            8 => 'Housekeeping',
            9 => 'Owner',
        ];
        return $map[$userRole] ?? 'User';
    }
}

if (!function_exists('up_user_name')) {
    function up_user_name(array $user): string {
        $name = trim((string)($user['firstname'] ?? '') . ' ' . (string)($user['lastname'] ?? ''));
        return $name !== '' ? $name : (string)($user['username'] ?? ('User #' . ($user['id'] ?? '')));
    }
}

$permissionGroups = [
    'Overview' => [
        'dashboard' => 'Main Dashboard',
        'executive_dashboard' => 'Executive Dashboard',
    ],
    'Reservations & Front Desk' => [
        'reservations' => 'Reservations',
        'availability_calendar' => 'Availability Calendar',
        'rooming' => 'Rooming / Planner',
        'guests' => 'Guests',
        'frontdesk' => 'Front Desk',
        'arrivals' => 'Arrivals',
        'departures' => 'Departures',
        'room_rack' => 'Room Rack',
        'housekeeping' => 'Housekeeping',
        'night_audit' => 'Night Audit',
        'folios' => 'Folios',
        'payments' => 'Guest Payments',
    ],
    'Stores & Inventory' => [
        'inventory_dashboard' => 'Inventory Dashboard',
        'inventory_items' => 'Inventory Items',
        'store_locations' => 'Store Locations',
        'suppliers' => 'Suppliers',
        'purchase_orders' => 'Purchase Orders',
        'grn' => 'GRN / Purchases',
        'stock_movements' => 'Stock Movements',
        'stock_take' => 'Stock Take',
        'recipes' => 'Recipes',
        'recipe_profit_report' => 'Recipe Profit Report',
        'stock_valuation_report' => 'Stock Valuation',
        'low_stock_report' => 'Low Stock Report',
        'month_end_inventory' => 'Month-End Inventory Closing',
    ],
    'POS Controls' => [
        'pos' => 'POS Screen',
        'pos_orders' => 'POS Orders',
        'pos_void' => 'Void POS Receipts',
        'pos_shifts' => 'POS Shifts',
        'pos_approvals' => 'POS Approvals',
        'pos_sales_report' => 'POS Sales Report',
    ],
    'Finance & Management' => [
        'supplier_ledger' => 'Supplier Ledger',
        'supplier_payments' => 'Supplier Payments',
        'owner_profit_dashboard' => 'Owner Profit Dashboard',
        'management_dashboard' => 'Management Dashboard',
        'audit_log' => 'Audit Log',
        'reports' => 'Reports',
    ],
    'Channel Manager' => [
        'channel_dashboard' => 'Channel Dashboard',
        'channel_settings' => 'Channel Connections',
        'channel_mapping' => 'Channel Mapping',
        'channel_push' => 'Push Availability/Rates',
        'channel_pull' => 'Pull Bookings',
        'channel_logs' => 'Channel Sync Logs',
    ],
    'System' => [
        'settings' => 'Settings',
        'role_permissions' => 'Role Permissions',
        'user_permissions' => 'User Permissions',
        'masters' => 'Masters',
    ],
];

$permissionLabels = [];
foreach ($permissionGroups as $group => $items) {
    foreach ($items as $key => $label) {
        $permissionLabels[$key] = $label;
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS user_permissions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        user_id INT UNSIGNED NOT NULL,
        permission_key VARCHAR(120) NOT NULL,
        can_view TINYINT(1) NULL,
        can_create TINYINT(1) NULL,
        can_edit TINYINT(1) NULL,
        can_delete TINYINT(1) NULL,
        can_approve TINYINT(1) NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_user_permission (user_id, permission_key),
        INDEX idx_user_permissions_user (user_id),
        INDEX idx_user_permissions_key (permission_key)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS user_permission_audit (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        user_id INT UNSIGNED NULL,
        permission_key VARCHAR(120) NULL,
        action VARCHAR(80) NOT NULL,
        details TEXT NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_user_permission_audit_user (user_id),
        INDEX idx_user_permission_audit_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS role_permissions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        role_key VARCHAR(80) NOT NULL,
        permission_key VARCHAR(120) NOT NULL,
        can_view TINYINT(1) NOT NULL DEFAULT 0,
        can_create TINYINT(1) NOT NULL DEFAULT 0,
        can_edit TINYINT(1) NOT NULL DEFAULT 0,
        can_delete TINYINT(1) NOT NULL DEFAULT 0,
        can_approve TINYINT(1) NOT NULL DEFAULT 0,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_role_permission (role_key, permission_key)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare user permission tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_user_permissions') {
            $userId = (int)($_POST['user_id'] ?? 0);
            if ($userId <= 0) throw new RuntimeException('Please select a user.');

            $stmt = $pdo->prepare("SELECT * FROM users WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$user) throw new RuntimeException('User not found.');

            $posted = $_POST['perm'] ?? [];
            if (!is_array($posted)) $posted = [];

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("DELETE FROM user_permissions WHERE user_id=:user_id");
            $stmt->execute([':user_id' => $userId]);

            $stmtInsert = $pdo->prepare("
                INSERT INTO user_permissions
                (user_id, permission_key, can_view, can_create, can_edit, can_delete, can_approve)
                VALUES
                (:user_id, :permission_key, :can_view, :can_create, :can_edit, :can_delete, :can_approve)
            ");

            foreach ($permissionLabels as $permissionKey => $label) {
                $p = $posted[$permissionKey] ?? [];

                /*
                 * NULL = use role default
                 * 1 = force allow
                 * 0 = force deny
                 */
                $values = [];
                foreach (['view','create','edit','delete','approve'] as $actionKey) {
                    $raw = $p[$actionKey] ?? '';
                    if ($raw === '1') $values[$actionKey] = 1;
                    elseif ($raw === '0') $values[$actionKey] = 0;
                    else $values[$actionKey] = null;
                }

                /*
                 * Only store rows where at least one action has an override.
                 */
                $hasOverride = false;
                foreach ($values as $v) {
                    if ($v !== null) {
                        $hasOverride = true;
                        break;
                    }
                }

                if (!$hasOverride) continue;

                $stmtInsert->execute([
                    ':user_id' => $userId,
                    ':permission_key' => $permissionKey,
                    ':can_view' => $values['view'],
                    ':can_create' => $values['create'],
                    ':can_edit' => $values['edit'],
                    ':can_delete' => $values['delete'],
                    ':can_approve' => $values['approve'],
                ]);
            }

            $stmtAudit = $pdo->prepare("
                INSERT INTO user_permission_audit
                (user_id, action, details, created_by)
                VALUES
                (:user_id, 'save_overrides', :details, :created_by)
            ");
            $stmtAudit->execute([
                ':user_id' => $userId,
                ':details' => 'Individual permission overrides saved.',
                ':created_by' => $_SESSION['user_id'] ?? null,
            ]);

            $pdo->commit();

            up_flash('success', 'Individual permissions saved for ' . up_user_name($user) . '.');
            header('Location: user_permissions.php?user_id=' . $userId);
            exit;
        }

        if ($action === 'clear_user_permissions') {
            $userId = (int)($_POST['user_id'] ?? 0);
            if ($userId <= 0) throw new RuntimeException('Please select a user.');

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("DELETE FROM user_permissions WHERE user_id=:user_id");
            $stmt->execute([':user_id' => $userId]);

            $stmtAudit = $pdo->prepare("
                INSERT INTO user_permission_audit
                (user_id, action, details, created_by)
                VALUES
                (:user_id, 'clear_overrides', :details, :created_by)
            ");
            $stmtAudit->execute([
                ':user_id' => $userId,
                ':details' => 'All individual overrides cleared; user now follows role permissions only.',
                ':created_by' => $_SESSION['user_id'] ?? null,
            ]);

            $pdo->commit();

            up_flash('success', 'Individual overrides cleared. User now follows role permissions only.');
            header('Location: user_permissions.php?user_id=' . $userId);
            exit;
        }

        if ($action === 'copy_role_to_user') {
            $userId = (int)($_POST['user_id'] ?? 0);
            if ($userId <= 0) throw new RuntimeException('Please select a user.');

            $stmt = $pdo->prepare("SELECT * FROM users WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$user) throw new RuntimeException('User not found.');

            $roleKey = role_key_from_user_role((int)$user['user_role']);

            $stmt = $pdo->prepare("SELECT * FROM role_permissions WHERE role_key=:role_key");
            $stmt->execute([':role_key' => $roleKey]);
            $rolePerms = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("DELETE FROM user_permissions WHERE user_id=:user_id");
            $stmt->execute([':user_id' => $userId]);

            $stmtInsert = $pdo->prepare("
                INSERT INTO user_permissions
                (user_id, permission_key, can_view, can_create, can_edit, can_delete, can_approve)
                VALUES
                (:user_id, :permission_key, :can_view, :can_create, :can_edit, :can_delete, :can_approve)
            ");

            foreach ($rolePerms as $rp) {
                $stmtInsert->execute([
                    ':user_id' => $userId,
                    ':permission_key' => $rp['permission_key'],
                    ':can_view' => (int)$rp['can_view'],
                    ':can_create' => (int)$rp['can_create'],
                    ':can_edit' => (int)$rp['can_edit'],
                    ':can_delete' => (int)$rp['can_delete'],
                    ':can_approve' => (int)$rp['can_approve'],
                ]);
            }

            $stmtAudit = $pdo->prepare("
                INSERT INTO user_permission_audit
                (user_id, action, details, created_by)
                VALUES
                (:user_id, 'copy_role', :details, :created_by)
            ");
            $stmtAudit->execute([
                ':user_id' => $userId,
                ':details' => 'Role permissions copied as user-specific overrides from role: ' . $roleKey,
                ':created_by' => $_SESSION['user_id'] ?? null,
            ]);

            $pdo->commit();

            up_flash('success', 'Role permissions copied to this user as individual overrides.');
            header('Location: user_permissions.php?user_id=' . $userId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        up_flash('danger', $e->getMessage());
        header('Location: user_permissions.php');
        exit;
    }
}

$userSearch = trim((string)($_GET['q'] ?? ''));
$selectedUserId = (int)($_GET['user_id'] ?? 0);

$users = [];
try {
    $where = "1=1";
    $params = [];

    if ($userSearch !== '') {
        $where .= " AND (firstname LIKE :q OR lastname LIKE :q OR username LIKE :q OR email LIKE :q)";
        $params[':q'] = '%' . $userSearch . '%';
    }

    $stmt = $pdo->prepare("
        SELECT u.*,
               COALESCE(upc.override_count,0) AS override_count
        FROM users u
        LEFT JOIN (
            SELECT user_id, COUNT(*) AS override_count
            FROM user_permissions
            GROUP BY user_id
        ) upc ON upc.user_id = u.id
        WHERE {$where}
        ORDER BY u.firstname ASC, u.lastname ASC, u.username ASC
        LIMIT 300
    ");
    $stmt->execute($params);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($selectedUserId <= 0 && $users) {
        $selectedUserId = (int)$users[0]['id'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load users: ' . $e->getMessage();
}

$selectedUser = null;
$userPermissions = [];
$rolePermissions = [];

if ($selectedUserId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id=:id LIMIT 1");
        $stmt->execute([':id' => $selectedUserId]);
        $selectedUser = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($selectedUser) {
            $roleKey = role_key_from_user_role((int)$selectedUser['user_role']);

            $stmt = $pdo->prepare("SELECT * FROM role_permissions WHERE role_key=:role_key");
            $stmt->execute([':role_key' => $roleKey]);
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $rolePermissions[$row['permission_key']] = $row;
            }

            $stmt = $pdo->prepare("SELECT * FROM user_permissions WHERE user_id=:user_id");
            $stmt->execute([':user_id' => $selectedUserId]);
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $userPermissions[$row['permission_key']] = $row;
            }
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load selected user permissions: ' . $e->getMessage();
    }
}

$auditRows = [];
try {
    $stmt = $pdo->prepare("
        SELECT *
        FROM user_permission_audit
        WHERE (:user_id = 0 OR user_id = :user_id)
        ORDER BY created_at DESC, id DESC
        LIMIT 50
    ");
    $stmt->execute([':user_id' => $selectedUserId]);
    $auditRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

function up_action_value(array $userPermissions, string $permissionKey, string $column): string
{
    if (!isset($userPermissions[$permissionKey])) return '';
    $v = $userPermissions[$permissionKey][$column] ?? null;
    if ($v === null) return '';
    return (string)(int)$v;
}

function up_role_badge(array $rolePermissions, string $permissionKey, string $column): string
{
    $v = (int)($rolePermissions[$permissionKey][$column] ?? 0);
    return $v === 1 ? 'Role allows' : 'Role denies';
}

$flashes = up_get_flash();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-person-lock"></i> System Security</div>
            <div class="hero-title mt-2">Individual User Permissions</div>
            <div class="hero-subtitle mt-2">
                Override role permissions for one specific user. Blank means “use role default”.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="users.php" class="btn btn-light me-2">
                <i class="bi bi-people me-2"></i>Users
            </a>
            <a href="role_permissions.php" class="btn btn-outline-light">
                <i class="bi bi-shield-lock me-2"></i>Role Permissions
            </a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-3">
        <div class="card panel-card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Select User</h5>
            </div>
            <div class="card-body">
                <form method="get" class="mb-3">
                    <label class="form-label">Search</label>
                    <div class="input-group">
                        <input type="text" name="q" class="form-control" value="<?php echo h($userSearch); ?>" placeholder="Name / email / username">
                        <button class="btn btn-primary"><i class="bi bi-search"></i></button>
                    </div>
                </form>

                <div class="user-list">
                    <?php if (!$users): ?>
                        <div class="text-muted">No users found.</div>
                    <?php else: foreach ($users as $user): ?>
                        <?php
                            $isActive = $selectedUserId === (int)$user['id'];
                            $roleKey = role_key_from_user_role((int)$user['user_role']);
                        ?>
                        <a href="user_permissions.php?user_id=<?php echo (int)$user['id']; ?>"
                           class="user-link <?php echo $isActive ? 'active' : ''; ?>">
                            <div>
                                <strong><?php echo h(up_user_name($user)); ?></strong>
                                <div class="small text-muted"><?php echo h($user['email'] ?? ''); ?></div>
                                <div class="small">
                                    <?php echo h(role_label_from_user_role((int)$user['user_role'])); ?>
                                    <span class="text-muted">(<?php echo h($roleKey); ?>)</span>
                                </div>
                            </div>
                            <?php if ((int)$user['override_count'] > 0): ?>
                                <span class="badge text-bg-warning"><?php echo (int)$user['override_count']; ?></span>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; endif; ?>
                </div>
            </div>
        </div>

        <?php if ($selectedUser): ?>
            <div class="card panel-card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">User Summary</h5>
                </div>
                <div class="card-body">
                    <div class="fw-bold fs-5"><?php echo h(up_user_name($selectedUser)); ?></div>
                    <div class="text-muted mb-2"><?php echo h($selectedUser['email'] ?? ''); ?></div>

                    <div class="mb-2">
                        <span class="badge text-bg-primary">
                            <?php echo h(role_label_from_user_role((int)$selectedUser['user_role'])); ?>
                        </span>
                    </div>

                    <div class="small text-muted">
                        Role key: <code><?php echo h(role_key_from_user_role((int)$selectedUser['user_role'])); ?></code>
                    </div>
                    <div class="small text-muted">
                        Individual overrides: <strong><?php echo count($userPermissions); ?></strong>
                    </div>

                    <hr>

                    <form method="post" class="mb-2" onsubmit="return confirm('Copy this user role permissions as individual overrides?');">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="copy_role_to_user">
                        <input type="hidden" name="user_id" value="<?php echo (int)$selectedUserId; ?>">
                        <button class="btn btn-outline-primary w-100">
                            <i class="bi bi-copy me-2"></i>Copy Role to User
                        </button>
                    </form>

                    <form method="post" onsubmit="return confirm('Clear all individual overrides for this user?');">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="clear_user_permissions">
                        <input type="hidden" name="user_id" value="<?php echo (int)$selectedUserId; ?>">
                        <button class="btn btn-outline-danger w-100">
                            <i class="bi bi-eraser me-2"></i>Clear Overrides
                        </button>
                    </form>
                </div>
            </div>
        <?php endif; ?>

        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0">Legend</h5>
            </div>
            <div class="card-body small">
                <div class="mb-2"><span class="badge text-bg-light border">Role</span> uses role permission.</div>
                <div class="mb-2"><span class="badge text-bg-success">Allow</span> forces access on.</div>
                <div class="mb-2"><span class="badge text-bg-danger">Deny</span> forces access off.</div>
                <div><strong>Blank</strong> means no override.</div>
            </div>
        </div>
    </div>

    <div class="col-xl-9">
        <?php if (!$selectedUser): ?>
            <div class="alert alert-info">Select a user to manage individual permissions.</div>
        <?php else: ?>
            <form method="post">
                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                <input type="hidden" name="action" value="save_user_permissions">
                <input type="hidden" name="user_id" value="<?php echo (int)$selectedUserId; ?>">

                <div class="card panel-card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-0">Overrides for <?php echo h(up_user_name($selectedUser)); ?></h5>
                            <div class="small text-muted">
                                Leave a field blank to inherit from role:
                                <strong><?php echo h(role_label_from_user_role((int)$selectedUser['user_role'])); ?></strong>
                            </div>
                        </div>
                        <button class="btn btn-success">
                            <i class="bi bi-save me-2"></i>Save Overrides
                        </button>
                    </div>

                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-modern align-middle mb-0 permission-table">
                                <thead>
                                <tr>
                                    <th style="min-width:260px">Module</th>
                                    <th class="text-center">View</th>
                                    <th class="text-center">Create</th>
                                    <th class="text-center">Edit</th>
                                    <th class="text-center">Delete</th>
                                    <th class="text-center">Approve</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($permissionGroups as $group => $perms): ?>
                                    <tr class="group-row">
                                        <td colspan="6"><?php echo h($group); ?></td>
                                    </tr>
                                    <?php foreach ($perms as $permissionKey => $label): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo h($label); ?></strong>
                                                <div class="small text-muted"><?php echo h($permissionKey); ?></div>
                                            </td>

                                            <?php foreach ([
                                                'view' => 'can_view',
                                                'create' => 'can_create',
                                                'edit' => 'can_edit',
                                                'delete' => 'can_delete',
                                                'approve' => 'can_approve'
                                            ] as $short => $column): ?>
                                                <?php
                                                    $current = up_action_value($userPermissions, $permissionKey, $column);
                                                    $roleText = up_role_badge($rolePermissions, $permissionKey, $column);
                                                    $roleAllows = strpos($roleText, 'allows') !== false;
                                                ?>
                                                <td class="text-center">
                                                    <select name="perm[<?php echo h($permissionKey); ?>][<?php echo h($short); ?>]"
                                                            class="form-select form-select-sm permission-select <?php echo $current === '1' ? 'force-allow' : ($current === '0' ? 'force-deny' : 'inherit'); ?>">
                                                        <option value="" <?php echo $current === '' ? 'selected' : ''; ?>>
                                                            Role <?php echo $roleAllows ? '✓' : '✕'; ?>
                                                        </option>
                                                        <option value="1" <?php echo $current === '1' ? 'selected' : ''; ?>>Allow</option>
                                                        <option value="0" <?php echo $current === '0' ? 'selected' : ''; ?>>Deny</option>
                                                    </select>
                                                </td>
                                            <?php endforeach; ?>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="card-footer bg-light d-flex justify-content-between align-items-center">
                        <span class="text-muted small">Overrides affect this user only.</span>
                        <button class="btn btn-success">
                            <i class="bi bi-save me-2"></i>Save Overrides
                        </button>
                    </div>
                </div>
            </form>

            <div class="card panel-card">
                <div class="card-header">
                    <h5 class="mb-0">User Permission Audit</h5>
                </div>
                <div class="card-body p-0">
                    <table class="table table-modern mb-0">
                        <thead>
                        <tr>
                            <th>Date</th>
                            <th>Action</th>
                            <th>Details</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$auditRows): ?>
                            <tr><td colspan="3" class="text-center text-muted py-4">No audit records.</td></tr>
                        <?php else: foreach ($auditRows as $row): ?>
                            <tr>
                                <td><?php echo h($row['created_at']); ?></td>
                                <td><strong><?php echo h($row['action']); ?></strong></td>
                                <td><?php echo h($row['details']); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="alert alert-warning mt-4">
    <strong>Important:</strong> For these individual overrides to work, update
    <code>/rooms/includes/permission_check.php</code> so it checks <code>user_permissions</code> before <code>role_permissions</code>.
</div>

<style>
.user-list{display:flex;flex-direction:column;gap:8px;max-height:580px;overflow:auto}
.user-link{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;text-decoration:none;color:#0f172a;border:1px solid rgba(15,23,42,.08);border-radius:16px;padding:12px;background:#fff}
.user-link:hover{background:#f8fafc}
.user-link.active{background:#eff6ff;border-color:#93c5fd}
.permission-table .group-row td{background:#0f172a!important;color:#fff!important;font-weight:900;text-transform:uppercase;font-size:12px;letter-spacing:.06em}
.permission-select{min-width:92px}
.permission-select.force-allow{background:#dcfce7;border-color:#86efac;color:#166534;font-weight:800}
.permission-select.force-deny{background:#fee2e2;border-color:#fca5a5;color:#991b1b;font-weight:800}
.permission-select.inherit{background:#f8fafc;color:#64748b}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('.permission-select').forEach(function(sel){
        sel.addEventListener('change', function(){
            this.classList.remove('force-allow', 'force-deny', 'inherit');
            if (this.value === '1') this.classList.add('force-allow');
            else if (this.value === '0') this.classList.add('force-deny');
            else this.classList.add('inherit');
        });
    });
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
