<div class="settings-header">
    <div class="sh-icon"><i class="fa-solid fa-gear"></i></div>
    <div class="sh-text">
        <h2>System Settings</h2>
        <div class="sh-sub"><?= e(setting('company_name', 'Rice & Curry')) ?> · Configure your shop, staff and system preferences</div>
    </div>
    <button type="submit" form="rmsShopInfoForm" class="btn sh-save-btn"><i class="fa-solid fa-circle-check"></i> Save All Settings</button>
</div>

<div class="settings-tabs">
    <button type="button" class="st-tab active" data-tab="shop" onclick="rmsSettingsTab('shop', this)"><i class="fa-solid fa-shop"></i> Shop Info</button>
    <button type="button" class="st-tab" data-tab="users" onclick="rmsSettingsTab('users', this)"><i class="fa-solid fa-users"></i> Users</button>
    <button type="button" class="st-tab" data-tab="roles" onclick="rmsSettingsTab('roles', this)"><i class="fa-solid fa-shield-halved"></i> Roles &amp; Permissions</button>
    <button type="button" class="st-tab" data-tab="log" onclick="rmsSettingsTab('log', this)"><i class="fa-solid fa-clipboard-list"></i> Activity Log</button>
</div>

<!-- ============ SHOP INFO TAB ============ -->
<div id="rms-settings-shop" class="settings-tab-panel">
    <form method="POST" action="<?= Router::url('admin/settings/save') ?>" enctype="multipart/form-data" id="rmsShopInfoForm">
        <?= $csrf ?>
        <div class="settings-grid">
            <div>
                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-store" style="color:var(--color-accent);margin-right:6px;"></i>Shop Information</h3>
                    <div class="form-group">
                        <label>Shop Name</label>
                        <input type="text" name="company_name" class="form-control" value="<?= e($current['company_name'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Tagline (login page)</label>
                        <textarea name="tagline" class="form-control" rows="2"><?= e($current['tagline'] ?? '') ?></textarea>
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" name="company_address" class="form-control" value="<?= e($current['company_address'] ?? '') ?>">
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" name="company_phone" class="form-control" value="<?= e($current['company_phone'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="company_email" class="form-control" value="<?= e($current['company_email'] ?? '') ?>">
                        </div>
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                        <div class="form-group">
                            <label>Currency Symbol</label>
                            <input type="text" name="currency_symbol" class="form-control" value="<?= e($current['currency_symbol'] ?? 'LKR') ?>">
                        </div>
                        <div class="form-group">
                            <label>Timezone</label>
                            <select name="timezone" class="form-control">
                                <?php foreach (['Asia/Colombo', 'Asia/Kolkata', 'Asia/Dubai', 'UTC'] as $tz): ?>
                                <option value="<?= $tz ?>" <?= ($current['timezone'] ?? 'Asia/Colombo') === $tz ? 'selected' : '' ?>><?= $tz ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div style="font-size:11px;color:var(--color-text-muted);margin-top:4px;">Now: <?= date('d M Y, H:i') ?></div>
                        </div>
                    </div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-image" style="color:var(--color-accent);margin-right:6px;"></i>Shop Logo</h3>
                    <?php if (!empty($current['logo_path'])): ?>
                    <div class="settings-img-preview">
                        <img src="<?= BASE_URL ?>/<?= e($current['logo_path']) ?>" alt="Logo">
                        <label class="remove-image-check"><input type="checkbox" name="remove_logo" value="1"> Remove logo</label>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="logo" class="form-control" accept="image/png,image/jpeg,image/gif,image/webp">
                    <div style="font-size:11px;color:var(--color-text-muted);margin-top:4px;">PNG, JPG, GIF · Max 2MB</div>
                </div>
            </div>

            <div>
                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-panorama" style="color:var(--color-accent);margin-right:6px;"></i>Login Page Background</h3>
                    <?php if (!empty($current['login_background_path'])): ?>
                    <div class="settings-img-preview settings-img-preview-wide">
                        <img src="<?= BASE_URL ?>/<?= e($current['login_background_path']) ?>" alt="Login background">
                        <label class="remove-image-check"><input type="checkbox" name="remove_login_background" value="1"> Remove background</label>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="login_background" class="form-control" accept="image/png,image/jpeg,image/webp">
                    <div style="font-size:11px;color:var(--color-text-muted);margin-top:4px;">PNG, JPG, WebP · Max 3MB · 1200×1600px recommended</div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-hashtag" style="color:var(--color-accent);margin-right:6px;"></i>Order Numbering</h3>
                    <div class="form-group">
                        <label>Order/Invoice Prefix</label>
                        <input type="text" name="order_number_prefix" class="form-control" value="<?= e($current['order_number_prefix'] ?? 'ORD') ?>">
                        <div style="font-size:11px;color:var(--color-text-muted);margin-top:4px;">e.g. <?= e($current['order_number_prefix'] ?? 'ORD') ?>-20260721-0001</div>
                    </div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-qrcode" style="color:var(--color-accent);margin-right:6px;"></i>QR Code / Tracking Link</h3>
                    <div class="form-group">
                        <label>Public Base URL</label>
                        <input type="text" name="public_base_url" class="form-control" value="<?= e($current['public_base_url'] ?? '') ?>" placeholder="e.g. http://192.168.1.5/rms/public">
                    </div>
                    <div class="alert alert-success" style="margin-bottom:0;font-size:12px;">
                        <i class="fa-solid fa-circle-info"></i>
                        <strong>Why this matters:</strong> the barcode label's QR code needs a link a <em>phone</em> can open.
                        On XAMPP, the system normally uses "localhost" — but a phone scanning the QR tries to reach
                        <em>its own</em> localhost, not your PC, so tracking fails.
                        <br><br>
                        <strong>Fix:</strong> find your PC's local network IP (Windows: run <code>ipconfig</code>, look for "IPv4 Address")
                        and enter it here, e.g. <code>http://192.168.1.5/rms/public</code> — make sure your phone is on the
                        same Wi-Fi. Leave blank to use the auto-detected address (fine once this is deployed on a real domain via cPanel).
                    </div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-building-columns" style="color:var(--color-accent);margin-right:6px;"></i>Bank Transfer Details (Customer App)</h3>
                    <div style="font-size:11.5px;color:var(--color-text-muted);margin-bottom:12px;">Shown to customers who choose "Bank Transfer" at checkout in the ordering app.</div>
                    <div class="form-group"><label>Account Name</label><input type="text" name="bank_account_name" class="form-control" value="<?= e($current['bank_account_name'] ?? '') ?>" placeholder="e.g. CurryPot.lk"></div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                        <div class="form-group"><label>Bank Name</label><input type="text" name="bank_name" class="form-control" value="<?= e($current['bank_name'] ?? '') ?>" placeholder="e.g. Commercial Bank"></div>
                        <div class="form-group"><label>Account Number</label><input type="text" name="bank_account_number" class="form-control" value="<?= e($current['bank_account_number'] ?? '') ?>"></div>
                    </div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-credit-card" style="color:var(--color-accent);margin-right:6px;"></i>PayHere Card Payment (Customer App)</h3>
                    <div class="alert alert-success" style="font-size:12px;margin-bottom:12px;">
                        <i class="fa-solid fa-circle-info"></i> These credentials come from your <a href="https://www.payhere.lk/merchant/" target="_blank" style="color:var(--color-teal);">PayHere Merchant Dashboard</a> → Integrations → Add Domain/App.
                        Keep the Merchant Secret private — never share it publicly.
                    </div>
                    <div class="form-group">
                        <label>Mode</label>
                        <select name="payhere_mode" class="form-control">
                            <option value="sandbox" <?= ($current['payhere_mode'] ?? 'sandbox') === 'sandbox' ? 'selected' : '' ?>>Sandbox (testing — no real money moves)</option>
                            <option value="live" <?= ($current['payhere_mode'] ?? '') === 'live' ? 'selected' : '' ?>>Live (real payments)</option>
                        </select>
                    </div>
                    <div class="form-group"><label>Merchant ID</label><input type="text" name="payhere_merchant_id" class="form-control" value="<?= e($current['payhere_merchant_id'] ?? '') ?>"></div>
                    <div class="form-group"><label>Merchant Secret</label><input type="password" name="payhere_merchant_secret" class="form-control" value="<?= e($current['payhere_merchant_secret'] ?? '') ?>" autocomplete="new-password"></div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-clock" style="color:var(--color-accent);margin-right:6px;"></i>Order Hours (Customer App)</h3>
                    <div style="font-size:11.5px;color:var(--color-text-muted);margin-bottom:12px;">Outside these hours, the customer app shows "Currently Closed" and won't accept new orders. Times are based on this server's clock.</div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px;">
                        <div class="form-group"><label>Opens At</label><input type="time" name="order_open_time" class="form-control" value="<?= e($current['order_open_time'] ?? '09:00') ?>"></div>
                        <div class="form-group"><label>Closes At</label><input type="time" name="order_close_time" class="form-control" value="<?= e($current['order_close_time'] ?? '22:00') ?>"></div>
                    </div>
                    <div class="settings-toggle-row" style="background:#FBEBEB;border-radius:8px;padding:10px 12px;">
                        <label style="display:flex;align-items:center;gap:8px;font-size:12.5px;font-weight:700;color:#8A2A2A;">
                            <input type="checkbox" name="orders_manually_paused" value="1" <?= ($current['orders_manually_paused'] ?? '0') === '1' ? 'checked' : '' ?>>
                            <i class="fa-solid fa-triangle-exclamation"></i> Temporarily pause all orders (overrides hours above — use for holidays/emergencies)
                        </label>
                    </div>
                </div>

                <div class="panel">
                    <h3 style="margin-bottom:14px;"><i class="fa-solid fa-receipt" style="color:var(--color-accent);margin-right:6px;"></i>Receipt Options</h3>
                    <div class="settings-toggle-row">
                        <div>
                            <div class="st-label">Show Tax on Receipt</div>
                            <div class="st-sub">Display tax breakdown line</div>
                        </div>
                        <label class="rms-switch">
                            <input type="checkbox" name="show_tax_on_receipt" value="1" <?= ($current['show_tax_on_receipt'] ?? '1') === '1' ? 'checked' : '' ?>>
                            <span></span>
                        </label>
                    </div>
                    <div class="settings-toggle-row">
                        <div>
                            <div class="st-label">Show Logo on Receipt</div>
                            <div class="st-sub">Print shop logo at top</div>
                        </div>
                        <label class="rms-switch">
                            <input type="checkbox" name="show_logo_on_receipt" value="1" <?= ($current['show_logo_on_receipt'] ?? '1') === '1' ? 'checked' : '' ?>>
                            <span></span>
                        </label>
                    </div>
                    <div class="form-group" style="margin-top:14px;">
                        <label>Receipt Footer Note</label>
                        <textarea name="receipt_footer_note" class="form-control" rows="2"><?= e($current['receipt_footer_note'] ?? '') ?></textarea>
                    </div>
                    <div style="font-size:11px;color:var(--color-text-muted);">Used once receipt printing is enabled in the Orders module.</div>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- ============ USERS TAB ============ -->
<div id="rms-settings-users" class="settings-tab-panel" style="display:none;">
    <div style="display:flex;justify-content:flex-end;margin-bottom:14px;">
        <?php if (Auth::can('users', 'add')): ?>
        <button type="button" class="btn btn-primary" onclick="rmsOpenModal('rmsAddUserModal')"><i class="fa-solid fa-plus"></i> Add User</button>
        <?php endif; ?>
    </div>
    <div class="panel" style="padding:0;overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>Name</th><th>Username</th><th>Role</th><th>Phone</th><th>Status</th><th>Last Login</th><th></th></tr></thead>
    <tbody>
    <?php foreach ($users as $u): ?>
    <tr>
        <td><?= e($u['full_name']) ?><?= $u['is_protected'] ? ' <span class="badge badge-gray"><i class="fa-solid fa-shield-halved"></i> Protected</span>' : '' ?></td>
        <td><?= e($u['username']) ?></td>
        <td><span class="badge badge-gold"><?= e($u['role_name']) ?></span></td>
        <td><?= e($u['phone'] ?? '—') ?></td>
        <td><?= $u['is_active'] ? '<span class="badge badge-green"><i class="fa-solid fa-circle-check"></i> Active</span>' : '<span class="badge badge-red"><i class="fa-solid fa-circle-xmark"></i> Inactive</span>' ?></td>
        <td><?= $u['last_login'] ? date('d M Y, h:i A', strtotime($u['last_login'])) : '—' ?></td>
        <td style="white-space:nowrap;">
            <?php if (Auth::can('users', 'edit')): ?>
            <button type="button" class="btn btn-secondary" style="padding:5px 10px;font-size:12px;" onclick="rmsOpenModal('rmsEditUser<?= $u['id'] ?>')"><i class="fa-solid fa-pen"></i></button>
            <?php endif; ?>
            <?php if (Auth::can('users', 'delete') && !$u['is_protected'] && (int)$u['id'] !== Auth::id()): ?>
            <form method="POST" action="<?= Router::url('admin/users/delete') ?>" style="display:inline;" onsubmit="return confirm('Delete this user?');">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <button type="submit" class="btn btn-danger" style="padding:5px 10px;font-size:12px;"><i class="fa-solid fa-trash"></i></button>
            </form>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($users)): ?>
    <tr><td colspan="7" style="text-align:center;color:var(--color-text-muted);padding:30px;">No users yet.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<!-- ============ ROLES & PERMISSIONS TAB ============ -->
<div id="rms-settings-roles" class="settings-tab-panel" style="display:none;">
    <div class="panel" style="padding:0;overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>Role</th><th>Description</th><th>Staff Count</th><th></th></tr></thead>
    <tbody>
    <?php foreach ($roles as $r): ?>
    <tr>
        <td><?= e($r['role_name']) ?><?= $r['is_system'] ? ' <span class="badge badge-gray">System</span>' : '' ?></td>
        <td><?= e($r['description'] ?? '—') ?></td>
        <td><?= (int) $r['user_count'] ?></td>
        <td><button type="button" class="btn btn-secondary" style="padding:5px 12px;font-size:12px;" onclick="rmsOpenModal('rmsRolePerms<?= $r['id'] ?>')"><i class="fa-solid <?= $r['is_system'] ? 'fa-eye' : 'fa-pen' ?>"></i> <?= $r['is_system'] ? 'View Permissions' : 'Edit Permissions' ?></button></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
    </table>
    </div>
</div>

<!-- ============ ACTIVITY LOG TAB ============ -->
<div id="rms-settings-log" class="settings-tab-panel" style="display:none;">
    <div class="panel" style="padding:0;overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>Date/Time</th><th>User</th><th>Action</th><th>Module</th><th>Description</th><th>IP</th></tr></thead>
    <tbody>
    <?php foreach ($auditLogs as $log): ?>
    <tr>
        <td style="white-space:nowrap;"><?= date('d M Y, h:i A', strtotime($log['created_at'])) ?></td>
        <td><?= e($log['full_name'] ?? 'System') ?></td>
        <td><span class="badge badge-gold"><i class="fa-solid fa-bolt"></i><?= e($log['action']) ?></span></td>
        <td><?= e($log['module_key'] ?? '—') ?></td>
        <td><?= e($log['description'] ?? '') ?></td>
        <td><?= e($log['ip_address'] ?? '') ?></td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($auditLogs)): ?>
    <tr><td colspan="6" style="text-align:center;color:var(--color-text-muted);padding:30px;">No activity logged yet.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<!-- ============ Add User Modal ============ -->
<?php if (Auth::can('users', 'add')): ?>
<div class="rms-modal-overlay" id="rmsAddUserModal">
    <div class="rms-modal" style="max-width:560px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-user-plus" style="color:var(--color-teal);margin-right:6px;"></i>Add User</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAddUserModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('admin/users/store') ?>">
            <?= $csrf ?>
            <div class="form-group"><label>Full Name</label><input type="text" name="full_name" class="form-control" required></div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="form-group"><label>Username</label><input type="text" name="username" class="form-control" required></div>
                <div class="form-group"><label>Password</label><input type="password" name="password" class="form-control" required></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control"></div>
                <div class="form-group"><label>Phone</label><input type="text" name="phone" class="form-control"></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="form-group">
                    <label>Role</label>
                    <select name="role_id" class="form-control">
                        <?php foreach ($roles as $r): ?>
                        <option value="<?= $r['id'] ?>"><?= e($r['role_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>NIC Number</label><input type="text" name="nic_number" class="form-control"></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;">
                <div class="form-group">
                    <label>Wage Type</label>
                    <select name="wage_type" class="form-control">
                        <?php foreach (['MONTHLY','DAILY','PIECE_RATE'] as $wt): ?>
                        <option value="<?= $wt ?>"><?= $wt ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>Basic Salary</label><input type="number" step="0.01" name="basic_salary" class="form-control" value="0"></div>
                <div class="form-group"><label>Daily Wage</label><input type="number" step="0.01" name="daily_wage" class="form-control" value="0"></div>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Create User</button>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- ============ Edit User Modals ============ -->
<?php foreach ($users as $u): if (!Auth::can('users', 'edit')) continue; ?>
<div class="rms-modal-overlay" id="rmsEditUser<?= $u['id'] ?>">
    <div class="rms-modal" style="max-width:560px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i>Edit — <?= e($u['full_name']) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditUser<?= $u['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('admin/users/update') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $u['id'] ?>">
            <div class="form-group"><label>Full Name</label><input type="text" name="full_name" class="form-control" value="<?= e($u['full_name']) ?>" required></div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="form-group"><label>Username</label><input type="text" class="form-control" value="<?= e($u['username']) ?>" readonly></div>
                <div class="form-group"><label>Password (leave blank to keep)</label><input type="password" name="password" class="form-control"></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" value="<?= e($u['email'] ?? '') ?>"></div>
                <div class="form-group"><label>Phone</label><input type="text" name="phone" class="form-control" value="<?= e($u['phone'] ?? '') ?>"></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="form-group">
                    <label>Role</label>
                    <select name="role_id" class="form-control" <?= $u['is_protected'] ? 'disabled' : '' ?>>
                        <?php foreach ($roles as $r): ?>
                        <option value="<?= $r['id'] ?>" <?= $u['role_id'] == $r['id'] ? 'selected' : '' ?>><?= e($r['role_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>NIC Number</label><input type="text" name="nic_number" class="form-control" value="<?= e($u['nic_number'] ?? '') ?>"></div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;">
                <div class="form-group">
                    <label>Wage Type</label>
                    <select name="wage_type" class="form-control">
                        <?php foreach (['MONTHLY','DAILY','PIECE_RATE'] as $wt): ?>
                        <option value="<?= $wt ?>" <?= $u['wage_type'] === $wt ? 'selected' : '' ?>><?= $wt ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>Basic Salary</label><input type="number" step="0.01" name="basic_salary" class="form-control" value="<?= e((string)$u['basic_salary']) ?>"></div>
                <div class="form-group"><label>Daily Wage</label><input type="number" step="0.01" name="daily_wage" class="form-control" value="<?= e((string)$u['daily_wage']) ?>"></div>
            </div>
            <?php if (!$u['is_protected']): ?>
            <div class="form-group"><label style="display:flex;align-items:center;gap:8px;"><input type="checkbox" name="is_active" value="1" <?= $u['is_active'] ? 'checked' : '' ?>> Active (can log in)</label></div>
            <?php endif; ?>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-floppy-disk"></i> Save Changes</button>
        </form>
    </div>
</div>
<?php endforeach; ?>

<!-- ============ Role Permission Modals ============ -->
<?php foreach ($roles as $r): $locked = (bool) $r['is_system']; $matrix = $permissionMatrices[$r['id']]; ?>
<div class="rms-modal-overlay" id="rmsRolePerms<?= $r['id'] ?>">
    <div class="rms-modal" style="max-width:640px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-shield-halved" style="color:var(--color-teal);margin-right:6px;"></i><?= e($r['role_name']) ?> Permissions</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsRolePerms<?= $r['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <?php if ($locked): ?>
        <div class="alert alert-success"><i class="fa-solid fa-lock"></i> System role — always has full access, can't be changed.</div>
        <?php endif; ?>
        <form method="POST" action="<?= Router::url('admin/roles/permissions/save') ?>">
            <?= $csrf ?>
            <input type="hidden" name="role_id" value="<?= $r['id'] ?>">
            <div style="max-height:50vh;overflow-y:auto;">
            <table class="data-table">
            <thead><tr><th>Module</th><th style="text-align:center;">View</th><th style="text-align:center;">Add</th><th style="text-align:center;">Edit</th><th style="text-align:center;">Delete</th></tr></thead>
            <tbody>
            <?php foreach ($matrix as $row): ?>
            <tr>
                <td><?= e($row['module_label']) ?></td>
                <?php foreach (['view','add','edit','delete'] as $action): ?>
                <td style="text-align:center;">
                    <input type="checkbox" name="perm[<?= $row['permission_id'] ?>][<?= $action ?>]" value="1" <?= $row['can_' . $action] ? 'checked' : '' ?> <?= $locked ? 'disabled' : '' ?>>
                </td>
                <?php endforeach; ?>
            </tr>
            <?php endforeach; ?>
            </tbody>
            </table>
            </div>
            <?php if (!$locked): ?>
            <button type="submit" class="btn btn-primary" style="margin-top:16px;width:100%;"><i class="fa-solid fa-floppy-disk"></i> Save Permissions</button>
            <?php endif; ?>
        </form>
    </div>
</div>
<?php endforeach; ?>

<style>
.settings-header {
    display: flex; align-items: center; gap: 16px;
    background: linear-gradient(120deg, var(--color-navy) 0%, var(--color-navy-2) 100%);
    color: #fff; border-radius: var(--radius); padding: 20px 24px; margin-bottom: 20px;
}
.settings-header .sh-icon {
    width: 44px; height: 44px; border-radius: 11px; background: rgba(255,255,255,0.14);
    display: flex; align-items: center; justify-content: center; font-size: 19px; flex-shrink: 0;
}
.settings-header .sh-text { flex: 1; }
.settings-header h2 { font-size: 19px; margin: 0 0 2px; }
.settings-header .sh-sub { font-size: 12.5px; color: rgba(255,255,255,0.75); }
.settings-header .sh-save-btn { background: #fff; color: var(--color-navy); font-weight: 700; flex-shrink: 0; }
.settings-header .sh-save-btn:hover { background: #F1F1F1; }

.settings-tabs {
    display: flex; gap: 4px; background: var(--color-surface); border: 1px solid var(--color-border);
    border-radius: 10px; padding: 4px; margin-bottom: 20px; overflow-x: auto;
}
.st-tab {
    flex: 1; white-space: nowrap; padding: 10px 16px; border-radius: 8px; border: none; background: transparent;
    color: var(--color-text-muted); font-size: 13px; font-weight: 700; cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: 7px;
}
.st-tab.active { background: var(--color-bg); color: var(--color-text); box-shadow: var(--shadow-sm); }

.settings-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; align-items: start; }
.settings-img-preview {
    display: flex; align-items: center; gap: 12px; margin-bottom: 10px;
    padding: 10px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-bg);
}
.settings-img-preview img { width: 64px; height: 64px; object-fit: cover; border-radius: 8px; flex-shrink: 0; }
.settings-img-preview-wide { flex-direction: column; align-items: center; text-align: center; }
.settings-img-preview-wide img { width: 100%; max-width: 260px; height: 140px; }
.settings-img-preview .remove-image-check { font-size: 12px; color: var(--color-danger); display: flex; align-items: center; gap: 6px; }

.settings-toggle-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--color-border); }
.settings-toggle-row .st-label { font-size: 13px; font-weight: 700; }
.settings-toggle-row .st-sub { font-size: 11.5px; color: var(--color-text-muted); }

.rms-switch { position: relative; display: inline-block; width: 42px; height: 24px; flex-shrink: 0; }
.rms-switch input { opacity: 0; width: 0; height: 0; }
.rms-switch span { position: absolute; inset: 0; background: var(--color-border); border-radius: 100px; transition: 0.2s; cursor: pointer; }
.rms-switch span::before { content: ''; position: absolute; width: 18px; height: 18px; left: 3px; top: 3px; background: #fff; border-radius: 50%; transition: 0.2s; }
.rms-switch input:checked + span { background: var(--color-teal); }
.rms-switch input:checked + span::before { transform: translateX(18px); }

@media (max-width: 900px) {
    .settings-grid { grid-template-columns: 1fr; }
    .settings-header { flex-wrap: wrap; }
}
</style>

<script>
function rmsSettingsTab(tab, btn) {
    document.querySelectorAll('.settings-tab-panel').forEach(p => p.style.display = 'none');
    document.getElementById('rms-settings-' + tab).style.display = 'block';
    document.querySelectorAll('.st-tab').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const url = new URL(window.location);
    url.searchParams.set('tab', tab);
    window.history.replaceState({}, '', url);
}
document.addEventListener('DOMContentLoaded', function () {
    const params = new URLSearchParams(window.location.search);
    const tab = params.get('tab');
    if (tab) {
        const btn = document.querySelector('.st-tab[data-tab="' + tab + '"]');
        if (btn) rmsSettingsTab(tab, btn);
    }
});
</script>
