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

/* CSRF */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

$msg = "";
$msgType = "success";

/* Handle approve / reject */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $msg = "Invalid request.";
        $msgType = "error";
    } else {
        $id = (int)($_POST['id'] ?? 0);
        $action = $_POST['action'] ?? '';

        if ($id > 0 && $action === 'approve') {
            $stmt = $conn->prepare("UPDATE users SET is_approved = 1 WHERE id = ? AND role = 'agency'");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                $msg = "Agency approved successfully.";
                $msgType = "success";
            } else {
                $msg = "Failed to approve agency.";
                $msgType = "error";
            }
            $stmt->close();
        } elseif ($id > 0 && $action === 'reject') {
            $stmt = $conn->prepare("UPDATE users SET is_approved = 2 WHERE id = ? AND role = 'agency'");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                $msg = "Agency rejected successfully.";
                $msgType = "success";
            } else {
                $msg = "Failed to reject agency.";
                $msgType = "error";
            }
            $stmt->close();
        }
    }
}

/* Counts */
$countStmt = $conn->prepare("
    SELECT
        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,
        COUNT(*) AS total_count
    FROM users
    WHERE role = 'agency'
");
$countStmt->execute();
$countRes = $countStmt->get_result();
$counts = $countRes ? $countRes->fetch_assoc() : [
    'pending_count' => 0,
    'approved_count' => 0,
    'rejected_count' => 0,
    'total_count' => 0
];
$countStmt->close();

$pending_count  = (int)($counts['pending_count'] ?? 0);
$approved_count = (int)($counts['approved_count'] ?? 0);
$rejected_count = (int)($counts['rejected_count'] ?? 0);
$total_count    = (int)($counts['total_count'] ?? 0);

/* Lists */
$pendingRes = $conn->query("SELECT id, name, email, country FROM users WHERE role='agency' AND is_approved=0 ORDER BY id DESC");
$approvedRes = $conn->query("SELECT id, name, email, country FROM users WHERE role='agency' AND is_approved=1 ORDER BY id DESC");
$rejectedRes = $conn->query("SELECT id, name, email, country FROM users WHERE role='agency' AND is_approved=2 ORDER BY id DESC");
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Agency Requests</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:20px;
    }

    .page-card{
        background:#fff;
        border-radius:18px;
        box-shadow:0 8px 26px rgba(15,23,42,.06);
        border:1px solid rgba(148,163,184,.15);
        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;
        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:8px;
        padding:5px 10px;
        font-size:12px;
    }

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

    .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:11px;
        font-weight:700;
        text-transform:uppercase;
        letter-spacing:.04em;
        margin-bottom:8px;
    }

    .stat-value{
        font-size:18px;
        font-weight:800;
        color:#0f172a;
    }

    .tabs{
        display:flex;
        gap:10px;
        margin-bottom:18px;
        flex-wrap:wrap;
    }

    .tab{
        padding:10px 16px;
        border-radius:999px;
        cursor:pointer;
        background:#f1f5f9;
        font-weight:700;
        transition:0.2s;
        user-select:none;
    }

    .tab:hover{
        background:#e2e8f0;
    }

    .tab.active{
        background:#374155;
        color:#fff;
    }

    .count-badge{
        padding:2px 6px;
        border-radius:999px;
        margin-left:6px;
        font-size:10px;
        background:#fff;
        color:#000;
        display:inline-block;
        min-width:26px;
        text-align:center;
    }

    .section-title{
        font-size:18px;
        font-weight:800;
        color:#0f172a;
        display:flex;
        align-items:center;
        gap:8px;
        margin:0 0 14px;
    }

    .table-wrap{
        overflow:auto;
        border-radius:14px;
    }

    table{
        width:100%;
        border-collapse:collapse;
         padding:6px 12px;
    font-size:12px;
    }

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

    tbody td{
          padding:8px !important;
        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:6px 10px;
        border-radius:999px;
        font-size:12px;
        font-weight:700;
        text-transform:capitalize;
    }

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

    .actions{
        display:flex;
        justify-content:center;
        align-items:center;
        gap:6px;
         width:100%;
        flex-wrap:wrap;
        white-space:nowrap;
    }
    td:last-child{
    text-align:center;
    vertical-align:middle;
}


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

    .action-btn:hover{
        background:#f8fafc;
    }

    .approve-btn{
        background:#22c55e;
        color:#fff;
        border-color:#22c55e;
    }
    .approve-btn:hover{ background:#16a34a; color:#fff; }

    .reject-btn{
        background:#ef4444;
        color:#fff;
        border-color:#ef4444;
         display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:6px;
    padding:5px 10px !important;
    font-size:11px !important;
    border-radius:8px;
    text-decoration:none !important;
    }
    .reject-btn:hover{ background:#dc2626; color:#fff;text-decoration:none !important; }

    .empty{
        text-align:center;
        padding:30px 10px;
        color:#64748b;
    }

    .alert{
        padding:12px 14px;
        border-radius:12px;
        margin-bottom:16px;
        font-weight:600;
    }
    .alert.success{
        background:#dcfce7;
        color:#166534;
    }
    .alert.error{
        background:#fee2e2;
        color:#991b1b;
    }

    .tab-section{
        display:none;
    }

    @media(max-width: 900px){
        .main-content{
            margin-left:0;
            padding:14px;
        }
        .stat-grid{
            grid-template-columns:repeat(2,minmax(0,1fr));
        }
        .page-title{
            font-size:24px;
        }
    }

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

<script>
function showTab(name){
    document.querySelectorAll('.tab-section').forEach(s => s.style.display = 'none');
    const activeSection = document.getElementById(name);
    if (activeSection) activeSection.style.display = 'block';

    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
    const activeTab = document.getElementById('tab-' + name);
    if (activeTab) activeTab.classList.add('active');
}

function confirmReject(form){
    return confirm("Are you sure you want to reject this agency?");
}

window.addEventListener('DOMContentLoaded', () => {
    showTab('pending');
});
</script>
</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-user-check"></i>
                    Agency Requests
                </h1>
                <div class="page-subtitle">Approve or reject agency accounts and review request status.</div>
            </div>

            <div class="top-actions">
                <a href="agency_list.php" class="btn btn-light">
                    <i class="fa-solid fa-address-book"></i> All Agency
                </a>
                <a href="agency_reports.php" class="btn btn-dark">
                    <i class="fa-solid fa-file-lines"></i> Agency Reports
                </a>
            </div>
        </div>

        <?php if ($msg !== ""): ?>
            <div class="alert <?php echo $msgType === 'error' ? 'error' : 'success'; ?>">
                <?php echo e($msg); ?>
            </div>
        <?php endif; ?>

        <div class="stat-grid">
            <div class="stat-card">
                <div class="stat-label">Total Agency</div>
                <div class="stat-value"><?php echo $total_count; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Approved</div>
                <div class="stat-value"><?php echo $approved_count; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Pending</div>
                <div class="stat-value"><?php echo $pending_count; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Rejected</div>
                <div class="stat-value"><?php echo $rejected_count; ?></div>
            </div>
        </div>

        <div class="tabs" role="tablist" aria-label="Agency tabs">
            <div id="tab-pending" class="tab" onclick="showTab('pending')">
                Pending <span class="count-badge"><?php echo $pending_count; ?></span>
            </div>
            <div id="tab-approved" class="tab" onclick="showTab('approved')">
                Approved <span class="count-badge"><?php echo $approved_count; ?></span>
            </div>
            <div id="tab-rejected" class="tab" onclick="showTab('rejected')">
                Rejected <span class="count-badge"><?php echo $rejected_count; ?></span>
            </div>
        </div>

        <!-- Pending -->
        <div id="pending" class="tab-section">
            <div class="section-title">
                <i class="fa-solid fa-hourglass-half"></i>
                Pending Requests
            </div>

            <?php if (!$pendingRes || $pendingRes->num_rows == 0): ?>
                <div class="empty">No pending agency requests</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:80px;">ID</th>
                                <th>Agency Name</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>Status</th>
                                <th style="width:220px;">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $pendingRes->fetch_assoc()): ?>
                                <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 pending">Pending</span></td>
                                    <td>
                                        <div class="actions">
                                            <form method="post" style="display:inline;">
                                                <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <input type="hidden" name="action" value="approve">
                                                <button class="btn approve-btn" type="submit">
                                                    <i class="fa-solid fa-check"></i> Approve
                                                </button>
                                            </form>

                                            <form method="post" style="display:inline;" onsubmit="return confirmReject(this);">
                                                <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <input type="hidden" name="action" value="reject">
                                                <button class="btn reject-btn" type="submit">
                                                    <i class="fa-solid fa-xmark"></i> Reject
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Approved -->
        <div id="approved" class="tab-section">
            <div class="section-title">
                <i class="fa-solid fa-circle-check"></i>
                Approved Agencies
            </div>

            <?php if (!$approvedRes || $approvedRes->num_rows == 0): ?>
                <div class="empty">No approved agencies</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:80px;">ID</th>
                                <th>Agency Name</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $approvedRes->fetch_assoc()): ?>
                                <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 approved">Approved</span></td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Rejected -->
        <div id="rejected" class="tab-section">
            <div class="section-title">
                <i class="fa-solid fa-circle-xmark"></i>
                Rejected Agencies
            </div>

            <?php if (!$rejectedRes || $rejectedRes->num_rows == 0): ?>
                <div class="empty">No rejected agencies</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:80px;">ID</th>
                                <th>Agency Name</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $rejectedRes->fetch_assoc()): ?>
                                <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 rejected">Rejected</span></td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

    </div>
</div>

</body>
</html>