<?php
declare(strict_types=1);

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

// Allow only authenticated users
if (!is_authenticated()) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$gp_id = $_GET['gp_id'] ?? '';
if (!$gp_id) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'GP ID required']);
    exit;
}

try {
    // Get current active REP for this GP
    $stRep = $pdo->prepare("
        SELECT user_id FROM gp_assignments 
        WHERE gp_id = ? AND status = 'ACTIVE'
    ");
    $stRep->execute([$gp_id]);
    $rep_id = $stRep->fetchColumn();
    
    if (!$rep_id) {
        echo json_encode(['total' => 0, 'visited' => 0, 'pending' => 0]);
        exit;
    }
    
    // Get statistics
    $st = $pdo->prepare("
        SELECT 
            COUNT(*) as total,
            COUNT(CASE WHEN vs.id IS NOT NULL THEN 1 END) as visited
        FROM schools s
        LEFT JOIN school_visits vs ON s.id = vs.school_id AND vs.representative_id = ?
        WHERE s.gp_id = ?
    ");
    $st->execute([$rep_id, $gp_id]);
    $stats = $st->fetch(PDO::FETCH_ASSOC);
    
    $result = [
        'total' => (int)$stats['total'],
        'visited' => (int)$stats['visited'],
        'pending' => (int)$stats['total'] - (int)$stats['visited']
    ];
    
    header('Content-Type: application/json');
    echo json_encode($result);
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Database error']);
}