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

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

$userId = isset($_GET['user_id']) ? $_GET['user_id'] : null;

if (!$userId) {
    echo json_encode(['status' => 'error', 'message' => 'User ID is required']);
    exit;
}

try {
    $today = date('Y-m-d');

    // Grace period: 7 days after match ends (INTERVAL 7 DAY from end_date).
    // Show Fill Point Card when:
    //   1. Match is currently ongoing (today <= end_date) and user is approved with no RM signature yet
    //   2. Match ended within the last 7 days — give user a grace window
    //   3. Match is_extended=1 (returned by admin for re-signing) — always show
    //   4. User already has a saved assignment (any role saved) — keep card visible until RM signs
    $stmt = $pdo->prepare("
        SELECT m.*, u_creator.area as creator_area, 
               u_target.match_assignment as profile_match_assignment,
               u_target.match_role as profile_match_role,
               ms.status as signification_status, ms.is_extended as ms_is_extended,
               mp.rm_signature as existing_rm_signature,
               mp.points as existing_points
        FROM match_schedules m
        LEFT JOIN users u_creator ON m.created_by = u_creator.id
        LEFT JOIN users u_target ON u_target.id = ?
        LEFT JOIN match_significations ms ON m.id = ms.match_id AND ms.user_id = ?
        LEFT JOIN match_points mp ON m.id = mp.match_id AND mp.user_id = ?
        WHERE ms.user_id = ?
        AND ms.status = 'approved'
        AND (
            (mp.rm_signature IS NULL OR mp.rm_signature = '')
            OR ms.is_extended = 1
        )
        AND (
            (? BETWEEN m.start_date AND m.end_date) -- Ongoing (Today is within match dates)
            OR ms.is_extended = 1 -- Manual extension
            OR mp.id IS NOT NULL -- Already started filling (draft or needs RM sig)
            OR (m.end_date < ? AND m.end_date >= DATE_SUB(?, INTERVAL 7 DAY)) -- 7-day grace period (Only after match ends)
            OR (m.is_retroactive = 1 AND ? >= m.start_date) -- Retroactive matches show once started until completed
        )
        GROUP BY m.id
        ORDER BY m.start_date ASC
    ");

    $stmt->execute([$userId, $userId, $userId, $userId, $today, $today, $today, $today]);
    $matches = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($matches as &$match) {
        // If returned, we should ignore the existing signature for display purposes on the "Fill" screen
        if ($match['ms_is_extended'] == 1) {
            // $match['existing_rm_signature'] = null; 
            // Actually, keep it but let the UI know it's returned
        }

        $match['expected_points'] = nroi_compute_match_points($match['match_level'], $match['range_master']);

        // Compute days_after_end: how many days since match ended (0 = still ongoing or upcoming)
        $endDate = new DateTime($match['end_date']);
        $todayDt = new DateTime($today);
        if ($todayDt > $endDate) {
            $diff = $todayDt->diff($endDate);
            $match['days_after_end'] = (int) $diff->days; // e.g. 1, 2 ... 7
        } else {
            $match['days_after_end'] = 0; // match still ongoing or upcoming
        }

        // Fetch assignment details for this match+user so the app can display them
        $matchId = $match['id'];
        $assignmentType = null;
        $assignedRole = null;
        $officerName = null;
        $stageNumber = null;
        $lroName = null;

        // Check states assignment
        $stmtSt = $pdo->prepare("SELECT states_number, lro_name, role FROM match_states_assignments WHERE match_id = ? AND submitted_by = ? LIMIT 1");
        $stmtSt->execute([$matchId, $userId]);
        $stRow = $stmtSt->fetch(PDO::FETCH_ASSOC);
        if ($stRow) {
            $assignmentType = 'states';
            $assignedRole = $stRow['role'];
            $stageNumber = $stRow['states_number'];
            $lroName = $stRow['lro_name'];
        }

        if (!$assignmentType) {
            // Check chrono
            $stmtCh = $pdo->prepare("SELECT officer_name, role FROM match_chrono_assignments WHERE match_id = ? AND submitted_by = ? LIMIT 1");
            $stmtCh->execute([$matchId, $userId]);
            $chRow = $stmtCh->fetch(PDO::FETCH_ASSOC);
            if ($chRow) {
                $assignmentType = 'chrono';
                $assignedRole = $chRow['role'];
                $officerName = $chRow['officer_name'];
            }
        }

        if (!$assignmentType) {
            // Check stats
            $stmtSs = $pdo->prepare("SELECT officer_name, role FROM match_stats_assignments WHERE match_id = ? AND submitted_by = ? LIMIT 1");
            $stmtSs->execute([$matchId, $userId]);
            $ssRow = $stmtSs->fetch(PDO::FETCH_ASSOC);
            if ($ssRow) {
                $assignmentType = 'stats';
                $assignedRole = $ssRow['role'];
                $officerName = $ssRow['officer_name'];
            }
        }

        if (!$assignmentType) {
            // Check equipment check
            $stmtEc = $pdo->prepare("SELECT officer_name, role FROM match_equipment_check_assignments WHERE match_id = ? AND submitted_by = ? LIMIT 1");
            $stmtEc->execute([$matchId, $userId]);
            $ecRow = $stmtEc->fetch(PDO::FETCH_ASSOC);
            if ($ecRow) {
                $assignmentType = 'equipment_check';
                $assignedRole = $ecRow['role'];
                $officerName = $ecRow['officer_name'];
            }
        }

        if (!$assignmentType) {
            // Check range_master assignment
            $stmtRm = $pdo->prepare("SELECT officer_name, role FROM match_range_master_assignments WHERE match_id = ? AND submitted_by = ? LIMIT 1");
            $stmtRm->execute([$matchId, $userId]);
            $rmRow = $stmtRm->fetch(PDO::FETCH_ASSOC);
            if ($rmRow) {
                $assignmentType = 'range_master';
                $assignedRole = $rmRow['role'];
                $officerName = $rmRow['officer_name'];
            }
        }

        if (!$assignmentType) {
            // Check dynamic assignments (including match_director)
            $stmtDynamic = $pdo->query("SELECT name FROM reference_match_assignments");
            $dynamicAssignments = $stmtDynamic->fetchAll(PDO::FETCH_ASSOC);
            foreach ($dynamicAssignments as $da) {
                $apiType = strtolower(str_replace(' ', '_', trim($da['name'])));
                // We've already checked standard ones above, but checking again is fine if they don't exist
                $tblName = "match_" . $apiType . "_assignments";
                try {
                    $stmtD = $pdo->prepare("SELECT officer_name, role FROM `$tblName` WHERE match_id = ? AND submitted_by = ? LIMIT 1");
                    $stmtD->execute([$matchId, $userId]);
                    if ($dRow = $stmtD->fetch(PDO::FETCH_ASSOC)) {
                        $assignmentType = $apiType;
                        $assignedRole = $dRow['role'];
                        $officerName = $dRow['officer_name'];
                        break;
                    }
                } catch (Exception $e) {
                    // table might not exist
                }
            }
        }

        $match['fill_assignment_type'] = $assignmentType;
        $match['fill_assigned_role'] = $assignedRole;
        $match['fill_officer_name'] = $officerName;
        $match['fill_stage_number'] = $stageNumber;
        $match['fill_lro_name'] = $lroName;
        $match['is_returned'] = ($match['ms_is_extended'] == 1) ? true : false;
        $match['profile_match_assignment'] = $match['profile_match_assignment'] ?? null;
        $match['profile_match_role'] = $match['profile_match_role'] ?? null;

        // has_assignment: true if user has any saved assignment/role for this match
        $match['has_assignment'] = !empty($assignmentType);
    }
    unset($match);

    // Now filter: if match is in grace period (days_after_end 1-7) AND has no assignment,
    // still show it. But if days_after_end >= 8, only keep if has_assignment (needs RM sign).
    // Note: The WHERE clause above already limits to 7 days, but let's double check here
    // to avoid edge cases on boundary days.
    $matches = array_filter($matches, function ($m) use ($today) {
        $dae = (int) ($m['days_after_end'] ?? 0);
        $hasAssignment = (bool) ($m['has_assignment'] ?? false);
        $isExtended = (bool) ($m['ms_is_extended'] == 1);
        // Always keep if: ongoing (dae == 0), returned (is_extended), has assignment
        // Keep in grace period (dae 1-7) even without assignment
        // Remove if dae >= 8 and no assignment and not extended
        if ($dae >= 8 && !$hasAssignment && !$isExtended) {
            return false;
        }
        return true;
    });
    $matches = array_values($matches); // Re-index

    // Fetch attachments
    $ids = array_column($matches, 'id');
    if (!empty($ids)) {
        $in = str_repeat('?,', count($ids) - 1) . '?';
        $stmtA = $pdo->prepare("SELECT match_id, file_name, file_path, file_type, id FROM match_attachments WHERE match_id IN ($in)");
        $stmtA->execute($ids);
        $attachments = $stmtA->fetchAll(PDO::FETCH_ASSOC);

        $attsByMatchId = [];
        foreach ($attachments as $att) {
            $attsByMatchId[$att['match_id']][] = $att;
        }
        foreach ($matches as &$m) {
            $m['attachments'] = $attsByMatchId[$m['id']] ?? [];
        }
        unset($m);
    }

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

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