<?php
require_once __DIR__ . '/../config/cors.php';
require_once '../config/db.php';

header('Content-Type: application/json');

try {
    $type = $_GET['type'] ?? 'all';

    $response = [
        'success' => true,
        'procedurals' => [],
        'disqualifications' => [],
        'match_assignments' => [],
        'match_roles' => []
    ];

    if ($type === 'procedural' || $type === 'all') {
        $stmt = $pdo->query("SELECT * FROM reference_procedural");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        usort($rows, fn($a, $b) => strnatcasecmp($a['name'], $b['name']));
        $response['procedurals'] = $rows;
    }

    if ($type === 'disqualification' || $type === 'all') {
        $stmt = $pdo->query("SELECT * FROM reference_disqualification");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        usort($rows, fn($a, $b) => strnatcasecmp($a['name'], $b['name']));
        $response['disqualifications'] = $rows;
    }

    if ($type === 'match_assignment' || $type === 'all') {
        $stmt = $pdo->query("SELECT id, name FROM reference_match_assignments ORDER BY name ASC");
        $response['match_assignments'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    if ($type === 'match_role' || $type === 'all') {
        $stmt = $pdo->query("SELECT id, name FROM reference_match_roles ORDER BY name ASC");
        $response['match_roles'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    echo json_encode($response);

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