<?php
// public/admin/verifications.php
declare(strict_types=1);

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../config/auth.php";

require_admin();

$u = current_user();
$uid = (int)($u['id'] ?? 0);
$name = (string)($u['name'] ?? '');

$today = (new DateTime('today'))->format('Y-m-d');

// ---------- Filter Parameters ----------
$status_filter = $_GET['status'] ?? 'pending';
$district_id = $_GET['district_id'] ?? '';
$block_id = $_GET['block_id'] ?? '';
$gp_id = $_GET['gp_id'] ?? '';
$rep_id = $_GET['rep_id'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = trim($_GET['search'] ?? '');

// ---------- Helpers ----------
function fetchValue(PDO $pdo, string $sql, array $params = []): int {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return (int)($st->fetchColumn() ?? 0);
}
function fetchAll(PDO $pdo, string $sql, array $params = []): array {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC);
}

// ---------- Get Filter Data ----------
// Districts for filter
$districts = fetchAll($pdo, "SELECT id, name FROM districts ORDER BY name");

// Blocks based on district
$blocks = [];
if ($district_id) {
    $blocks = fetchAll($pdo, "SELECT id, name FROM blocks WHERE district_id = ? ORDER BY name", [$district_id]);
}

// GPs based on block
$gps = [];
if ($block_id) {
    $gps = fetchAll($pdo, "SELECT id, name FROM gps WHERE block_id = ? ORDER BY name", [$block_id]);
}

// Representatives for filter
$reps = fetchAll($pdo, "
    SELECT id, name, email 
    FROM users 
    WHERE role = 'REP' 
    ORDER BY name
");

// ---------- Build Verification Query ----------
$where = ["1=1"];
$params = [];

if ($status_filter !== 'all') {
    $where[] = "sv.status = ?";
    $params[] = strtoupper($status_filter);
}

if ($district_id) {
    $where[] = "d.id = ?";
    $params[] = $district_id;
}

if ($block_id) {
    $where[] = "b.id = ?";
    $params[] = $block_id;
}

if ($gp_id) {
    $where[] = "g.id = ?";
    $params[] = $gp_id;
}

if ($rep_id) {
    $where[] = "sv.representative_id = ?";
    $params[] = $rep_id;
}

if ($date_from) {
    $where[] = "DATE(sv.requested_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $where[] = "DATE(sv.requested_at) <= ?";
    $params[] = $date_to;
}

if ($search) {
    $where[] = "(s.name LIKE ? OR s.id LIKE ? OR u.name LIKE ?)";
    $search_term = "%{$search}%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = implode(" AND ", $where);

// Get total count for pagination
$total_count = fetchValue($pdo, "
    SELECT COUNT(*) 
    FROM school_verification sv
    JOIN schools s ON s.id = sv.school_id
    JOIN users u ON u.id = sv.representative_id
    LEFT JOIN gps g ON g.id = s.gp_id
    LEFT JOIN blocks b ON b.id = g.block_id
    LEFT JOIN districts d ON d.id = b.district_id
    WHERE {$where_clause}
", $params);

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;
$total_pages = ceil($total_count / $per_page);

// Get verifications
$verifications = fetchAll($pdo, "
    SELECT 
        sv.id,
        sv.school_id,
        sv.representative_id,
        sv.requested_at,
        sv.verified_at,
        sv.status,
        sv.admin_remark AS remarks,
        sv.verified_by,
        
        s.name AS school_name,
        s.address,
        s.category,
        s.contact_no,
        
        g.id AS gp_id,
        g.name AS gp_name,
        b.id AS block_id,
        b.name AS block_name,
        d.id AS district_id,
        d.name AS district_name,
        
        u.name AS rep_name,
        u.email AS rep_email,
        
        v.name AS verifier_name,
        
        -- Additional stats
        (
            SELECT COUNT(*) FROM visits v2 
            WHERE v2.school_id = sv.school_id
        ) AS total_visits,
        
        (
            SELECT COUNT(DISTINCT vsi.class) 
            FROM visits v3
            JOIN visit_student_interactions vsi ON vsi.visit_id = v3.id
            WHERE v3.school_id = sv.school_id
        ) AS classes_covered,
        
        (
            SELECT MAX(visit_date) 
            FROM visits v4 
            WHERE v4.school_id = sv.school_id
        ) AS last_visit_date
        
    FROM school_verification sv
    JOIN schools s ON s.id = sv.school_id
    JOIN users u ON u.id = sv.representative_id
    LEFT JOIN gps g ON g.id = s.gp_id
    LEFT JOIN blocks b ON b.id = g.block_id
    LEFT JOIN districts d ON d.id = b.district_id
    LEFT JOIN users v ON v.id = sv.verified_by
    WHERE {$where_clause}
    ORDER BY 
        CASE sv.status 
            WHEN 'PENDING' THEN 1 
            WHEN 'APPROVED' THEN 2 
            WHEN 'REJECTED' THEN 3 
        END,
        sv.requested_at DESC
    LIMIT ? OFFSET ?
", array_merge($params, [$per_page, $offset]));

// ---------- Summary Statistics ----------
$summary = [
    'pending' => fetchValue($pdo, "SELECT COUNT(*) FROM school_verification WHERE status = 'PENDING'"),
    'approved' => fetchValue($pdo, "SELECT COUNT(*) FROM school_verification WHERE status = 'APPROVED'"),
    'rejected' => fetchValue($pdo, "SELECT COUNT(*) FROM school_verification WHERE status = 'REJECTED'"),
    'total' => fetchValue($pdo, "SELECT COUNT(*) FROM school_verification"),
    
    'pending_today' => fetchValue($pdo, "
        SELECT COUNT(*) FROM school_verification 
        WHERE status = 'PENDING' AND DATE(requested_at) = ?
    ", [$today]),
    
    'avg_response_days' => fetchValue($pdo, "
        SELECT ROUND(AVG(DATEDIFF(verified_at, requested_at)), 1)
        FROM school_verification 
        WHERE verified_at IS NOT NULL
    "),
    
    'by_rep' => fetchAll($pdo, "
        SELECT 
            u.name,
            COUNT(*) as total,
            SUM(CASE WHEN sv.status = 'PENDING' THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN sv.status = 'APPROVED' THEN 1 ELSE 0 END) as approved
        FROM school_verification sv
        JOIN users u ON u.id = sv.representative_id
        GROUP BY sv.representative_id
        ORDER BY pending DESC, total DESC
        LIMIT 10
    "),
];

$page_title = "School Verifications";
require_once __DIR__ . "/../partials/header.php";
?>

<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
:root {
    --primary: #4361ee;
    --success: #06d6a0;
    --warning: #ffb703;
    --danger: #ef476f;
    --dark: #073b4c;
    --info: #17a2b8;
    --purple: #6f42c1;
    --orange: #fd7e14;
    --light: #f8f9fa;
    --gray: #6c757d;
}

body {
    background: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

/* Admin Container */
.admin-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
}

/* Header */
.page-header {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
    border-radius: 24px;
    padding: 30px;
    margin-bottom: 30px;
    box-shadow: 0 10px 30px rgba(67, 97, 238, 0.2);
}

.page-header h1 {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-header .subtitle {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    opacity: 0.9;
    font-size: 1rem;
}

/* Summary Cards */
.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.summary-card {
    background: white;
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.03);
    border: 1px solid #e9ecef;
    transition: all 0.3s;
    position: relative;
    overflow: hidden;
}

.summary-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 30px rgba(0,0,0,0.08);
}

.summary-card.pending { border-left: 4px solid var(--warning); }
.summary-card.approved { border-left: 4px solid var(--success); }
.summary-card.rejected { border-left: 4px solid var(--danger); }

.summary-value {
    font-size: 2.2rem;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 4px;
}

.summary-label {
    color: var(--gray);
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 6px;
}

.summary-trend {
    margin-top: 12px;
    font-size: 0.8rem;
    padding: 4px 8px;
    background: var(--light);
    border-radius: 20px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

/* Filter Section */
.filter-section {
    background: white;
    border-radius: 20px;
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #e9ecef;
}

.filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.filter-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--dark);
}

.filter-title i {
    color: var(--primary);
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 15px;
}

.filter-item {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.filter-item label {
    font-size: 0.8rem;
    font-weight: 600;
    color: var(--gray);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.filter-item select,
.filter-item input {
    padding: 10px 12px;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    font-size: 0.9rem;
    background: white;
}

.filter-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

.btn-filter {
    padding: 12px 24px;
    border: none;
    border-radius: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-filter.primary {
    background: var(--primary);
    color: white;
}

.btn-filter.primary:hover {
    background: #3651d4;
}

.btn-filter.secondary {
    background: var(--light);
    color: var(--dark);
    border: 1px solid #e9ecef;
}

.btn-filter.secondary:hover {
    background: #e9ecef;
}

/* Status Tabs */
.status-tabs {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.status-tab {
    padding: 10px 20px;
    border-radius: 30px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    background: white;
    border: 1px solid #e9ecef;
    color: var(--gray);
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.status-tab:hover {
    background: var(--light);
}

.status-tab.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.status-tab.pending.active { background: var(--warning); border-color: var(--warning); }
.status-tab.approved.active { background: var(--success); border-color: var(--success); }
.status-tab.rejected.active { background: var(--danger); border-color: var(--danger); }

/* Table Styles */
.table-container {
    background: white;
    border-radius: 20px;
    padding: 20px;
    border: 1px solid #e9ecef;
    overflow: auto;
}

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

.table th {
    text-align: left;
    padding: 16px 12px;
    background: var(--light);
    color: var(--gray);
    font-weight: 600;
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid #e9ecef;
}

.table td {
    padding: 16px 12px;
    border-bottom: 1px solid #e9ecef;
    vertical-align: middle;
}

.table tr:hover td {
    background: rgba(67, 97, 238, 0.02);
}

/* Status Badges */
.status-badge {
    padding: 6px 12px;
    border-radius: 30px;
    font-size: 0.75rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.badge-pending {
    background: rgba(255, 183, 3, 0.1);
    color: var(--warning);
}

.badge-approved {
    background: rgba(6, 214, 160, 0.1);
    color: var(--success);
}

.badge-rejected {
    background: rgba(239, 71, 111, 0.1);
    color: var(--danger);
}

/* School Info */
.school-info {
    display: flex;
    flex-direction: column;
}

.school-name {
    font-weight: 600;
    color: var(--dark);
    text-decoration: none;
}

.school-name:hover {
    color: var(--primary);
}

.school-location {
    font-size: 0.8rem;
    color: var(--gray);
}

/* Rep Info */
.rep-info {
    display: flex;
    flex-direction: column;
}

.rep-name {
    font-weight: 500;
    color: var(--dark);
}

.rep-email {
    font-size: 0.75rem;
    color: var(--gray);
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.btn-action {
    padding: 8px 12px;
    border: none;
    border-radius: 8px;
    font-size: 0.8rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.btn-view {
    background: var(--light);
    color: var(--gray);
}

.btn-view:hover {
    background: #e9ecef;
}

.btn-approve {
    background: var(--success);
    color: white;
}

.btn-approve:hover {
    background: #05b588;
}

.btn-reject {
    background: var(--danger);
    color: white;
}

.btn-reject:hover {
    background: #d43f62;
}

/* Pagination */
.pagination {
    display: flex;
    justify-content: center;
    gap: 8px;
    margin-top: 20px;
    flex-wrap: wrap;
}

.page-item {
    list-style: none;
}

.page-link {
    padding: 8px 16px;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    color: var(--dark);
    text-decoration: none;
    transition: all 0.2s;
    display: block;
}

.page-link:hover {
    background: var(--light);
}

.page-item.active .page-link {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.page-item.disabled .page-link {
    opacity: 0.5;
    pointer-events: none;
}

/* Quick Stats */
.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin-top: 20px;
}

.stat-block {
    background: var(--light);
    border-radius: 12px;
    padding: 15px;
    text-align: center;
}

.stat-block h4 {
    font-size: 1.2rem;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 5px;
}

.stat-block p {
    font-size: 0.8rem;
    color: var(--gray);
    margin: 0;
}

/* Modal */
.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
    align-items: center;
    justify-content: center;
}

.modal.show {
    display: flex;
}

.modal-content {
    background: white;
    border-radius: 24px;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow: auto;
}

.modal-header {
    padding: 20px;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-title {
    font-size: 1.3rem;
    font-weight: 600;
    color: var(--dark);
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: var(--gray);
}

.modal-body {
    padding: 20px;
}

.modal-footer {
    padding: 20px;
    border-top: 1px solid #e9ecef;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .admin-container {
        padding: 12px;
    }
    
    .page-header {
        padding: 20px;
    }
    
    .page-header h1 {
        font-size: 1.5rem;
    }
    
    .summary-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }
    
    .summary-value {
        font-size: 1.8rem;
    }
    
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .status-tabs {
        overflow-x: auto;
        padding-bottom: 5px;
        flex-wrap: nowrap;
    }
    
    .status-tab {
        white-space: nowrap;
    }
    
    .table-container {
        padding: 12px;
        overflow-x: auto;
    }
    
    .table {
        min-width: 1000px;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .stats-row {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="admin-container">
    <!-- Page Header -->
    <div class="page-header">
        <h1>
            <i class="bi bi-check2-circle"></i>
            School Verifications
        </h1>
        <div class="subtitle">
            <span><i class="bi bi-calendar"></i> <?= date('l, d F Y') ?></span>
            <span><i class="bi bi-hourglass-split"></i> <?= $summary['pending'] ?> Pending</span>
            <span><i class="bi bi-clock-history"></i> Avg. Response: <?= $summary['avg_response_days'] ?? 0 ?> days</span>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="summary-grid">
        <div class="summary-card pending">
            <div class="summary-value"><?= $summary['pending'] ?></div>
            <div class="summary-label">
                <i class="bi bi-hourglass-split"></i>
                Pending Verifications
            </div>
            <?php if ($summary['pending_today'] > 0): ?>
            <div class="summary-trend">
                <i class="bi bi-calendar"></i> <?= $summary['pending_today'] ?> today
            </div>
            <?php endif; ?>
        </div>

        <div class="summary-card approved">
            <div class="summary-value"><?= $summary['approved'] ?></div>
            <div class="summary-label">
                <i class="bi bi-check-circle"></i>
                Approved
            </div>
        </div>

        <div class="summary-card rejected">
            <div class="summary-value"><?= $summary['rejected'] ?></div>
            <div class="summary-label">
                <i class="bi bi-x-circle"></i>
                Rejected
            </div>
        </div>

        <div class="summary-card">
            <div class="summary-value"><?= $summary['total'] ?></div>
            <div class="summary-label">
                <i class="bi bi-grid"></i>
                Total Requests
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter-section">
        <div class="filter-header">
            <div class="filter-title">
                <i class="bi bi-funnel"></i>
                Filter Verifications
            </div>
            <div>
                <span class="badge bg-light"><?= $total_count ?> records found</span>
            </div>
        </div>

        <form method="get" id="filterForm">
            <div class="filter-grid">
                <div class="filter-item">
                    <label>Status</label>
                    <select name="status" class="form-select">
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>Approved</option>
                        <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                    </select>
                </div>

                <div class="filter-item">
                    <label>District</label>
                    <select name="district_id" id="filterDistrict">
                        <option value="">All Districts</option>
                        <?php foreach ($districts as $d): ?>
                            <option value="<?= $d['id'] ?>" <?= $district_id == $d['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($d['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>Block</label>
                    <select name="block_id" id="filterBlock" <?= !$district_id ? 'disabled' : '' ?>>
                        <option value="">All Blocks</option>
                        <?php foreach ($blocks as $b): ?>
                            <option value="<?= $b['id'] ?>" <?= $block_id == $b['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($b['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>GP</label>
                    <select name="gp_id" id="filterGP" <?= !$block_id ? 'disabled' : '' ?>>
                        <option value="">All GPs</option>
                        <?php foreach ($gps as $g): ?>
                            <option value="<?= $g['id'] ?>" <?= $gp_id == $g['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($g['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>Representative</label>
                    <select name="rep_id">
                        <option value="">All Reps</option>
                        <?php foreach ($reps as $rep): ?>
                            <option value="<?= $rep['id'] ?>" <?= $rep_id == $rep['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($rep['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-item">
                    <label>From Date</label>
                    <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>">
                </div>

                <div class="filter-item">
                    <label>To Date</label>
                    <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>">
                </div>

                <div class="filter-item">
                    <label>Search</label>
                    <input type="text" name="search" placeholder="School name, ID, Rep..." value="<?= htmlspecialchars($search) ?>">
                </div>
            </div>

            <div class="filter-actions">
                <button type="submit" class="btn-filter primary">
                    <i class="bi bi-search"></i> Apply Filters
                </button>
                <a href="verifications.php" class="btn-filter secondary">
                    <i class="bi bi-x-circle"></i> Clear
                </a>
            </div>
        </form>
    </div>

    <!-- Status Tabs -->
    <div class="status-tabs">
        <a href="?status=pending<?= http_build_query(array_filter(['district_id' => $district_id, 'block_id' => $block_id, 'gp_id' => $gp_id, 'rep_id' => $rep_id])) ?>" 
           class="status-tab pending <?= $status_filter === 'pending' ? 'active' : '' ?>">
            <i class="bi bi-hourglass-split"></i> Pending (<?= $summary['pending'] ?>)
        </a>
        <a href="?status=approved<?= http_build_query(array_filter(['district_id' => $district_id, 'block_id' => $block_id, 'gp_id' => $gp_id, 'rep_id' => $rep_id])) ?>" 
           class="status-tab approved <?= $status_filter === 'approved' ? 'active' : '' ?>">
            <i class="bi bi-check-circle"></i> Approved (<?= $summary['approved'] ?>)
        </a>
        <a href="?status=rejected<?= http_build_query(array_filter(['district_id' => $district_id, 'block_id' => $block_id, 'gp_id' => $gp_id, 'rep_id' => $rep_id])) ?>" 
           class="status-tab rejected <?= $status_filter === 'rejected' ? 'active' : '' ?>">
            <i class="bi bi-x-circle"></i> Rejected (<?= $summary['rejected'] ?>)
        </a>
        <a href="?status=all<?= http_build_query(array_filter(['district_id' => $district_id, 'block_id' => $block_id, 'gp_id' => $gp_id, 'rep_id' => $rep_id])) ?>" 
           class="status-tab <?= $status_filter === 'all' ? 'active' : '' ?>">
            <i class="bi bi-grid"></i> All (<?= $summary['total'] ?>)
        </a>
    </div>

    <!-- Verifications Table -->
    <div class="table-container">
        <?php if (empty($verifications)): ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox" style="font-size: 3rem; color: var(--gray);"></i>
                <h5 class="mt-3">No verifications found</h5>
                <p class="text-muted">Try adjusting your filters</p>
            </div>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Requested</th>
                        <th>School</th>
                        <th>Location</th>
                        <th>Representative</th>
                        <th>Status</th>
                        <th>Progress</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($verifications as $v): ?>
                    <tr>
                        <td class="text-nowrap">
                            <div><?= date('d M Y', strtotime($v['requested_at'])) ?></div>
                            <small class="text-muted"><?= date('h:i A', strtotime($v['requested_at'])) ?></small>
                        </td>
                        <td>
                            <div class="school-info">
                                <strong class="school-name"><?= htmlspecialchars($v['school_name'] ?? '') ?></strong>
                                <small class="school-location">
                                    <i class="bi bi-tag"></i> <?= htmlspecialchars($v['category'] ?? 'N/A') ?>
                                </small>
                                <?php if ($v['contact_no']): ?>
                                    <small class="school-location">
                                        <i class="bi bi-telephone"></i> <?= htmlspecialchars($v['contact_no']) ?>
                                    </small>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <div><?= htmlspecialchars($v['gp_name'] ?? '') ?></div>
                            <small class="text-muted"><?= htmlspecialchars($v['block_name'] ?? '') ?>, <?= htmlspecialchars($v['district_name'] ?? '') ?></small>
                        </td>
                        <td>
                            <div class="rep-info">
                                <span class="rep-name"><?= htmlspecialchars($v['rep_name'] ?? '') ?></span>
                                <small class="rep-email"><?= htmlspecialchars($v['rep_email'] ?? '') ?></small>
                            </div>
                        </td>
                        <td>
                            <?php if ($v['status'] === 'PENDING'): ?>
                                <span class="status-badge badge-pending">
                                    <i class="bi bi-hourglass-split"></i> Pending
                                </span>
                                <?php if ($v['verified_by']): ?>
                                    <div class="mt-1">
                                        <small class="text-muted">Assigned to <?= htmlspecialchars($v['verifier_name'] ?? 'Admin') ?></small>
                                    </div>
                                <?php endif; ?>
                            <?php elseif ($v['status'] === 'APPROVED'): ?>
                                <span class="status-badge badge-approved">
                                    <i class="bi bi-check-circle"></i> Approved
                                </span>
                                <?php if ($v['verified_at']): ?>
                                    <div class="mt-1">
                                        <small class="text-muted">by <?= htmlspecialchars($v['verifier_name'] ?? 'Admin') ?></small>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="status-badge badge-rejected">
                                    <i class="bi bi-x-circle"></i> Rejected
                                </span>
                                <?php if ($v['verified_at']): ?>
                                    <div class="mt-1">
                                        <small class="text-muted">by <?= htmlspecialchars($v['verifier_name'] ?? 'Admin') ?></small>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= $v['classes_covered'] ?? 0 ?>/12 classes</div>
                            <small class="text-muted"><?= $v['total_visits'] ?? 0 ?> visits</small>
                            <?php if ($v['last_visit_date']): ?>
                                <div>
                                    <small class="text-muted">Last: <?= date('d M', strtotime($v['last_visit_date'])) ?></small>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="verification_detail.php?id=<?= $v['id'] ?>" class="btn-action btn-view">
                                    <i class="bi bi-eye"></i> View
                                </a>
                                
                                <?php if ($v['status'] === 'PENDING'): ?>
                                    <button onclick="openVerifyModal(<?= $v['id'] ?>, '<?= htmlspecialchars($v['school_name']) ?>', 'approve')" class="btn-action btn-approve">
                                        <i class="bi bi-check-lg"></i> Approve
                                    </button>
                                    <button onclick="openVerifyModal(<?= $v['id'] ?>, '<?= htmlspecialchars($v['school_name']) ?>', 'reject')" class="btn-action btn-reject">
                                        <i class="bi bi-x-lg"></i> Reject
                                    </button>
                                <?php endif; ?>
                            </div>
                            
                            <?php if ($v['remarks']): ?>
                                <div class="mt-2">
                                    <small class="text-muted">
                                        <i class="bi bi-chat"></i> <?= htmlspecialchars(substr($v['remarks'], 0, 50)) ?>...
                                    </small>
                                </div>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav>
                <ul class="pagination">
                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">Previous</a>
                    </li>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <?php if ($i >= $page - 2 && $i <= $page + 2): ?>
                            <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
                            </li>
                        <?php endif; ?>
                    <?php endfor; ?>
                    
                    <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                        <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">Next</a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Statistics by Representative -->
    <?php if (!empty($summary['by_rep'])): ?>
    <div class="table-container mt-4">
        <h5 class="mb-3">
            <i class="bi bi-people"></i>
            Pending Verifications by Representative
        </h5>
        <div class="stats-row">
            <?php foreach ($summary['by_rep'] as $rep): ?>
            <div class="stat-block">
                <h4><?= htmlspecialchars(explode(' ', $rep['name'])[0]) ?></h4>
                <p>
                    <span class="text-warning"><?= $rep['pending'] ?> pending</span> • 
                    <span class="text-success"><?= $rep['approved'] ?> approved</span> • 
                    <?= $rep['total'] ?> total
                </p>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Verification Modal -->
<div id="verifyModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="modalTitle">Verify School</h5>
            <button type="button" class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        <form id="verifyForm" method="POST" action="process_verification.php">
            <div class="modal-body">
                <input type="hidden" name="verification_id" id="verification_id">
                <input type="hidden" name="action" id="action">
                <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                
                <div class="mb-3">
                    <p>
                        <strong id="schoolName"></strong>
                    </p>
                    <p class="text-muted" id="actionText"></p>
                </div>
                
                <div class="mb-3">
                    <label for="remarks" class="form-label">Remarks (Optional)</label>
                    <textarea class="form-control" id="remarks" name="remarks" rows="3" placeholder="Add any remarks or notes..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-filter secondary" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn-filter primary" id="modalSubmitBtn">Confirm</button>
            </div>
        </form>
    </div>
</div>

<script>
// Filter dependency chain
document.getElementById('filterDistrict')?.addEventListener('change', function() {
    const blockSelect = document.getElementById('filterBlock');
    const gpSelect = document.getElementById('filterGP');
    
    if (this.value) {
        // Enable block select and load blocks via AJAX
        blockSelect.disabled = false;
        gpSelect.disabled = true;
        gpSelect.innerHTML = '<option value="">All GPs</option>';
        
        fetch(`get_blocks.php?district_id=${this.value}`)
            .then(response => response.json())
            .then(data => {
                blockSelect.innerHTML = '<option value="">All Blocks</option>';
                data.forEach(block => {
                    blockSelect.innerHTML += `<option value="${block.id}">${block.name}</option>`;
                });
            });
    } else {
        blockSelect.disabled = true;
        gpSelect.disabled = true;
        blockSelect.innerHTML = '<option value="">All Blocks</option>';
        gpSelect.innerHTML = '<option value="">All GPs</option>';
    }
});

document.getElementById('filterBlock')?.addEventListener('change', function() {
    const gpSelect = document.getElementById('filterGP');
    
    if (this.value) {
        gpSelect.disabled = false;
        
        fetch(`get_gps.php?block_id=${this.value}`)
            .then(response => response.json())
            .then(data => {
                gpSelect.innerHTML = '<option value="">All GPs</option>';
                data.forEach(gp => {
                    gpSelect.innerHTML += `<option value="${gp.id}">${gp.name}</option>`;
                });
            });
    } else {
        gpSelect.disabled = true;
        gpSelect.innerHTML = '<option value="">All GPs</option>';
    }
});

// Modal functions
function openVerifyModal(id, schoolName, action) {
    document.getElementById('verifyModal').classList.add('show');
    document.getElementById('verification_id').value = id;
    document.getElementById('action').value = action;
    document.getElementById('schoolName').textContent = schoolName;
    
    if (action === 'approve') {
        document.getElementById('modalTitle').textContent = 'Approve Verification';
        document.getElementById('actionText').textContent = 'Are you sure you want to approve this school verification?';
        document.getElementById('modalSubmitBtn').classList.add('btn-approve');
        document.getElementById('modalSubmitBtn').classList.remove('btn-reject');
    } else {
        document.getElementById('modalTitle').textContent = 'Reject Verification';
        document.getElementById('actionText').textContent = 'Are you sure you want to reject this school verification?';
        document.getElementById('modalSubmitBtn').classList.add('btn-reject');
        document.getElementById('modalSubmitBtn').classList.remove('btn-approve');
    }
}

function closeModal() {
    document.getElementById('verifyModal').classList.remove('show');
    document.getElementById('remarks').value = '';
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('verifyModal');
    if (event.target === modal) {
        closeModal();
    }
}

// Auto-submit filters on change
document.querySelectorAll('#filterForm select, #filterForm input').forEach(element => {
    element.addEventListener('change', function() {
        document.getElementById('filterForm').submit();
    });
});

// Debounced search
let searchTimeout;
document.querySelector('input[name="search"]').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        document.getElementById('filterForm').submit();
    }, 500);
});
</script>

<?php
// Create helper files for AJAX endpoints
if (!file_exists(__DIR__ . '/get_blocks.php')) {
    file_put_contents(__DIR__ . '/get_blocks.php', '<?php
require_once __DIR__ . "/../../config/db.php";
header("Content-Type: application/json");

$district_id = $_GET["district_id"] ?? "";
if (!$district_id) {
    echo json_encode([]);
    exit;
}

$stmt = $pdo->prepare("SELECT id, name FROM blocks WHERE district_id = ? ORDER BY name");
$stmt->execute([$district_id]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
');
}

if (!file_exists(__DIR__ . '/get_gps.php')) {
    file_put_contents(__DIR__ . '/get_gps.php', '<?php
require_once __DIR__ . "/../../config/db.php";
header("Content-Type: application/json");

$block_id = $_GET["block_id"] ?? "";
if (!$block_id) {
    echo json_encode([]);
    exit;
}

$stmt = $pdo->prepare("SELECT id, name FROM gps WHERE block_id = ? ORDER BY name");
$stmt->execute([$block_id]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
');
}

if (!file_exists(__DIR__ . '/process_verification.php')) {
    file_put_contents(__DIR__ . '/process_verification.php', '<?php
declare(strict_types=1);

require_once __DIR__ . "/../../config/db.php";
require_once __DIR__ . "/../../config/auth.php";

require_admin();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: verifications.php");
    exit;
}

$verification_id = (int)($_POST["verification_id"] ?? 0);
$action = $_POST["action"] ?? "";
$remarks = trim($_POST["remarks"] ?? "");
$csrf_token = $_POST["csrf_token"] ?? "";

// Verify CSRF token
if (!verify_csrf($csrf_token)) {
    $_SESSION["error"] = "Invalid security token";
    header("Location: verifications.php");
    exit;
}

if (!$verification_id || !in_array($action, ["approve", "reject"])) {
    $_SESSION["error"] = "Invalid request";
    header("Location: verifications.php");
    exit;
}

$status = $action === "approve" ? "APPROVED" : "REJECTED";
$admin_id = (int)($_SESSION["user_id"] ?? 0);

try {
    $stmt = $pdo->prepare("
        UPDATE school_verification 
        SET status = ?, 
            verified_at = NOW(), 
            verified_by = ?, 
            remarks = CONCAT(IFNULL(remarks, ""), ?)
        WHERE id = ? AND status = "PENDING"
    ");
    
    $remarks_text = $remarks ? "\nAdmin remarks: " . $remarks : "";
    $stmt->execute([$status, $admin_id, $remarks_text, $verification_id]);
    
    if ($stmt->rowCount() > 0) {
        $_SESSION["success"] = "Verification " . strtolower($status) . " successfully";
        
        // If approved, maybe update school status or send notification
        if ($status === "APPROVED") {
            // Get school_id for this verification
            $school_stmt = $pdo->prepare("SELECT school_id FROM school_verification WHERE id = ?");
            $school_stmt->execute([$verification_id]);
            $school_id = $school_stmt->fetchColumn();
            
            // You can add additional logic here when school is verified
            // e.g., update school status, send notification to rep, etc.
        }
    } else {
        $_SESSION["error"] = "Verification request not found or already processed";
    }
} catch (PDOException $e) {
    $_SESSION["error"] = "Database error occurred";
    error_log($e->getMessage());
}

header("Location: verifications.php");
exit;
');
}

require_once __DIR__ . "/../partials/footer.php"; 
?>