<?php
/**
 * pages/learners.php — Learner list
 * Super admin sees all. Agency user sees only their agency.
 */
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_login();

$is_super  = is_super_admin();
$agency_id = current_user_agency_id();

$search      = get_search();
$page_num    = get_current_page();
$per_page    = 25;
$filter_ag   = $is_super ? (isset($_GET['agency_id']) && ctype_digit($_GET['agency_id']) ? (int)$_GET['agency_id'] : 0) : (int)$agency_id;

// Count
$count_sql  = 'SELECT COUNT(*) FROM learners l WHERE 1=1';
$count_args = [];

if (!$is_super) {
    $count_sql   .= ' AND l.agency_id = ?';
    $count_args[] = $agency_id;
} elseif ($filter_ag) {
    $count_sql   .= ' AND l.agency_id = ?';
    $count_args[] = $filter_ag;
}
if ($search !== '') {
    $count_sql   .= ' AND (l.first_name LIKE ? OR l.last_name LIKE ? OR l.email LIKE ?)';
    $count_args[] = "%$search%";
    $count_args[] = "%$search%";
    $count_args[] = "%$search%";
}
$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 l.id, l.first_name, l.last_name, l.email, l.phone, l.active, l.created_at,
                a.name AS agency_name,
                (SELECT COUNT(*) FROM certificates c WHERE c.learner_id = l.id) AS cert_count
           FROM learners l
           JOIN agencies a ON a.id = l.agency_id
          WHERE 1=1';
$args = [];

if (!$is_super) {
    $sql    .= ' AND l.agency_id = ?';
    $args[]  = $agency_id;
} elseif ($filter_ag) {
    $sql    .= ' AND l.agency_id = ?';
    $args[]  = $filter_ag;
}
if ($search !== '') {
    $sql    .= ' AND (l.first_name LIKE ? OR l.last_name LIKE ? OR l.email LIKE ?)';
    $args[]  = "%$search%";
    $args[]  = "%$search%";
    $args[]  = "%$search%";
}
$sql .= ' ORDER BY l.last_name, l.first_name LIMIT ' . $per_page . ' OFFSET ' . $pager['offset'];

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

// Agency list for filter dropdown (super admin only)
if ($is_super) {
    $agencies = db()->query('SELECT id, name FROM agencies WHERE active = 1 ORDER BY name')->fetchAll();
}

$page_title  = 'Learners';
$active_page = 'learners';
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">Learners</h4>
                    <p class="text-muted mb-0"><?= number_format($total) ?> learner<?= $total !== 1 ? 's' : '' ?></p>
                </div>
            </div>

            <?php render_flash(); ?>

            <!-- Filters -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body py-2">
                    <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:280px;"
                               placeholder="Search name or email…" value="<?= e($search) ?>">
                        <?php if ($is_super): ?>
                        <select name="agency_id" class="form-control" style="max-width:220px;">
                            <option value="">All Agencies</option>
                            <?php foreach ($agencies as $ag): ?>
                            <option value="<?= $ag['id'] ?>" <?= $filter_ag === $ag['id'] ? 'selected' : '' ?>>
                                <?= e($ag['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php endif; ?>
                        <button type="submit" class="btn btn-outline-primary">Filter</button>
                        <?php if ($search || $filter_ag): ?>
                        <a href="learners.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($learners)): ?>
                    <div class="text-center text-muted py-5">No learners 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>Email</th>
                                    <th>Phone</th>
                                    <?php if ($is_super): ?><th>Agency</th><?php endif; ?>
                                    <th class="text-center">Certs</th>
                                    <th class="text-center">Status</th>
                                    <th>Added</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($learners as $lr): ?>
                                <tr>
                                    <td class="fw-semibold">
                                        <?= e($lr['first_name'] . ' ' . $lr['last_name']) ?>
                                    </td>
                                    <td><?= $lr['email'] ? e($lr['email']) : '—' ?></td>
                                    <td><?= $lr['phone'] ? e($lr['phone']) : '—' ?></td>
                                    <?php if ($is_super): ?>
                                    <td><?= e($lr['agency_name']) ?></td>
                                    <?php endif; ?>
                                    <td class="text-center">
                                        <?php if ($lr['cert_count'] > 0): ?>
                                        <a href="<?= base_url('pages/certificates.php?learner_id=' . $lr['id']) ?>"
                                           class="badge bg-success text-white">
                                            <?= (int)$lr['cert_count'] ?>
                                        </a>
                                        <?php else: ?>
                                        <span class="text-muted">0</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center"><?= badge_active((int)$lr['active']) ?></td>
                                    <td class="text-muted small"><?= fmt_date($lr['created_at']) ?></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) ?>&agency_id=<?= $filter_ag ?>&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) ?>&agency_id=<?= $filter_ag ?>&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'; ?>
