<?php
require_once dirname(__DIR__) . '/safety/ChairmanSafeLoader.php';
require_once dirname(__DIR__) . '/presenter/ChairmanGatewayPresenter.php';

$raceDate = isset($_GET['race_date']) ? trim($_GET['race_date']) :
    (isset($_GET['date']) ? trim($_GET['date']) :
    (isset($_GET['review_date']) ? trim($_GET['review_date']) : date('Y-m-d')));

$venue = isset($_GET['venue']) ? trim($_GET['venue']) : '';
$raceNum = isset($_GET['race_num']) ? intval($_GET['race_num']) : 0;

header('Content-Type: application/json; charset=utf-8');

try {
    $payload = ChairmanSafeLoader::payload($raceDate, $venue, $raceNum);
    if (!isset($payload['ok']) || !$payload['ok']) {
        echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }

    $presenter = new ChairmanGatewayPresenter();
    $view = $presenter->present($payload);

    echo json_encode(array(
        'ok' => true,
        'race_date' => $raceDate,
        'venue' => $venue,
        'race_num' => $raceNum,
        'counts' => isset($payload['counts']) ? $payload['counts'] : array(),
        'auto_production' => isset($payload['auto_production']) ? $payload['auto_production'] : array(),
        'view' => $view,
        'ts' => date('Y-m-d H:i:s')
    ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(array(
        'ok'=>false,
        'status'=>'V46_PRESENTER_ERROR',
        'error'=>$e->getMessage()
    ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(array(
        'ok'=>false,
        'status'=>'V46_PRESENTER_ERROR',
        'error'=>$e->getMessage()
    ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
