<?php
// api/endpoints/events.php
include_once __DIR__ . '/../config/root_path.php';

require_once ROOT_PATH . 'api/core/response.php';
require_once ROOT_PATH . 'api/core/db.php';
require_once ROOT_PATH . 'api/core/tournament.php';

/**
 * =========================
 * PARSE ID FROM URL
 * =========================
 */
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = array_values(array_filter(explode('/', $uri)));
$idFromUrl = is_numeric(end($segments)) ? (int) end($segments) : null;

/**
 * =========================
 * SANITIZE GET
 * =========================
 */
$type = isset($_GET['type']) ? trim($_GET['type']) : null;
$lang = $_GET['lang'] ?? 'id';
$idFromUrl = is_numeric(end($segments)) ? (int) end($segments) : null;

$page  = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$limit = isset($_GET['limit']) ? min(50, max(1, (int) $_GET['limit'])) : 8;
$offset = ($page - 1) * $limit;

$dateFrom = (
    isset($_GET['dateFrom']) &&
    preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['dateFrom'])
) ? $_GET['dateFrom'] : null;

$search = isset($_GET['search']) ? trim($_GET['search']) : null;

/**
 * =========================
 * BASE QUERY (DATA)
 * =========================
 */
$options = [
    'type' => $type,
    'lang' => $lang,
    'idFromUrl' => $idFromUrl,
    'page' => $page,
    'limit' => $limit,
    'search' => $search,
    'dateFrom' => $dateFrom,
    'getData' => $_GET
];

$result = getTournamentEvents($options);

jsonResponse($result);