<?php
/**
 * GET assignments for a match: Chrono, Stats, or Equipment check.
 * GET: match_id
 */
require_once __DIR__ . '/../config/cors.php';
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

$matchId = (int) ($_GET['match_id'] ?? 0);

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

$types = ['chrono', 'stats', 'equipment_check', 'states', 'quarter_master', 'range_master'];

// Fetch dynamic assignments
$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'])));
    if (!in_array($apiType, $types)) {
        $types[] = $apiType;
    }
}

$assignments = [];

foreach ($types as $type) {
    $table = 'match_' . $type . '_assignments';

    // Check if table exists
    $check = $pdo->query("SHOW TABLES LIKE '$table'");
    if ($check->rowCount() > 0) {
        $cols = ($type === 'states') ? "states_number, lro_name as officer_name, role, rm_signature" : "officer_name, role, rm_signature";
        $stmt = $pdo->prepare("SELECT $cols FROM `$table` WHERE match_id = ? AND submitted_by = ?");
        $stmt->execute([$matchId, $_GET['user_id'] ?? 0]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($data) {
            $res = [
                'officer_name' => $data['officer_name'],
                'role' => $data['role'],
                'has_signature' => !empty($data['rm_signature']),
                'rm_signature' => $data['rm_signature']
            ];
            if ($type === 'states') {
                $res['states_number'] = $data['states_number'];
            }
            $assignments[$type] = $res;
        } else {
            $assignments[$type] = null;
        }
    } else {
        $assignments[$type] = null;
    }
}

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