<?php
// API endpoint for creating, updating and syncing matches with the game client
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';

function respond($payload, $status = 200)
{
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

function requireAuth()
{
    if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
        respond(['success' => false, 'error' => 'Unauthorized'], 401);
    }
}

// Database connection (reuses admin config for consistency)
require_once __DIR__ . '/../administration/includes/config.php'; // populates $pdo

if (!isset($pdo) || !($pdo instanceof PDO)) {
    respond(['success' => false, 'error' => 'Database connection not initialized'], 500);
}

// Services
if (!defined('VALID_REQUEST')) {
    define('VALID_REQUEST', true);
}
require_once __DIR__ . '/game-validator.php';
require_once __DIR__ . '/match_service.php';

$validator = new GameValidator($pdo);
$service = new MatchService($pdo, $validator);

$method = $_SERVER['REQUEST_METHOD'];
$userId = $_SESSION['user_id'] ?? null;

try {
    if ($method === 'GET') {
        $since = $_GET['since'] ?? null;
        $filters = [
            'status' => $_GET['status'] ?? null,
            'team_id' => $_GET['team_id'] ?? null,
        ];
        $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 100;

        $data = $service->fetchUpdates($since, $filters, $limit);
        respond([
            'success' => true,
            'data' => $data,
            'syncedAt' => gmdate('Y-m-d H:i:s')
        ]);
    }

    if ($method === 'POST') {
        requireAuth();
        $payload = json_decode(file_get_contents('php://input'), true) ?? [];
        $payload['creator_id'] = $userId;

        $record = $service->createMatch($payload, $userId);
        respond(['success' => true, 'data' => $record], 201);
    }

    if ($method === 'PUT' || $method === 'PATCH') {
        requireAuth();
        $matchId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
        $payload = json_decode(file_get_contents('php://input'), true) ?? [];

        $record = $service->updateMatch($matchId, $payload, $userId);
        respond(['success' => true, 'data' => $record]);
    }

    respond(['success' => false, 'error' => 'Method not allowed'], 405);
} catch (InvalidArgumentException $e) {
    respond(['success' => false, 'error' => $e->getMessage()], 400);
} catch (PDOException $e) {
    respond(['success' => false, 'error' => 'Database error: ' . $e->getMessage()], 500);
} catch (Throwable $e) {
    respond(['success' => false, 'error' => 'Unexpected error: ' . $e->getMessage()], 500);
}
