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

try {
    $matchId = $_GET['match_id'] ?? null;
    $rmId = $_GET['rm_id'] ?? null;

    if (!$matchId || !$rmId) {
        throw new Exception('Missing match_id or rm_id');
    }

    // Verify RM assignment
    $stmt = $pdo->prepare("SELECT rm_id, is_local, is_retroactive FROM match_schedules WHERE id = ?");
    $stmt->execute([$matchId]);
    $match = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$match || $match['rm_id'] != $rmId) {
        throw new Exception('Unauthorized: Not the assigned RM');
    }

    // Note: The user specified RM management is for Regular matches.
    // However, the button appears for any RM. We'll let the app decide visibility.

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

    $today = date('Y-m-d');
    $stmt = $pdo->prepare("
        SELECT 
            ms.id, 
            ms.user_id, 
            ms.status, 
            ms.created_at, 
            ms.officer_remarks,
            ms.withdrawal_reason,
            u.first_name, 
            u.last_name, 
            u.nroi_id, 
            u.rank, 
            u.role, 
            u.match_assignment,
            u.match_role,
            u.profile_photo,
            ms.is_rm_enabled,
            ms.is_extended,
            (SELECT COUNT(*) FROM match_significations WHERE user_id = u.id AND status = 'withdrawn') as withdraw_count,
            mp.points,
            mp.rm_signature,
            CASE 
                WHEN ms.status != 'approved' THEN NULL
                WHEN mp.rm_signature IS NOT NULL AND mp.rm_signature != '' AND mp.rm_signature != 'DEMERIT' THEN 'served'
                ELSE 'incomplete'
            END as match_completion_status,
            m.match_level,
            m.range_master
        FROM match_significations ms
        JOIN users u ON ms.user_id = u.id
        JOIN match_schedules m ON ms.match_id = m.id
        LEFT JOIN match_points mp ON ms.match_id = mp.match_id AND ms.user_id = mp.user_id
        WHERE ms.match_id = ?
        ORDER BY ms.created_at DESC
    ");
    $stmt->execute([$matchId]);
    $significations = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $castedMatchId = (int) $matchId;

    // Ensure all possible assignment tables exist to prevent crashes during the search loop
    $assignment_types = ['states', 'chrono', 'stats', 'equipment_check', 'quarter_master', 'range_master', 'match_director', 'deputy_range_master'];
    foreach ($assignment_types as $type) {
        $tableName = ($type === 'states') ? "match_states_assignments" : "match_{$type}_assignments";
        $uniqueKeyName = "unique_match_user_{$type}";
        $officerCol = ($type === 'states') ? "`states_number` VARCHAR(100) NOT NULL, `lro_name` VARCHAR(255) NULL," : "`officer_name` VARCHAR(255) NOT NULL,";

        $pdo->exec("CREATE TABLE IF NOT EXISTS `$tableName` (
            `id` INT AUTO_INCREMENT PRIMARY KEY,
            `match_id` INT NOT NULL,
            $officerCol
            `role` VARCHAR(100) NULL,
            `rm_signature` VARCHAR(255) NULL,
            `submitted_by` INT NOT NULL,
            `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY `$uniqueKeyName` (`match_id`, `submitted_by`)
        )");
    }

    foreach ($significations as &$sig) {
        // Initial defaults (fallback to profile/match assignment info)
        $sig['fill_assigned_role'] = $sig['match_role'] ?: $sig['role'];
        $sig['fill_assignment_type'] = $sig['match_assignment'] ?: null;
        $sig['fill_officer_name'] = null;
        $sig['fill_stage_number'] = null;
        $sig['fill_lro_name'] = null;

        $targetUserId = (int) $sig['user_id'];
        $profileType = $sig['match_assignment'];
        $profileTypeKey = ($profileType && strtolower(trim($profileType)) === 'stage') ? 'states' : ($profileType ? strtolower(str_replace(' ', '_', trim($profileType))) : null);

        // List of all possible assignment types (keys)
        $allAssignmentKeys = ['states', 'chrono', 'stats', 'equipment_check', 'quarter_master', 'range_master', 'match_director', 'deputy_range_master'];

        // Prioritize: If profile says they are a certain type, check that table first.
        $checkList = $allAssignmentKeys;
        if ($profileTypeKey && in_array($profileTypeKey, $allAssignmentKeys)) {
            // Move profile type to front
            $checkList = array_diff($allAssignmentKeys, [$profileTypeKey]);
            array_unshift($checkList, $profileTypeKey);
        }

        foreach ($checkList as $t) {
            try {
                if ($t === 'states') {
                    $stmtSt = $pdo->prepare("SELECT states_number, lro_name, role FROM match_states_assignments WHERE match_id = ? AND submitted_by = ? LIMIT 1");
                    $stmtSt->execute([$castedMatchId, $targetUserId]);
                    if ($stRow = $stmtSt->fetch(PDO::FETCH_ASSOC)) {
                        $sig['fill_assignment_type'] = 'states';
                        $sig['fill_assigned_role'] = $stRow['role'] ?: $sig['fill_assigned_role'];
                        $sig['fill_stage_number'] = $stRow['states_number'];
                        $sig['fill_lro_name'] = $stRow['lro_name'];
                        $sig['fill_officer_name'] = $stRow['lro_name'];
                        break; // Found matching table entry
                    }
                } else {
                    $tblName = "match_{$t}_assignments";
                    $stmtT = $pdo->prepare("SELECT officer_name, role FROM `$tblName` WHERE match_id = ? AND submitted_by = ? LIMIT 1");
                    $stmtT->execute([$castedMatchId, $targetUserId]);
                    if ($tRow = $stmtT->fetch(PDO::FETCH_ASSOC)) {
                        $sig['fill_assignment_type'] = $t;
                        $sig['fill_assigned_role'] = $tRow['role'] ?: $sig['fill_assigned_role'];
                        $sig['fill_officer_name'] = $tRow['officer_name'];
                        break; // Found matching table entry
                    }
                }
            } catch (Exception $e) {
                // table might not exist
            }
        }

        // Calculate expected points if not already set in match_points
        if (empty($sig['points'])) {
            $sig['expected_points'] = nroi_compute_match_points($sig['match_level'] ?? '', $sig['range_master'] ?? '');
        }
    }

    echo json_encode(['status' => 'success', 'data' => $significations]);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>