<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
iscms_require_roles(['SUPER_ADMIN', 'ADMIN']);

$pageTitle = 'Users';
$activeNav = 'users';

$sql = "SELECT u.id, u.employee_number, u.first_name, u.last_name, u.email, u.user_type, u.status,
               u.phone, u.last_login, u.created_at,
               r.role_name, r.role_code,
               o.org_name,
               d.dept_name
        FROM users u
        INNER JOIN roles r ON u.role_id = r.id
        LEFT JOIN organizations o ON u.org_id = o.id
        LEFT JOIN departments d ON u.dept_id = d.id
        ORDER BY u.last_name ASC, u.first_name ASC
        LIMIT 500";
$result = $conn->query($sql);
$rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$dbError = $result ? null : $conn->error;

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);

$created = isset($_GET['created']) && $_GET['created'] === '1';
?>
    <?php if ($created): ?>
    <div class="alert alert-success mb-4" style="font-size:.88rem"><i class="ri-checkbox-circle-line me-1"></i> User created successfully.</div>
    <?php endif; ?>

    <div class="page-header">
        <h1>Users</h1>
        <p>Staff and client accounts with roles and organisation linkage.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Related</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="add_user.php"><i class="ri-user-add-line"></i> Add user</a>
            <a class="qa-btn" href="user_roles.php"><i class="ri-shield-user-line"></i> Roles</a>
            <a class="qa-btn" href="role_permissions.php"><i class="ri-key-2-line"></i> Role permissions</a>
            <a class="qa-btn" href="permissions.php"><i class="ri-lock-unlock-line"></i> Permissions catalogue</a>
            <a class="qa-btn" href="profile.php"><i class="ri-user-line"></i> My profile</a>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-team-line"></i> Directory</h2>
            <span class="text-muted" style="font-size:.75rem"><?= count($rows) ?> shown</span>
        </div>
        <div class="table-responsive">
            <?php if ($dbError): ?>
                <div class="alert alert-danger m-3" style="font-size:.85rem">Unable to load data: <?= iscms_h($dbError) ?></div>
            <?php else: ?>
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Type</th>
                        <th>Role</th>
                        <th>Organisation</th>
                        <th>Department</th>
                        <th>Status</th>
                        <th>Last login</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="9"><i class="ri-inbox-line me-2"></i>No users</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <tr>
                            <td><strong><?= iscms_h(trim((string) ($r['first_name'] ?? '') . ' ' . (string) ($r['last_name'] ?? ''))) ?></strong></td>
                            <td class="iscms-mono"><small><?= iscms_h($r['email']) ?></small></td>
                            <td><small><?= iscms_h(str_replace('_', ' ', (string) $r['user_type'])) ?></small></td>
                            <td><small><?= iscms_h((string) ($r['role_name'] ?? '')) ?> <span class="text-muted">(<?= iscms_h((string) ($r['role_code'] ?? '')) ?>)</span></small></td>
                            <td><small><?= iscms_val($r['org_name'] ?? null) ?></small></td>
                            <td><small><?= iscms_val($r['dept_name'] ?? null) ?></small></td>
                            <td><?= iscms_status_badge((string) ($r['status'] ?? '')) ?></td>
                            <td><small class="text-muted"><?= !empty($r['last_login']) ? iscms_h(substr((string) $r['last_login'], 0, 19)) : '-' ?></small></td>
                            <td><a class="btn btn-sm btn-outline-primary py-0 px-2" style="font-size:.72rem" href="edit_user.php?id=<?= urlencode((string) ($r['id'] ?? '')) ?>"><i class="ri-pencil-line"></i> Edit</a></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
