<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/site_join_guides_lib.php';

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

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    $kind = trim((string) ($_GET['kind'] ?? ''));
    if ($kind !== '' && $kind !== 'events' && $kind !== 'tickets') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'kind'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($kind === 'events') {
        mocker_admin_require_permission('events');
    } elseif ($kind === 'tickets') {
        mocker_admin_require_permission('tickets');
    } else {
        if (!mocker_admin_can('events') && !mocker_admin_can('tickets')) {
            mocker_admin_require_permission('events');
        }
    }

    $all = mocker_join_guides_read();
    $payload = ['ok' => true, 'joinGuides' => $all];
    if ($kind !== '') {
        $payload['guide'] = $all[$kind] ?? ['locales' => ['tr' => mocker_join_guide_trim_locale([]), 'en' => mocker_join_guide_trim_locale([])]];
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$kind = trim((string) ($input['kind'] ?? ''));
$guide = isset($input['guide']) && is_array($input['guide']) ? $input['guide'] : [];

if ($kind === 'events') {
    mocker_admin_require_permission('events');
} elseif ($kind === 'tickets') {
    mocker_admin_require_permission('tickets');
} else {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'kind'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $saved = mocker_join_guide_save_kind($kind, $guide);
    echo json_encode(['ok' => true, 'kind' => $kind, 'guide' => $saved], JSON_UNESCAPED_UNICODE);
} catch (InvalidArgumentException $e) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'save'], JSON_UNESCAPED_UNICODE);
}
