<?php
declare(strict_types=1);

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

require_rep();

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

const FIX_COLLATE = "utf8mb4_unicode_ci";

function fetchAll(PDO $pdo, string $sql, array $params = []): array {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC);
}

function coll(string $expr): string {
    return $expr . " COLLATE " . FIX_COLLATE;
}

// NOTE: IDs are treated as strings here (safe for VARCHAR/UUID/CHAR).
$district_id = strtoupper(trim((string)($_GET['district_id'] ?? '')));
$block_id    = strtoupper(trim((string)($_GET['block_id'] ?? '')));
$gp_id       = strtoupper(trim((string)($_GET['gp_id'] ?? '')));
$school_id   = strtoupper(trim((string)($_GET['school_id'] ?? '')));
$status_filter = (string)($_GET['status'] ?? 'all');
$q           = trim((string)($_GET['q'] ?? '')) ;

// District list only those where rep has assignments
$districts = fetchAll($pdo, "
  SELECT DISTINCT d.id, d.name
  FROM gp_assignments a
  JOIN gps g ON g.id = a.gp_id
  JOIN blocks b ON b.id = g.block_id
  LEFT JOIN districts d ON d.id = b.district_id
  WHERE a.user_id = ? AND a.status = 'ACTIVE'
  ORDER BY d.name ASC
", [$uid]);

$blocks = [];
if ($district_id !== '') {
    $blocks = fetchAll($pdo, "
      SELECT DISTINCT b.id, b.name
      FROM gp_assignments a
      JOIN gps g ON g.id = a.gp_id
      JOIN blocks b ON b.id = g.block_id
      WHERE a.user_id = ? AND a.status = 'ACTIVE'
        AND b.district_id = ?
      ORDER BY b.name ASC
    ", [$uid, $district_id]);
}

$gps = [];
if ($block_id !== '') {
    $gps = fetchAll($pdo, "
      SELECT DISTINCT g.id, g.name
      FROM gp_assignments a
      JOIN gps g ON g.id = a.gp_id
      WHERE a.user_id = ? AND a.status = 'ACTIVE'
        AND g.block_id = ?
      ORDER BY g.name ASC
    ", [$uid, $block_id]);
}

// Get schools for dropdown (filtered by current selections)
$schools_dropdown = [];
if ($gp_id !== '' || $block_id !== '' || $district_id !== '') {
    $school_where = [];
    $school_params = [$uid];
    
    if ($district_id !== '') {
        $school_where[] = "b.district_id = ?";
        $school_params[] = $district_id;
    }
    if ($block_id !== '') {
        $school_where[] = "b.id = ?";
        $school_params[] = $block_id;
    }
    if ($gp_id !== '') {
        $school_where[] = "g.id = ?";
        $school_params[] = $gp_id;
    }
    
    $school_where_sql = !empty($school_where) ? "AND " . implode(" AND ", $school_where) : "";
    
    $schools_dropdown = fetchAll($pdo, "
      SELECT DISTINCT s.id, s.name
      FROM gp_assignments a
      JOIN gps g ON g.id = a.gp_id
      JOIN blocks b ON b.id = g.block_id
      JOIN schools s ON s.gp_id = g.id
      WHERE a.user_id = ? AND a.status = 'ACTIVE'
      {$school_where_sql}
      ORDER BY s.name ASC
      LIMIT 500
    ", $school_params);
}

// Build WHERE clause for main schools query
$where = "a.user_id = ? AND a.status = 'ACTIVE'";
$params = [$uid];

if ($district_id !== '') {
    $where .= " AND b.district_id = ?";
    $params[] = $district_id;
}
if ($block_id !== '') {
    $where .= " AND b.id = ?";
    $params[] = $block_id;
}
if ($gp_id !== '') {
    $where .= " AND g.id = ?";
    $params[] = $gp_id;
}
if ($school_id !== '') {
    $where .= " AND s.id = ?";
    $params[] = $school_id;
}
if ($q !== '') {
    // Only use COLLATE for string name searches, not for ID
    $where .= " AND (" . coll("s.name") . " LIKE ? OR s.id LIKE ?)";
    $params[] = "%{$q}%";
    $params[] = "%{$q}%";
}

// For subqueries comparing school_id with schools.id - use direct comparison without COLLATE
$school_eq = "svX.school_id = s.id";

$rows = fetchAll($pdo, "
  SELECT
    s.id AS school_id,
    s.name AS school_name,
    s.address,
    s.category,
    s.contact_no,
    s.whatsapp_no,
    g.id AS gp_id,
    g.name AS gp_name,
    b.id AS block_id,
    b.name AS block_name,
    d.name AS district_name,
    d.id AS district_id,

    -- visited?
    CASE
      WHEN EXISTS (
        SELECT 1 FROM school_visits sv
        WHERE sv.school_id = s.id
          AND sv.representative_id = ?
      ) THEN 1 ELSE 0
    END AS visited,

    -- last visit date
    (
      SELECT MAX(sv2.visited_at)
      FROM school_visits sv2
      WHERE sv2.school_id = s.id
        AND sv2.representative_id = ?
    ) AS last_visit_date,

    -- last permission status
    (
      SELECT sv3.permission_status
      FROM school_visits sv3
      WHERE sv3.school_id = s.id
        AND sv3.representative_id = ?
      ORDER BY sv3.visited_at DESC
      LIMIT 1
    ) AS last_permission_status,

    -- total visits
    (
      SELECT COUNT(*)
      FROM school_visits sv4
      WHERE sv4.school_id = s.id
        AND sv4.representative_id = ?
    ) AS total_visits,

    -- completed? (distinct classes >= 12)
    CASE
      WHEN (
        SELECT COUNT(DISTINCT vsi.class)
        FROM school_visits sv5
        JOIN visit_student_interactions vsi ON vsi.visit_id = sv5.id
        WHERE sv5.school_id = s.id
          AND sv5.representative_id = ?
      ) >= 12 THEN 1 ELSE 0
    END AS is_completed,

    -- waiting verification?
    CASE
      WHEN EXISTS (
        SELECT 1 FROM school_verification sv6
        WHERE sv6.school_id = s.id
          AND sv6.representative_id = ?
          AND sv6.status = 'PENDING'
      ) THEN 1 ELSE 0
    END AS waiting_verification,
    
    -- verification status
    (
      SELECT status 
      FROM school_verification sv7 
      WHERE sv7.school_id = s.id
        AND sv7.representative_id = ?
      ORDER BY sv7.id DESC 
      LIMIT 1
    ) AS verification_status

  FROM gp_assignments a
  JOIN gps g ON g.id = a.gp_id
  JOIN blocks b ON b.id = g.block_id
  LEFT JOIN districts d ON d.id = b.district_id
  JOIN schools s ON s.gp_id = g.id

  WHERE {$where}

  ORDER BY waiting_verification DESC, visited ASC, d.name ASC, b.name ASC, g.name ASC, s.name ASC
  LIMIT 1000
", array_merge([$uid, $uid, $uid, $uid, $uid, $uid, $uid], $params));

// ... rest of the code remains the same ...

// Always keep the full list for filtering
$all_rows = $rows;
if ($status_filter !== 'all') {
    $rows = array_filter($all_rows, function($r) use ($status_filter) {
        switch($status_filter) {
            case 'visited': return (int)$r['visited'] === 1 && !(int)$r['is_completed'] && !(int)$r['waiting_verification'];
            case 'not_visited': return (int)$r['visited'] === 0;
            case 'completed': return (int)$r['is_completed'] === 1 && !(int)$r['waiting_verification'];
            case 'waiting': return (int)$r['waiting_verification'] === 1;
            case 'verified': return $r['verification_status'] === 'APPROVED';
            case 'rejected': return $r['verification_status'] === 'REJECTED';
            default: return true;
        }
    });
}

$page_title = "My Assigned Schools";
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;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

/* App Container - Mobile First */
.app-container {
    max-width: 480px;
    margin: 0 auto;
    background: white;
    min-height: 100vh;
    position: relative;
    box-shadow: 0 0 20px rgba(0,0,0,0.05);
}

/* App Header */
.app-header {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
    padding: 20px;
    position: sticky;
    top: 0;
    z-index: 100;
    backdrop-filter: blur(10px);
}

.app-header h1 {
    font-size: 1.5rem;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.app-header h1 i {
    font-size: 1.8rem;
}

.app-header .subtitle {
    font-size: 0.8rem;
    opacity: 0.9;
    margin-top: 5px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

/* Stats Scroll */
.stats-scroll {
    overflow-x: auto;
    padding: 15px;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
    background: white;
    border-bottom: 1px solid #e9ecef;
}

.stats-scroll::-webkit-scrollbar {
    display: none;
}

.stats-row {
    display: flex;
    gap: 12px;
    min-width: min-content;
}

.stat-chip {
    background: var(--light);
    border-radius: 30px;
    padding: 10px 18px;
    display: flex;
    align-items: center;
    gap: 8px;
    border: 1px solid #e9ecef;
    transition: all 0.2s;
    cursor: pointer;
    white-space: nowrap;
}

.stat-chip.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.stat-chip i {
    font-size: 1.1rem;
}

.stat-chip .count {
    font-weight: 600;
    margin-left: 4px;
}

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

.filter-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    color: var(--dark);
    font-weight: 500;
    font-size: 0.9rem;
}

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

.filter-grid {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.filter-row {
    display: flex;
    gap: 10px;
    align-items: center;
}

.filter-row .form-select,
.filter-row .form-control {
    flex: 1;
    padding: 12px;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    font-size: 0.9rem;
    background: white;
}

.filter-actions {
    display: flex;
    gap: 8px;
    margin-top: 5px;
}

.btn-filter {
    flex: 1;
    padding: 12px;
    border: none;
    border-radius: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    cursor: pointer;
    transition: all 0.2s;
}

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

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

.btn-filter:active {
    transform: scale(0.98);
}

/* School Cards Grid */
.schools-grid {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 15px;
}

.school-card {
    background: white;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.03);
    border: 1px solid #e9ecef;
    transition: all 0.2s;
    position: relative;
}

.school-card:active {
    transform: scale(0.98);
}

/* Status-based card styles */
.school-card.visited { border-left: 4px solid var(--success); }
.school-card.not-visited { border-left: 4px solid var(--warning); }
.school-card.completed { border-left: 4px solid var(--purple); }
.school-card.waiting { 
    border-left: 4px solid var(--info);
    background: #f0f9ff;
}
.school-card.verified { border-left: 4px solid var(--success); }
.school-card.rejected { border-left: 4px solid var(--danger); }

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

.school-badge {
    padding: 6px 12px;
    border-radius: 30px;
    font-size: 0.7rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.badge-success { background: rgba(6, 214, 160, 0.1); color: var(--success); }
.badge-warning { background: rgba(255, 183, 3, 0.1); color: var(--warning); }
.badge-info { background: rgba(23, 162, 184, 0.1); color: var(--info); }
.badge-purple { background: rgba(111, 66, 193, 0.1); color: var(--purple); }
.badge-danger { background: rgba(239, 71, 111, 0.1); color: var(--danger); }

.school-id {
    font-size: 0.7rem;
    color: var(--gray);
    background: var(--light);
    padding: 4px 8px;
    border-radius: 12px;
}

.school-card-body {
    padding: 15px;
}

.school-name {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--dark);
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.school-name i {
    color: var(--primary);
    font-size: 1.2rem;
}

.school-details {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 12px;
}

.detail-row {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.9rem;
    color: var(--gray);
}

.detail-row i {
    color: var(--primary);
    width: 20px;
    font-size: 0.9rem;
}

.detail-row strong {
    color: var(--dark);
    margin-right: 4px;
}

.contact-info {
    background: var(--light);
    border-radius: 12px;
    padding: 10px;
    margin: 12px 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 0.9rem;
}

.contact-info i {
    color: var(--primary);
}

.progress-section {
    margin: 15px 0;
}

.progress-label {
    display: flex;
    justify-content: space-between;
    font-size: 0.8rem;
    margin-bottom: 6px;
    color: var(--gray);
}

.progress-bar {
    height: 8px;
    background: var(--light);
    border-radius: 4px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, var(--primary), var(--success));
    border-radius: 4px;
    transition: width 0.3s;
}

.visit-stats {
    background: var(--light);
    border-radius: 12px;
    padding: 12px;
    margin: 12px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.visit-count {
    display: flex;
    align-items: center;
    gap: 6px;
    color: var(--primary);
    font-weight: 500;
}

.permission-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: 600;
}

.permission-granted { background: #d4edda; color: #155724; }
.permission-pending { background: #fff3cd; color: #856404; }
.permission-not-allowed { background: #f8d7da; color: #721c24; }

.status-message {
    background: var(--light);
    border-radius: 12px;
    padding: 12px;
    margin: 12px 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 0.9rem;
}

.status-message i {
    font-size: 1.2rem;
}

.status-message.warning { background: #fff3cd; color: #856404; }
.status-message.info { background: #e3f2fd; color: #0c5460; }
.status-message.success { background: #d4edda; color: #155724; }
.status-message.danger { background: #f8d7da; color: #721c24; }

.school-card-footer {
    padding: 15px;
    border-top: 1px solid #e9ecef;
    display: flex;
    gap: 8px;
}

.btn-action {
    flex: 1;
    padding: 12px;
    border: none;
    border-radius: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    text-decoration: none;
    transition: all 0.2s;
    cursor: pointer;
}

.btn-action:active {
    transform: scale(0.96);
}

.btn-primary {
    background: linear-gradient(135deg, var(--primary), #3a0ca3);
    color: white;
}

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

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

.btn-warning {
    background: var(--orange);
    color: white;
}

.btn-action.disabled {
    opacity: 0.5;
    pointer-events: none;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 50px 20px;
    background: white;
    border-radius: 20px;
    margin: 20px;
}

.empty-state i {
    font-size: 3rem;
    color: #dee2e6;
    margin-bottom: 15px;
}

.empty-state h5 {
    color: var(--dark);
    margin-bottom: 8px;
}

.empty-state p {
    color: var(--gray);
    font-size: 0.9rem;
}

/* Bottom Navigation */
.bottom-nav {
    position: sticky;
    bottom: 0;
    background: white;
    padding: 10px 20px;
    border-top: 1px solid #e9ecef;
    display: flex;
    justify-content: space-around;
    backdrop-filter: blur(10px);
    z-index: 100;
}

.nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: var(--gray);
    text-decoration: none;
    font-size: 0.7rem;
    padding: 6px;
    border-radius: 30px;
    transition: all 0.2s;
}

.nav-item i {
    font-size: 1.3rem;
    margin-bottom: 2px;
}

.nav-item.active {
    color: var(--primary);
    background: rgba(67, 97, 238, 0.1);
}

/* Pull to refresh indicator */
.pull-to-refresh {
    text-align: center;
    padding: 10px;
    color: var(--gray);
    font-size: 0.8rem;
    display: none;
}

/* Loading Skeleton */
.skeleton-card {
    background: white;
    border-radius: 20px;
    padding: 15px;
    margin-bottom: 12px;
    border: 1px solid #e9ecef;
}

.skeleton-line {
    height: 20px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: loading 1.5s infinite;
    border-radius: 4px;
    margin-bottom: 10px;
}

@keyframes loading {
    0% { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

/* Tablet and Desktop adjustments */
@media (min-width: 768px) {
    .app-container {
        max-width: 1200px;
    }
    
    .stats-scroll {
        overflow-x: visible;
    }
    
    .stats-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    }
    
    .filter-grid {
        flex-direction: row;
        align-items: flex-end;
    }
    
    .filter-row {
        flex: 1;
    }
    
    .schools-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    }
}
</style>

<div class="app-container">
    <!-- App Header -->
    <div class="app-header">
        <h1>
            <i class="bi bi-building"></i>
            My Schools
        </h1>
        <div class="subtitle">
            <span><i class="bi bi-person"></i> <?= htmlspecialchars($rep_name) ?></span>
            <span><i class="bi bi-geo-alt"></i> <?= count($districts) ?> Districts</span>
        </div>
    </div>

    <!-- Quick Stats Chips (Horizontal Scroll) -->
    <?php
    $total_schools = count($rows);
    $visited_schools = count(array_filter($rows, fn($r) => (int)$r['visited'] === 1 && !(int)$r['is_completed'] && !(int)$r['waiting_verification']));
    $not_visited = count(array_filter($rows, fn($r) => (int)$r['visited'] === 0));
    $completed_schools = count(array_filter($rows, fn($r) => (int)$r['is_completed'] === 1 && !(int)$r['waiting_verification']));
    $waiting_verification = count(array_filter($rows, fn($r) => (int)$r['waiting_verification'] === 1));
    $verified = count(array_filter($rows, fn($r) => $r['verification_status'] === 'APPROVED'));
    $rejected = count(array_filter($rows, fn($r) => $r['verification_status'] === 'REJECTED'));
    ?>
    
    <div class="stats-scroll">
        <div class="stats-row">
            <div class="stat-chip <?= $status_filter === 'all' ? 'active' : '' ?>" onclick="filterByStatus('all')">
                <i class="bi bi-grid"></i>
                <span>All <span class="count"><?= $total_schools ?></span></span>
            </div>
            <div class="stat-chip <?= $status_filter === 'visited' ? 'active' : '' ?>" onclick="filterByStatus('visited')">
                <i class="bi bi-check-circle"></i>
                <span>Visited <span class="count"><?= $visited_schools ?></span></span>
            </div>
            <div class="stat-chip <?= $status_filter === 'not_visited' ? 'active' : '' ?>" onclick="filterByStatus('not_visited')">
                <i class="bi bi-clock"></i>
                <span>Not Visited <span class="count"><?= $not_visited ?></span></span>
            </div>
            <div class="stat-chip <?= $status_filter === 'completed' ? 'active' : '' ?>" onclick="filterByStatus('completed')">
                <i class="bi bi-check2-all"></i>
                <span>Completed <span class="count"><?= $completed_schools ?></span></span>
            </div>
            <div class="stat-chip <?= $status_filter === 'waiting' ? 'active' : '' ?>" onclick="filterByStatus('waiting')">
                <i class="bi bi-hourglass-split"></i>
                <span>Waiting <span class="count"><?= $waiting_verification ?></span></span>
            </div>
            <div class="stat-chip <?= $status_filter === 'verified' ? 'active' : '' ?>" onclick="filterByStatus('verified')">
                <i class="bi bi-check-circle-fill"></i>
                <span>Verified <span class="count"><?= $verified ?></span></span>
            </div>
            <div class="stat-chip <?= $status_filter === 'rejected' ? 'active' : '' ?>" onclick="filterByStatus('rejected')">
                <i class="bi bi-x-circle"></i>
                <span>Rejected <span class="count"><?= $rejected ?></span></span>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter-section">
        <div class="filter-header">
            <i class="bi bi-funnel"></i>
            Filter Schools
        </div>
        
        <form method="get" id="filterForm">
            <div class="filter-grid">
                <div class="filter-row">
                    <select class="form-select" name="district_id" id="fDistrict">
                        <option value="">All Districts</option>
                        <?php foreach ($districts as $d): ?>
                            <option value="<?= htmlspecialchars($d['id']) ?>" <?= ($district_id === $d['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($d['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

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

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

                <!-- School Dropdown Filter -->
                <div class="filter-row">
                    <select class="form-select" name="school_id" id="fSchool" <?= empty($schools_dropdown) ? 'disabled' : '' ?>>
                        <option value="">All Schools</option>
                        <?php foreach ($schools_dropdown as $s): ?>
                            <option value="<?= htmlspecialchars($s['id']) ?>" <?= ($school_id === $s['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($s['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-row">
                    <input type="text" class="form-control" name="q" value="<?= htmlspecialchars($q) ?>"
                           placeholder="Search schools...">
                </div>

                <input type="hidden" name="status" id="statusInput" value="<?= htmlspecialchars($status_filter) ?>">

                <div class="filter-actions">
                    <button type="submit" class="btn-filter primary">
                        <i class="bi bi-search"></i> Apply Filters
                    </button>
                    <button type="button" class="btn-filter secondary" onclick="clearFilters()">
                        <i class="bi bi-x-circle"></i> Clear
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Schools List -->
    <div class="schools-grid" id="schoolsContainer">
        <?php if (empty($rows)): ?>
            <div class="empty-state">
                <i class="bi bi-building-slash"></i>
                <h5>No Schools Found</h5>
                <p>Try adjusting your filters or search criteria</p>
            </div>
        <?php endif; ?>

        <?php foreach ($rows as $r):
            $visited = (int)$r['visited'] === 1;
            $is_completed = (int)$r['is_completed'] === 1;
            $waiting = (int)$r['waiting_verification'] === 1;
            $verified_status = $r['verification_status'];
            $last_visit = $r['last_visit_date'] ? date('d M Y', strtotime($r['last_visit_date'])) : 'Never';
            
            // Calculate progress
            $classes_visited = (int)$r['total_visits']; // This is approximate, you might want to calculate properly
            $progress_percent = min(100, round(($classes_visited / 12) * 100));

            $permission_class = '';
            $permission_text = '';
            if ($r['last_permission_status'] === 'GRANTED') {
                $permission_class = 'permission-granted';
                $permission_text = '✅ Granted';
            } elseif ($r['last_permission_status'] === 'PENDING') {
                $permission_class = 'permission-pending';
                $permission_text = '⏳ Pending';
            } elseif ($r['last_permission_status'] === 'NOT_ALLOWED') {
                $permission_class = 'permission-not-allowed';
                $permission_text = '❌ Not Allowed';
            }

            $card_class = 'school-card';
            if ($verified_status === 'APPROVED') $card_class .= ' verified';
            elseif ($verified_status === 'REJECTED') $card_class .= ' rejected';
            elseif ($waiting) $card_class .= ' waiting';
            elseif ($is_completed) $card_class .= ' completed';
            elseif ($visited) $card_class .= ' visited';
            else $card_class .= ' not-visited';
        ?>
        <div class="<?= $card_class ?>" data-school-id="<?= htmlspecialchars($r['school_id']) ?>">
            <div class="school-card-header">
                <?php if ($verified_status === 'APPROVED'): ?>
                    <span class="school-badge badge-success"><i class="bi bi-check-circle"></i> Verified</span>
                <?php elseif ($verified_status === 'REJECTED'): ?>
                    <span class="school-badge badge-danger"><i class="bi bi-x-circle"></i> Rejected</span>
                <?php elseif ($waiting): ?>
                    <span class="school-badge badge-info"><i class="bi bi-hourglass-split"></i> Waiting</span>
                <?php elseif ($is_completed): ?>
                    <span class="school-badge badge-purple"><i class="bi bi-check2-all"></i> Completed</span>
                <?php elseif ($visited): ?>
                    <span class="school-badge badge-success"><i class="bi bi-check-circle"></i> Visited</span>
                <?php else: ?>
                    <span class="school-badge badge-warning"><i class="bi bi-clock"></i> Not Visited</span>
                <?php endif; ?>
                <span class="school-id">#<?= htmlspecialchars(substr($r['school_id'], -6)) ?></span>
            </div>

            <div class="school-card-body">
                <div class="school-name">
                    <i class="bi bi-building"></i>
                    <?= htmlspecialchars($r['school_name']) ?>
                </div>

                <div class="school-details">
                    <div class="detail-row">
                        <i class="bi bi-geo-alt"></i>
                        <span><strong><?= htmlspecialchars($r['district_name'] ?? 'N/A') ?></strong> / <?= htmlspecialchars($r['block_name'] ?? 'N/A') ?></span>
                    </div>
                    <div class="detail-row">
                        <i class="bi bi-diagram-3"></i>
                        <span>GP: <?= htmlspecialchars($r['gp_name'] ?? 'N/A') ?></span>
                    </div>
                    <?php if (!empty($r['category'])): ?>
                    <div class="detail-row">
                        <i class="bi bi-tag"></i>
                        <span><?= htmlspecialchars($r['category']) ?></span>
                    </div>
                    <?php endif; ?>
                </div>

                <?php if (!empty($r['contact_no'])): ?>
                <div class="contact-info">
                    <i class="bi bi-telephone"></i>
                    <span><?= htmlspecialchars($r['contact_no']) ?></span>
                </div>
                <?php endif; ?>

                <!-- Progress Bar -->
                <?php if ($visited && !$waiting && $verified_status !== 'APPROVED'): ?>
                <div class="progress-section">
                    <div class="progress-label">
                        <span>Progress</span>
                        <span><?= $classes_visited ?>/12 classes</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: <?= $progress_percent ?>%;"></div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Status Messages -->
                <?php if ($verified_status === 'REJECTED'): ?>
                    <div class="status-message danger">
                        <i class="bi bi-x-circle"></i>
                        <span>Verification rejected. Please resubmit.</span>
                    </div>
                <?php elseif ($waiting): ?>
                    <div class="status-message info">
                        <i class="bi bi-hourglass-split"></i>
                        <span>Waiting for admin verification</span>
                    </div>
                <?php elseif ($is_completed && !$waiting): ?>
                    <div class="status-message warning">
                        <i class="bi bi-check2-all"></i>
                        <span>All classes completed! Ready for verification</span>
                    </div>
                <?php endif; ?>

                <!-- Visit Stats -->
                <?php if ($visited && !$waiting && $verified_status !== 'APPROVED'): ?>
                <div class="visit-stats">
                    <span class="visit-count">
                        <i class="bi bi-calendar-check"></i>
                        <?= (int)$r['total_visits'] ?> visit<?= ((int)$r['total_visits'] !== 1) ? 's' : '' ?>
                    </span>
                    <?php if ($permission_class): ?>
                        <span class="permission-badge <?= $permission_class ?>"><?= $permission_text ?></span>
                    <?php endif; ?>
                </div>
                <div style="font-size: 0.8rem; color: var(--gray); margin-top: 5px;">
                    <i class="bi bi-clock"></i> Last: <?= $last_visit ?>
                </div>
                <?php endif; ?>
            </div>

            <div class="school-card-footer">
                <?php if ($verified_status === 'APPROVED'): ?>
                    <a href="#" class="btn-action btn-secondary disabled">
                        <i class="bi bi-check-circle"></i> Verified
                    </a>
                    <a href="/school-crm/public/visit_history.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-secondary">
                        <i class="bi bi-eye"></i> View
                    </a>

                <?php elseif ($verified_status === 'REJECTED'): ?>
                    <a href="/school-crm/public/visit_add.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-warning">
                        <i class="bi bi-arrow-repeat"></i> Resubmit
                    </a>
                    <a href="/school-crm/public/visit_history.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-secondary">
                        <i class="bi bi-eye"></i> View
                    </a>

                <?php elseif ($waiting): ?>
                    <a href="#" class="btn-action btn-secondary disabled">
                        <i class="bi bi-hourglass-split"></i> Under Review
                    </a>
                    <a href="/school-crm/public/visit_history.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-secondary">
                        <i class="bi bi-eye"></i> Report
                    </a>

                <?php elseif ($is_completed): ?>
                    <a href="#" class="btn-action btn-success" onclick="requestVerification('<?= $r['school_id'] ?>')">
                        <i class="bi bi-send"></i> Request Verify
                    </a>
                    <a href="/school-crm/public/visit_history.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-secondary">
                        <i class="bi bi-eye"></i> Summary
                    </a>

                <?php else: ?>
                    <a href="/school-crm/public/visit_add.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-primary">
                        <i class="bi bi-plus-circle"></i> Add Visit
                    </a>
                    <?php if ($visited): ?>
                    <a href="/school-crm/public/visit_history.php?school_id=<?= urlencode((string)$r['school_id']) ?>" class="btn-action btn-secondary">
                        <i class="bi bi-eye"></i> History
                    </a>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Bottom Navigation -->
    <div class="bottom-nav">
        <a href="/school-crm/public/dashboard.php" class="nav-item">
            <i class="bi bi-house"></i>
            <span>Home</span>
        </a>
        <a href="/school-crm/public/visit_add.php" class="nav-item">
            <i class="bi bi-plus-circle"></i>
            <span>Add Visit</span>
        </a>
        <a href="#" class="nav-item active">
            <i class="bi bi-building"></i>
            <span>Schools</span>
        </a>
        <a href="/school-crm/public/profile.php" class="nav-item">
            <i class="bi bi-person"></i>
            <span>Profile</span>
        </a>
    </div>
</div>

<script>
// Filter dependency chain
document.getElementById('fDistrict')?.addEventListener('change', function() {
    document.getElementById('fBlock').disabled = !this.value;
    document.getElementById('fGP').disabled = true;
    document.getElementById('fSchool').disabled = true;
    document.getElementById('filterForm').submit();
});

document.getElementById('fBlock')?.addEventListener('change', function() {
    document.getElementById('fGP').disabled = !this.value;
    document.getElementById('fSchool').disabled = true;
    document.getElementById('filterForm').submit();
});

document.getElementById('fGP')?.addEventListener('change', function() {
    document.getElementById('fSchool').disabled = !this.value;
    document.getElementById('filterForm').submit();
});

document.getElementById('fSchool')?.addEventListener('change', function() {
    document.getElementById('filterForm').submit();
});

// Filter by status
function filterByStatus(status) {
    document.getElementById('statusInput').value = status;
    document.getElementById('filterForm').submit();
}

// Clear all filters
function clearFilters() {
    const url = new URL(window.location.href);
    url.search = '';
    window.location.href = url.toString();
}

// Search on enter
document.querySelector('input[name="q"]')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('filterForm').submit();
    }
});

// Request verification
function requestVerification(schoolId) {
    if (!confirm('Are you sure you want to request verification for this school?')) {
        return;
    }
    
    // Show loading state
    const btn = event.target.closest('button, a');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Sending...';
    btn.disabled = true;
    
    fetch('/school-crm/api/request_verification.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            school_id: schoolId,
            csrf: '<?= csrf_token() ?>'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Verification request submitted successfully!');
            window.location.reload();
        } else {
            alert('Error: ' + data.message);
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
        btn.innerHTML = originalText;
        btn.disabled = false;
    });
}

// Pull to refresh (mobile)
let touchStart = 0;
document.addEventListener('touchstart', (e) => {
    touchStart = e.touches[0].clientY;
});

document.addEventListener('touchmove', (e) => {
    const touchY = e.touches[0].clientY;
    const pull = touchY - touchStart;
    
    if (pull > 100 && window.scrollY === 0) {
        document.querySelector('.pull-to-refresh').style.display = 'block';
    }
});

document.addEventListener('touchend', () => {
    if (document.querySelector('.pull-to-refresh').style.display === 'block') {
        window.location.reload();
    }
});
</script>

<!-- Pull to refresh indicator -->
<div class="pull-to-refresh">
    <i class="bi bi-arrow-down"></i> Pull to refresh
</div>

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