<?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);
}

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';
}

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

/* Country list */
$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'];
    }
}

/* Filters */
$where = "WHERE role = 'agency'";

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

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

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

/* Summary cards */
$summarySql = "
    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'
";
$summaryRes = $conn->query($summarySql);
$summary = $summaryRes ? $summaryRes->fetch_assoc() : [
    'total_count' => 0,
    'pending_count' => 0,
    'approved_count' => 0,
    'rejected_count' => 0
];

/* Country report */
$countrySql = "
    SELECT 
        COALESCE(country, 'Unknown') AS country_name,
        COUNT(*) AS total_agency,
        SUM(CASE WHEN is_approved = 1 THEN 1 ELSE 0 END) AS approved_agency,
        SUM(CASE WHEN is_approved = 0 THEN 1 ELSE 0 END) AS pending_agency,
        SUM(CASE WHEN is_approved = 2 THEN 1 ELSE 0 END) AS rejected_agency
    FROM users
    WHERE role = 'agency'
    GROUP BY COALESCE(country, 'Unknown')
    ORDER BY total_agency DESC, country_name ASC
";
$countryRes = $conn->query($countrySql);
$countryRows = [];
if ($countryRes) {
    while ($row = $countryRes->fetch_assoc()) {
        $countryRows[] = $row;
    }
}

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

/* Count for pagination */
$countSql = "
    SELECT COUNT(*) AS total_rows
    FROM users
    {$where}
";
$countRes = $conn->query($countSql);
$totalRows = 0;
if ($countRes) {
    $totalRows = (int)($countRes->fetch_assoc()['total_rows'] ?? 0);
}
$totalPages = max(1, (int)ceil($totalRows / $limit));

/* CSV Export */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $exportSql = "
        SELECT
            id,
            name,
            email,
            country,
            is_approved,
            approver_role,
            approver_id
        FROM users
        {$where}
        ORDER BY id DESC
    ";
    $exportRes = $conn->query($exportSql);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=agency_report_' . date('Ymd_His') . '.csv');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Name', 'Email', 'Country', 'Status', 'Approver Role', 'Approver ID']);

    if ($exportRes) {
        while ($row = $exportRes->fetch_assoc()) {
            fputcsv($out, [
                $row['id'],
                $row['name'],
                $row['email'],
                $row['country'],
                status_text($row['is_approved']),
                $row['approver_role'],
                $row['approver_id'],
            ]);
        }
    }

    fclose($out);
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Agency Reports</title>

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

<style>
    body{
        background:#eef2f7;
        font-family:'Segoe UI',Arial,sans-serif;
        margin:0;
        color:#0f172a;
    }
    .main-content{
        margin-left:250px;
        padding:18px;
    }
    .page-card{
        background:#fff;
        border:1px solid rgba(148,163,184,.15);
        border-radius:18px;
        box-shadow:0 8px 26px rgba(15,23,42,.06);
        padding:22px;
    }
    .header-row{
        display:flex;
        justify-content:space-between;
        align-items:flex-start;
        gap:16px;
        flex-wrap:wrap;
        margin-bottom:18px;
    }
    .page-title{
        display:flex;
        align-items:center;
        gap:10px;
        font-size:20px;
        font-weight:800;
        margin:0;
        color:#000;
    }
    .page-subtitle{
        font-size:12px !important;
        color:#64748b;
        margin-top:4px;
    }
    .top-actions{
        display:flex;
        gap:10px;
        flex-wrap:wrap;
        align-items:center;
    }
    .btn{
        display:inline-flex;
        align-items:center;
        gap:8px;
        border:none;
        cursor:pointer;
        text-decoration:none;
        font-weight:700;
        border-radius:999px;
        padding:5px 10px;
        font-size:12px;
    }
    .btn-dark{
        background:#374155;   /* FIXED */
        color:#fff;
    }
    .btn-dark:hover{
        background:#2f3848;   /* slightly darker */
    }
    .btn-light{
        background:#fff;
        color:#374155;
        border:1px solid #d6dde8;
    }
    .btn-light:hover{ background:#f8fafc; }

    .stat-grid{
        display:grid;
        grid-template-columns:repeat(4,minmax(0,1fr));
        gap:14px;
        margin-bottom:18px;
    }
    .stat-card{
        background:linear-gradient(180deg,#fff,#f8fafc);
        border:1px solid #e5e7eb;
        border-radius:16px;
        padding:10px;
        box-shadow:0 6px 18px rgba(15,23,42,.04);
    }
    .stat-label{
        color:#64748b;
        font-size:13px;
        font-weight:700;
        text-transform:uppercase;
        letter-spacing:.04em;
        margin-bottom:8px;
    }
    .stat-value{
        font-size:18px;
        font-weight:800;
        color:#0f172a;
    }

    .filter-box{
        background:#f8fafc;
        border:1px solid #e2e8f0;
        border-radius:16px;
        padding:10px;
        margin-bottom:18px;
    }
    .filter-row{
        display:grid;
        grid-template-columns:2fr 1fr 1fr auto;
        gap:12px;
        align-items:end;
    }
    .form-label{
        display:block;
        font-size:11px;
        font-weight:700;
        margin-bottom:8px;
        color:#111827;
    }
    .form-control, .form-select{
        width:100%;
        box-sizing:border-box;
        padding:6px 10px;
        border-radius:12px;
        border:1px solid #d6dde8;
        outline:none;
        background:#fff;
        font-size:12px;
    }
    .form-control:focus, 
    .form-select:focus{
        border-color:#374155;   /* FIXED */
    }
    .section-head{
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:12px;
        flex-wrap:wrap;
        margin:6px 0 14px;
    }
    .section-title{
        font-size:18px;
        font-weight:800;
        color:#0f172a;
        display:flex;
        align-items:center;
        gap:8px;
        margin:0;
    }

    .table-wrap{
        overflow-x:hidden;
        border-radius:14px;
    }
    table{
        width:100%;
        border-collapse:collapse;
    }
    thead th{
        background:#374155;   /* FIXED */
        color:#fff;
        text-align:left;
        padding:8px;
        font-size:11px;
        white-space:nowrap;
    }
    tbody td{
        padding:8px;
        border-bottom:1px solid #eef2f7;
        font-size:12px;
        vertical-align:middle;
    }
    tbody tr:hover td{
        background:#f8fafc;
    }

    .badge{
        display:inline-flex;
        align-items:center;
        padding:4px 8px;
        border-radius:999px;
        font-size:10px;
        font-weight:700;
        text-transform:capitalize;
    }
    .approved{ background:#dcfce7; color:#166534; }
    .pending{ background:#fef3c7; color:#92400e; }
    .rejected{ background:#fee2e2; color:#991b1b; }

    .actions{
        display:flex;
        gap:8px;
        flex-wrap:wrap;
    }
    .action-btn{
        display:inline-flex;
        align-items:center;
        gap:6px;
        padding:5px 10px;
        border-radius:8px;
        font-size:11px;
        text-decoration:none;
        border:1px solid #d6dde8;
        color:#111827;
        background:#fff;
        white-space:nowrap;
    }
    .action-btn:hover{
        background:#f8fafc;
    }

    .country-grid{
        display:grid;
        grid-template-columns:repeat(2,minmax(0,1fr));
        gap:14px;
        margin-bottom:18px;
    }
    .mini-card{
        background:#fff;
        border:1px solid #e5e7eb;
        border-radius:16px;
        padding:16px;
        box-shadow:0 6px 18px rgba(15,23,42,.04);
    }
    .mini-card h4{
        margin:0 0 10px;
        font-size:16px;
        font-weight:800;
    }

    .pagination{
        display:flex;
        gap:8px;
        flex-wrap:wrap;
        margin-top:18px;
    }
    .page-link{
        display:inline-flex;
        align-items:center;
        justify-content:center;
        min-width:30px;
        height:30px !important;
    font-size:12px !important;
        padding:8px 12px;
        border-radius:10px;
        border:1px solid #d6dde8;
        background:#fff;
        text-decoration:none;
        color:#111827;
        font-weight:700;
    }
    .page-link.active{
        background:#374155;
        color:#fff;
        border-color:#374155;
    }
    .empty{
        text-align:center;
        padding:30px 10px;
        color:#64748b;
    }

    @media(max-width: 900px){
        .main-content{ margin-left:0; padding:14px; }
        .stat-grid{ grid-template-columns:repeat(2,minmax(0,1fr)); }
        .filter-row{ grid-template-columns:1fr; }
        .country-grid{ grid-template-columns:1fr; }
        .page-title{ font-size:24px; }
    }
    @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-file-lines"></i>
                    Agency Reports
                </h1>
                <div class="page-subtitle">Agency summary, status distribution, and country-wise overview.</div>
            </div>

            <div class="top-actions">
                <a href="<?php echo build_url(['export' => 'csv']); ?>" class="btn btn-dark">
                    <i class="fa-solid fa-file-csv"></i> Export CSV
                </a>
                <a href="agency_reports.php" class="btn btn-light">
                    <i class="fa-solid fa-rotate-left"></i> Reset
                </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)$summary['total_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Approved</div>
                <div class="stat-value"><?php echo (int)$summary['approved_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Pending</div>
                <div class="stat-value"><?php echo (int)$summary['pending_count']; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Rejected</div>
                <div class="stat-value"><?php echo (int)$summary['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($q); ?>" placeholder="Search name, email, country">
                </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>
                    <label class="form-label">Country</label>
                    <select name="country" class="form-select">
                        <option value="all" <?php echo $country === 'all' ? 'selected' : ''; ?>>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>
                    <button type="submit" class="btn btn-dark">
                        <i class="fa-solid fa-filter"></i> Filter
                    </button>
                    <a href="agency_reports.php" class="btn btn-light" style="margin-left:6px;">
                        <i class="fa-solid fa-rotate-left"></i> Reset
                    </a>
                </div>
            </div>
        </form>

        <div class="country-grid">
            <div class="mini-card">
                <h4><i class="fa-solid fa-chart-simple"></i> Status Report</h4>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Status</th>
                                <th>Count</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><span class="badge approved">Approved</span></td>
                                <td><?php echo (int)$summary['approved_count']; ?></td>
                            </tr>
                            <tr>
                                <td><span class="badge pending">Pending</span></td>
                                <td><?php echo (int)$summary['pending_count']; ?></td>
                            </tr>
                            <tr>
                                <td><span class="badge rejected">Rejected</span></td>
                                <td><?php echo (int)$summary['rejected_count']; ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="mini-card">
                <h4><i class="fa-solid fa-globe"></i> Country Wise Report</h4>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Country</th>
                                <th>Total</th>
                                <th>Approved</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($countryRows)): ?>
                                <?php foreach ($countryRows as $row): ?>
                                    <tr>
                                        <td><?php echo e($row['country_name']); ?></td>
                                        <td><?php echo (int)$row['total_agency']; ?></td>
                                        <td><?php echo (int)$row['approved_agency']; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="3" class="empty">No country data found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="section-head">
            <h3 class="section-title">
                <i class="fa-solid fa-users"></i>
                Agency List
            </h3>
        </div>

        <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>Approved By</th>
                        <th style="width:160px;">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($listRes && $listRes->num_rows > 0): ?>
                    <?php while ($row = $listRes->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 e($row['approver_role'] ?: 'Admin'); ?>
                                </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="8" 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>