<?php
require_once '../config/cors.php';
header('Content-Type: application/json');
require_once '../config/db.php';

try {
    $matchId = isset($_GET['match_id']) ? (int) $_GET['match_id'] : 0;
    $excludeUserId = isset($_GET['user_id']) ? $_GET['user_id'] : null;

    if ($matchId <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Match ID is required']);
        exit;
    }

    // Fetch users who are approved for this match (optionally exclude current user)
    $sql = "
        SELECT u.id, u.nroi_id, u.first_name, u.last_name, u.middle_name
        FROM match_significations ms
        JOIN users u ON ms.user_id = u.id
        WHERE ms.match_id = ? AND ms.status = 'approved'
    ";
    $params = [$matchId];
    if (!empty($excludeUserId)) {
        $sql .= " AND u.id != ?";
        $params[] = $excludeUserId;
    }
    $sql .= " ORDER BY u.last_name ASC, u.first_name ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'data' => $list,
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage(),
    ]);
}
