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

require_once '../config/db.php';
require_once '../config/points_config.php';

try {
    // Fetch participants where RM action is enabled (is_rm_enabled = 1)
    // and they are still incomplete (missing signature or missing points)
    // We group by match to show them under each match
    $stmt = $pdo->prepare("
        SELECT 
            m.id as match_id, m.match_name, m.match_level, m.location, m.start_date, m.end_date, m.rm_name as scheduled_rm, m.range_master as disciplines,
            u.id as user_id, u.first_name, u.last_name, u.nroi_id, u.role, u.match_role, u.rank, u.profile_photo,
            ms.is_rm_enabled, ms.created_at as signified_at, ms.reviewed_at as approved_at,
            (SELECT mp.points FROM match_points mp WHERE mp.user_id = u.id AND mp.match_id = m.id LIMIT 1) as points,
            (SELECT mp2.rm_signature FROM match_points mp2 WHERE mp2.user_id = u.id AND mp2.match_id = m.id LIMIT 1) as rm_signature
        FROM match_significations ms
        JOIN match_schedules m ON ms.match_id = m.id
        JOIN users u ON ms.user_id = u.id
        WHERE ms.is_rm_enabled = 1
        AND (
            (DATE(m.end_date) >= DATE(NOW()))
            OR ms.is_extended = 1
        )
        ORDER BY m.start_date ASC, u.last_name ASC
    ");

    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Grouping results by match
    $grouped = [];
    foreach ($results as $row) {
        $mid = $row['match_id'];
        if (!isset($grouped[$mid])) {
            $grouped[$mid] = [
                'id' => $row['match_id'],
                'match_name' => $row['match_name'],
                'match_level' => $row['match_level'],
                'location' => $row['location'],
                'start_date' => $row['start_date'],
                'end_date' => $row['end_date'],
                'scheduled_rm' => $row['scheduled_rm'],
                'disciplines' => $row['disciplines'],
                'participants' => []
            ];
        }

        $allocatedPoints = nroi_compute_match_points($row['match_level'], $row['disciplines']);

        $grouped[$mid]['participants'][] = [
            'user_id' => $row['user_id'],
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'nroi_id' => $row['nroi_id'],
            'role' => ($row['match_role'] && $row['match_role'] !== '') ? $row['match_role'] : $row['role'],
            'rank' => $row['rank'],
            'profile_photo' => $row['profile_photo'],
            'points' => $row['points'],
            'allocated_points' => $allocatedPoints,
            'signified_at' => $row['signified_at'],
            'approved_at' => $row['approved_at'],
            'has_signature' => !empty($row['rm_signature'])
        ];
    }

    echo json_encode([
        'status' => 'success',
        'data' => array_values($grouped)
    ]);

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