<?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 {
    $st = $pdo->prepare("
        SELECT u.id, u.name, u.email
        FROM gp_assignments ga
        JOIN users u ON ga.user_id = u.id
        WHERE ga.gp_id = ? AND ga.status = 'ACTIVE'
    ");
    $st->execute([$gp_id]);
    $rep = $st->fetch(PDO::FETCH_ASSOC);
    
    header('Content-Type: application/json');
    echo json_encode($rep ?: null);
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Database error']);
}