<?php
/**
 * pages/users.php — User & admin list (super_admin only)
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';

require_role('super_admin');

$search   = get_search();
$page_num = get_current_page();
$per_page = 20;
$filter_role = $_GET['role'] ?? '';

// Count
$count_sql  = 'SELECT COUNT(*) FROM users u WHERE 1=1';
$count_args = [];
if ($search !== '') {
    $count_sql   .= ' AND (u.name LIKE ? OR u.email LIKE ? OR u.username LIKE ?)';
    $count_args[] = "%$search%";
    $count_args[] = "%$search%";
    $count_args[] = "%$search%";
}
if ($filter_role !== '') {
    $count_sql   .= ' AND u.role = ?';
    $count_args[] = $filter_role;
}
$count_stmt = db()->prepare($count_sql);
$count_stmt->execute($count_args);
$total = (int) $count_stmt->fetchColumn();

$pager = paginate($total, $per_page, $page_num);

// Fetch
$sql  = 'SELECT u.id, u.name, u.email, u.username, u.role, u.active,
                u.last_login, u.created_at,
                a.name AS agency_name
           FROM users u
           LEFT JOIN agencies a ON a.id = u.agency_id
          WHERE 1=1';
$args = [];
if ($search !== '') {
    $sql    .= ' AND (u.name LIKE ? OR u.email LIKE ? OR u.username LIKE ?)';
    $args[]  = "%$search%";
    $args[]  = "%$search%";
    $args[]  = "%$search%";
}
if ($filter_role !== '') {
    $sql    .= ' AND u.role = ?';
    $args[]  = $filter_role;
}
$sql .= ' ORDER BY u.name LIMIT ' . $per_page . ' OFFSET ' . $pager['offset'];

$stmt = db()->prepare($sql);
$stmt->execute($args);
$users = $stmt->fetchAll();

$page_title  = 'Users & Admins';
$active_page = 'users';
require_once __DIR__ . '/../templates/head.php';
?>

<?php require_once __DIR__ . '/../templates/header.php'; ?>
<?php require_once __DIR__ . '/../templates/sidebar.php'; ?>

<div class="nxl-everything">
    <div class="nxl-container">
        <div class="main-content" style="padding-top: 80px;">

            <div class="page-header d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
                <div>
                    <h4 class="fw-bold mb-1">Users &amp; Admins</h4>
                    <p class="text-muted mb-0"><?= number_format($total) ?> user<?= $total !== 1 ? 's' : '' ?></p>
                </div>
                <a href="<?= base_url('pages/user-form.php') ?>" class="btn btn-primary">
                    <i class="feather-user-plus me-1"></i> Add User
                </a>
            </div>

            <?php render_flash(); ?>

            <!-- Filters -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
                    <form method="GET" action="" class="d-flex flex-wrap gap-2 align-items-center">
                        <input type="search" name="q" class="form-control" style="max-width:260px;"
                               placeholder="Search name, email, username…" value="<?= e($search) ?>">
                        <select name="role" class="form-control" style="max-width:180px;">
                            <option value="">All Roles</option>
                            <option value="super_admin" <?= $filter_role === 'super_admin' ? 'selected' : '' ?>>Super Admin</option>
                            <option value="agency_user" <?= $filter_role === 'agency_user' ? 'selected' : '' ?>>Agency User</option>
                        </select>
                        <button type="submit" class="btn btn-outline-primary">Filter</button>
                        <?php if ($search || $filter_role): ?>
                        <a href="users.php" class="btn btn-outline-secondary">Clear</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <!-- Table -->
            <div class="card border-0 shadow-sm">
                <div class="card-body p-0">
                    <?php if (empty($users)): ?>
                    <div class="text-center text-muted py-5">No users found.</div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Name</th>
                                    <th>Username</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Agency</th>
                                    <th class="text-center">Status</th>
                                    <th>Last Login</th>
                                    <th class="text-end">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users as $u): ?>
                                <tr>
                                    <td class="fw-semibold"><?= e($u['name']) ?></td>
                                    <td class="text-muted small"><?= e($u['username']) ?></td>
                                    <td><?= e($u['email']) ?></td>
                                    <td>
                                        <?php if ($u['role'] === 'super_admin'): ?>
                                        <span class="badge bg-primary">Super Admin</span>
                                        <?php else: ?>
                                        <span class="badge bg-secondary">Agency User</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= $u['agency_name'] ? e($u['agency_name']) : '—' ?></td>
                                    <td class="text-center"><?= badge_active((int)$u['active']) ?></td>
                                    <td class="text-muted small">
                                        <?= $u['last_login'] ? fmt_datetime($u['last_login']) : 'Never' ?>
                                    </td>
                                    <td class="text-end">
                                        <div class="d-flex justify-content-end gap-1">
                                            <a href="<?= base_url('pages/user-form.php?id=' . $u['id']) ?>"
                                               class="btn btn-sm btn-outline-secondary">Edit</a>

                                            <?php if ($u['id'] !== current_user_id()): ?>
                                            <form method="POST"
                                                  action="<?= base_url('actions/user-toggle.php') ?>"
                                                  class="d-inline"
                                                  onsubmit="return confirm('<?= $u['active'] ? 'Deactivate' : 'Activate' ?> this user?')">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                                                <input type="hidden" name="active" value="<?= $u['active'] ? '0' : '1' ?>">
                                                <button type="submit"
                                                        class="btn btn-sm <?= $u['active'] ? 'btn-outline-danger' : 'btn-outline-success' ?>">
                                                    <?= $u['active'] ? 'Deactivate' : 'Activate' ?>
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($pager['total_pages'] > 1): ?>
                    <div class="d-flex justify-content-between align-items-center px-3 py-2 border-top">
                        <small class="text-muted">Page <?= $pager['current'] ?> of <?= $pager['total_pages'] ?></small>
                        <div class="d-flex gap-1">
                            <?php if ($pager['has_prev']): ?>
                            <a href="?q=<?= urlencode($search) ?>&role=<?= urlencode($filter_role) ?>&page=<?= $pager['current'] - 1 ?>"
                               class="btn btn-sm btn-outline-secondary">&laquo; Prev</a>
                            <?php endif; ?>
                            <?php if ($pager['has_next']): ?>
                            <a href="?q=<?= urlencode($search) ?>&role=<?= urlencode($filter_role) ?>&page=<?= $pager['current'] + 1 ?>"
                               class="btn btn-sm btn-outline-secondary">Next &raquo;</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

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