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

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

try {
    $userId = isset($_GET['user_id']) ? $_GET['user_id'] : null;
    $params = [];
    $areaFilter = '';
    // Area filtering removed: all users can now see all matches regardless of area.


    $today = date('Y-m-d');
    if ($userId) {
        $stmt = $pdo->prepare("
            SELECT m.*, ms.status as signification_status, ms.is_extended as ms_is_extended,
            u_creator.area as creator_area,
            ms.withdrawal_reason, ms.officer_remarks,
            (SELECT al.performed_by_role FROM activity_logs al
             WHERE al.reference_type = 'match_signification' AND al.reference_id = ms.id
               AND al.performed_by_role IN ('AC','AAC','ADMIN','RM')
             ORDER BY al.created_at DESC LIMIT 1) as reviewer_role,
            (SELECT COUNT(*) FROM match_significations ms2 WHERE ms2.match_id = m.id AND ms2.status = 'approved') as approved_count,
            (SELECT COUNT(*) FROM match_significations ms3 WHERE ms3.match_id = m.id AND ms3.is_rm_enabled = 1) as pending_rm_count,
            (SELECT COUNT(*) FROM match_significations ms4 WHERE ms4.match_id = m.id AND ms4.status = 'pending') as pending_signification_count
            FROM match_schedules m
            LEFT JOIN users u_creator ON m.created_by = u_creator.id
            LEFT JOIN match_significations ms ON m.id = ms.match_id AND ms.user_id = ?
            WHERE (
                m.end_date >= ? 
                OR ms.is_extended = 1 
                OR (m.rm_id = ? AND (
                    EXISTS (SELECT 1 FROM match_significations ms5 WHERE ms5.match_id = m.id AND ms5.is_rm_enabled = 1)
                    OR EXISTS (SELECT 1 FROM match_significations ms6 WHERE ms6.match_id = m.id AND ms6.status = 'pending')
                ))
            )
            ORDER BY m.start_date ASC
        ");
        $stmt->execute([$userId, $today, $userId]);
    } else {
        $stmt = $pdo->prepare("
            SELECT m.*, u_creator.area as creator_area, NULL as signification_status,
            (SELECT COUNT(*) FROM match_significations ms2 WHERE ms2.match_id = m.id AND ms2.status = 'approved') as approved_count
            FROM match_schedules m
            LEFT JOIN users u_creator ON m.created_by = u_creator.id
            WHERE m.end_date >= ?
            ORDER BY m.start_date ASC
        ");
        $stmt->execute([$today]);
    }

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

    // Get the requesting user's area for retroactive filtering
    $userArea = null;
    if ($userId) {
        $stmtUserArea = $pdo->prepare("SELECT area FROM users WHERE id = ?");
        $stmtUserArea->execute([$userId]);
        $userArea = $stmtUserArea->fetchColumn();
    }

    $matches = [];

    foreach ($allMatches as $m) {
        $status = $m['signification_status'] ?? 'none';
        $isApproved = ($status === 'approved');
        $isFull = ($m['ro_limit'] > 0 && ($m['approved_count'] ?? 0) >= $m['ro_limit']);
        $isOngoing = ($m['start_date'] <= $today);
        $isRM = ($userId && isset($m['rm_id']) && (string) $m['rm_id'] === (string) $userId);
        $isRMWithPending = ($isRM && (($m['pending_rm_count'] ?? 0) > 0 || ($m['pending_signification_count'] ?? 0) > 0));

        // Disappearance Rules:
        if (!$isRM) {
            // 1. already ongoing and not approved (for ROs)
            if ($isOngoing && !$isApproved) {
                continue;
            }

            // 3. match is already full and user has not been approved (for ROs)
            if ($isFull && !$isApproved) {
                continue;
            }

            // 4. Retroactive or Local match: only show to users in the same area as creator
            if ((!empty($m['is_retroactive']) && $m['is_retroactive'] == 1) || (!empty($m['is_local']) && $m['is_local'] == 1)) {
                $matchArea = $m['creator_area'] ?? null;
                if ($matchArea !== null && $matchArea !== '') {
                    if ($userArea !== $matchArea) {
                        // But still show if they are already approved (already joined)
                        if (!$isApproved && $status !== 'pending') {
                            continue;
                        }
                    }
                }
            }
        }

        $matches[] = $m;
    }

    // For matches where the user has signified and status is NOT pending, attach list of other approved members
    if ($userId) {
        $stmtApproved = $pdo->prepare("
            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' AND u.id != ?
            ORDER BY u.last_name ASC, u.first_name ASC
        ");
        foreach ($matches as &$m) {
            $m['approved_signifiers'] = [];
            $status = $m['signification_status'] ?? null;
            if ($status !== null && $status !== 'pending') {
                $stmtApproved->execute([$m['id'], $userId]);
                $m['approved_signifiers'] = $stmtApproved->fetchAll(PDO::FETCH_ASSOC);
            }
        }
        unset($m);
    }

    // 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()
    ]);
}
?>