<?php
/**
 * pages/agencies.php — Agency 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_role('super_admin');

$search   = get_search();
$page_num = get_current_page();
$per_page = 20;

// Count
$count_sql  = 'SELECT COUNT(*) FROM agencies WHERE 1=1';
$count_args = [];
if ($search !== '') {
    $count_sql  .= ' AND (name LIKE ? OR contact_email LIKE ?)';
    $count_args  = ["%$search%", "%$search%"];
}
$total = (int) db()->prepare($count_sql)->execute($count_args) ? db()->prepare($count_sql) : 0;
$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 a.id, a.name, a.contact_email, a.phone, a.active, a.created_at,
                (SELECT COUNT(*) FROM learners l WHERE l.agency_id = a.id) AS learner_count
           FROM agencies a
          WHERE 1=1';
$args = [];
if ($search !== '') {
    $sql  .= ' AND (a.name LIKE ? OR a.contact_email LIKE ?)';
    $args  = ["%$search%", "%$search%"];
}
$sql .= ' ORDER BY a.name LIMIT ' . $per_page . ' OFFSET ' . $pager['offset'];

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

$page_title  = 'Agencies';
$active_page = 'agencies';
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">Agencies</h4>
                    <p class="text-muted mb-0"><?= number_format($total) ?> agenc<?= $total === 1 ? 'y' : 'ies' ?> found</p>
                </div>
                <a href="<?= base_url('pages/agency-form.php') ?>" class="btn btn-primary">
                    <i class="feather-plus me-1"></i> Add Agency
                </a>
            </div>

            <?php render_flash(); ?>

            <!-- Search -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body py-2">
                    <form method="GET" action="" class="d-flex gap-2">
                        <input type="search" name="q" class="form-control" style="max-width:320px;"
                               placeholder="Search name or email…" value="<?= e($search) ?>">
                        <button type="submit" class="btn btn-outline-primary">Search</button>
                        <?php if ($search): ?>
                        <a href="agencies.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($agencies)): ?>
                    <div class="text-center text-muted py-5">
                        <?= $search ? 'No agencies match your search.' : 'No agencies yet. Add one above.' ?>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Agency Name</th>
                                    <th>Contact Email</th>
                                    <th>Phone</th>
                                    <th class="text-center">Learners</th>
                                    <th class="text-center">Status</th>
                                    <th class="text-center">Added</th>
                                    <th class="text-end">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($agencies as $ag): ?>
                                <tr>
                                    <td class="fw-semibold"><?= e($ag['name']) ?></td>
                                    <td><?= $ag['contact_email'] ? e($ag['contact_email']) : '—' ?></td>
                                    <td><?= $ag['phone'] ? e($ag['phone']) : '—' ?></td>
                                    <td class="text-center"><?= (int)$ag['learner_count'] ?></td>
                                    <td class="text-center"><?= badge_active((int)$ag['active']) ?></td>
                                    <td class="text-center text-muted small"><?= fmt_date($ag['created_at']) ?></td>
                                    <td class="text-end">
                                        <a href="<?= base_url('pages/agency-form.php?id=' . $ag['id']) ?>"
                                           class="btn btn-sm btn-outline-secondary">Edit</a>
                                    </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) ?>&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) ?>&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'; ?>
