<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    echo "Access Denied";
    exit;
}

function e($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

function build_url($params = []) {
    $query = array_merge($_GET, $params);
    foreach ($query as $k => $v) {
        if ($v === '' || $v === null) unset($query[$k]);
    }
    return '?' . http_build_query($query);
}

$search = trim($_GET['q'] ?? '');
$status = trim($_GET['status'] ?? 'all');
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 10;
$offset = ($page - 1) * $limit;

$countries = [];
$cRes = $conn->query("SELECT DISTINCT country FROM users WHERE role='agency' AND country IS NOT NULL AND country != '' ORDER BY country ASC");

if ($cRes) {
    while ($r = $cRes->fetch_assoc()) {
        $countries[] = $r['country'];
    }
}

$country = trim($_GET['country'] ?? '');

$where = "WHERE role = 'agency'";

if ($country !== '' && $country !== 'all') {
    $cEsc = $conn->real_escape_string($country);
    $where .= " AND country = '{$cEsc}'";
}

if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $where .= " AND (
        name LIKE '%{$s}%'
        OR email LIKE '%{$s}%'
        OR country LIKE '%{$s}%'
    )";
}

if ($status !== '' && $status !== 'all') {
    $where .= " AND is_approved = " . (int)$status;
}

/* Counts */
$countSql = "
    SELECT
        COUNT(*) AS total_count,
        SUM(CASE WHEN is_approved = 0 THEN 1 ELSE 0 END) AS pending_count,
        SUM(CASE WHEN is_approved = 1 THEN 1 ELSE 0 END) AS approved_count,
        SUM(CASE WHEN is_approved = 2 THEN 1 ELSE 0 END) AS rejected_count
    FROM users
    WHERE role = 'agency'
";
$countRes = $conn->query($countSql);
$counts = $countRes ? $countRes->fetch_assoc() : [
    'total_count' => 0,
    'pending_count' => 0,
    'approved_count' => 0,
    'rejected_count' => 0
];

$totalCount   = (int)($counts['total_count'] ?? 0);
$totalPages   = max(1, ceil($totalCount / $limit));

/* Main query */
$sql = "
    SELECT
        id,
        name,
        email,
        country,
        is_approved,
        approver_role,
        approver_id
    FROM users
    {$where}
    ORDER BY id DESC
    LIMIT {$limit} OFFSET {$offset}
";
$res = $conn->query($sql);

function status_text($s) {
    if ((int)$s === 1) return 'Approved';
    if ((int)$s === 2) return 'Rejected';
    return 'Pending';
}

function status_class($s) {
    if ((int)$s === 1) return 'approved';
    if ((int)$s === 2) return 'rejected';
    return 'pending';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>All Agency</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
    /* ===== BASE ===== */
body{
    background:#eef2f7;
    font-family:'Segoe UI',Arial,sans-serif;
    margin:0;
    color:#0f172a;
}

/* ===== LAYOUT ===== */
.main-content{
    margin-left:270px;
    padding:10px;
}

/* ===== CARD ===== */
.page-card{
    background:#fff;
    border:1px solid rgba(148,163,184,.12);
    border-radius:14px;
    box-shadow:0 6px 18px rgba(15,23,42,.05);
    padding:14px;
}

/* ===== HEADER ===== */
.header-row{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:12px;
}

.page-title{
    display:flex;
    align-items:center;
    gap:8px;
    font-size:22px;
    font-weight:800;
    margin:0;
}

.page-subtitle{
    color:#64748b;
    font-size:12px;
    margin-top:2px;
}

/* ===== BUTTON ===== */
.top-actions{
    display:flex;
    gap:6px;
}

.btn{
    display:inline-flex;
    align-items:center;
    gap:6px;
    border:none;
    cursor:pointer;
    text-decoration:none;
    font-weight:600;
    border-radius:10px;
    padding:6px 12px;
    font-size:12px;
}

.btn-dark{
    background:#374155;
    color:#fff;
}

.btn-dark:hover{
    background:#1f2937;
}

.btn-light{
    background:#fff;
    color:#374155;
    border:1px solid #d6dde8;
}

/* ===== STATS ===== */
.stat-grid{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:10px;
    margin-bottom:12px;
}

.stat-card{
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:12px;
    padding:10px;
}

.stat-label{
    color:#64748b;
    font-size:11px;
    font-weight:700;
    text-transform:uppercase;
}

.stat-value{
    font-size:18px;
    font-weight:800;
    margin-top:4px;
}

/* ===== FILTER ===== */
.filter-box{
    background:#f8fafc;
    border:1px solid #e2e8f0;
    border-radius:12px;
    padding:12px;
    margin-bottom:12px;
}

.filter-row{
    display:grid;
    grid-template-columns:2fr 1fr 1fr auto;
    gap:8px;
    align-items:end;
}

.form-label{
    font-size:12px;
    font-weight:600;
    margin-bottom:4px;
}

.form-control,
.form-select{
    padding:6px 10px;
    border-radius:8px;
    border:1px solid #d6dde8;
    font-size:12px;
}

/* ===== TABLE ===== */
.table-wrap{
    overflow-x:auto;
    border-radius:12px;
}

table{
    width:100%;
    border-collapse:collapse;
}

thead th{
    background:#374155;
    color:#fff;
    padding:8px;
    font-size:11px;
    white-space:nowrap;
}

tbody td{
    padding:8px;
    border-bottom:1px solid #eef2f7;
    vertical-align:middle;
    font-size:12px;
}

tbody tr:hover td{
    background:#f4f8ff;
}

/* ===== BADGE ===== */
.badge{
    padding:4px 8px;
    border-radius:999px;
    font-size:10px;
    font-weight:600;
}

.approved{ background:#dcfce7; color:#166534; }
.pending{ background:#fef3c7; color:#92400e; }
.rejected{ background:#fee2e2; color:#991b1b; }

/* ===== ACTION ===== */
.actions{
    display:flex;
    justify-content:center;   /* ADD THIS */
    align-items:center;       /* ADD THIS */
    gap:6px;
     width:100%;   
}
td:last-child{
    text-align:center;
    vertical-align:middle;
}
.action-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:6px;
    padding:5px 12px;
    font-size:12px;
    border-radius:10px;
    border:1px solid #d6dde8;
    background:#f1f5f9;
    color:#111827;
    text-decoration:none !important;
}

.action-btn:hover{
    background:#e2e8f0;
    text-decoration:none !important;
}

/* ===== PAGINATION ===== */
.pagination{
    display:flex;
    gap:6px;
    flex-wrap:wrap;
    margin-top:12px;
}

.page-link{
    min-width:32px;
    height:32px;
    padding:0 10px;
    border-radius:8px;
    border:1px solid #d6dde8;
    background:#fff;
    font-size:12px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-weight:600;
}

.page-link.active{
    background:#374155;
    color:#fff;
}

/* ===== EMPTY ===== */
.empty{
    text-align:center;
    padding:20px;
    color:#64748b;
    font-size:13px;
}

/* ===== MOBILE ===== */
@media(max-width:900px){
    .main-content{
        margin-left:0;
        padding:10px;
    }

    .stat-grid{
        grid-template-columns:1fr 1fr;
    }

    .filter-row{
        grid-template-columns:1fr;
    }

    .page-title{
        font-size:20px;
    }
}

@media(max-width:560px){
    .stat-grid{
        grid-template-columns:1fr;
    }
}
</style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="main-content">
    <div class="page-card">

        <div class="header-row">
            <div>
                <h1 class="page-title" style="color:#000">
                    <i class="fa-solid fa-building"></i>
                    All Agency
                </h1>
                <div class="page-subtitle">View every agency account and its approval status.</div>
            </div>

            <div class="top-actions">
                <a href="agency_requests.php" class="btn btn-dark">
                    <i class="fa-solid fa-user-check"></i> Agency Requests
                </a>
                <a href="agency_reports.php" class="btn btn-light">
                    <i class="fa-solid fa-file-lines"></i> Agency Reports
                </a>
            </div>
        </div>

        <div class="stat-grid">
            <div class="stat-card">
                <div class="stat-label">Total Agency</div>
                <div class="stat-value"><?php echo (int)$counts['total_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Approved</div>
                <div class="stat-value"><?php echo (int)$counts['approved_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Pending</div>
                <div class="stat-value"><?php echo (int)$counts['pending_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Rejected</div>
                <div class="stat-value"><?php echo (int)$counts['rejected_count']; ?></div>
            </div>
        </div>

        <form method="GET" class="filter-box">
            <div class="filter-row">
                <div>
                    <label class="form-label">Search</label>
                    <input type="text" name="q" class="form-control" value="<?php echo e($search); ?>" placeholder="Search name, email, country">
                </div>
<div>
    <label class="form-label">Country</label>
    <select name="country" class="form-select">
        <option value="all">All</option>
        <?php foreach($countries as $c): ?>
            <option value="<?php echo e($c); ?>" <?php echo $country === $c ? 'selected' : ''; ?>>
                <?php echo e($c); ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

                <div>
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All</option>
                        <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>Pending</option>
                        <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>Approved</option>
                        <option value="2" <?php echo $status === '2' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>

                <div>
                    <button type="submit" class="btn btn-dark">
                        <i class="fa-solid fa-filter"></i> Filter
                    </button>
                    <a href="agency_list.php" class="btn btn-light" style="margin-left:6px;">
                        <i class="fa-solid fa-rotate-left"></i> Reset
                    </a>
                </div>
            </div>
        </form>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th style="width:80px;">ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Country</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th style="width:160px;">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($res && $res->num_rows > 0): ?>
                    <?php while ($row = $res->fetch_assoc()): 
                        $st = (int)($row['is_approved'] ?? 0);
                    ?>
                        <tr>
                            <td><?php echo (int)$row['id']; ?></td>
                            <td><?php echo e($row['name']); ?></td>
                            <td><?php echo e($row['email']); ?></td>
                            <td><?php echo e($row['country'] ?: '-'); ?></td>
                            <td>
                                <span class="badge <?php echo status_class($st); ?>">
                                    <?php echo status_text($st); ?>
                                </span>
                            </td>
                            
                            <td><?php echo !empty($row['created_at']) ? date('d M Y', strtotime($row['created_at'])) : '-'; ?></td>
                            <td>
                                <div class="actions">
                                    <a href="agency_requests.php" class="action-btn">
                                        <i class="fa-solid fa-eye"></i> Requests
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="empty">No agency found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php
                $start = max(1, $page - 2);
                $end   = min($totalPages, $page + 2);
                if ($start > 1) {
                    echo '<a class="page-link" href="'.e(build_url(['page' => 1])).'">1</a>';
                    if ($start > 2) echo '<span class="page-link" style="pointer-events:none;">...</span>';
                }
                for ($p = $start; $p <= $end; $p++): ?>
                    <a class="page-link <?php echo $p === $page ? 'active' : ''; ?>" href="<?php echo e(build_url(['page' => $p])); ?>">
                        <?php echo $p; ?>
                    </a>
                <?php endfor;
                if ($end < $totalPages) {
                    if ($end < $totalPages - 1) echo '<span class="page-link" style="pointer-events:none;">...</span>';
                    echo '<a class="page-link" href="'.e(build_url(['page' => $totalPages])).'">'.$totalPages.'</a>';
                }
                ?>
            </div>
        <?php endif; ?>

    </div>
</div>

</body>
</html>