<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/ticket_lib.php';
require_once __DIR__ . '/level_lib.php';

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

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

mocker_require_csrf_post();

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$eventId = (int) ($input['eventId'] ?? 0);
$siteUsername = trim((string) ($input['siteUsername'] ?? ''));
$investmentAmount = (float) ($input['investmentAmount'] ?? 0);
$investmentAtRaw = trim((string) ($input['investmentAt'] ?? ''));
$ticketRef = mocker_utf8_substr(trim((string) ($input['ticketRef'] ?? '')), 0, 64);

if ($eventId <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'event'], JSON_UNESCAPED_UNICODE);
    exit;
}
if ($siteUsername === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'site_username'], JSON_UNESCAPED_UNICODE);
    exit;
}
if ($investmentAmount <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'amount'], JSON_UNESCAPED_UNICODE);
    exit;
}

$investmentAt = time();
if ($investmentAtRaw !== '') {
    $parsed = strtotime($investmentAtRaw);
    if ($parsed !== false && $parsed > 0) {
        $investmentAt = $parsed;
    }
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$st = $pdo->prepare(
    'SELECT id, status, ends_at, investment_per_ticket, category FROM ticket_events WHERE id = :id LIMIT 1'
);
$st->execute([':id' => $eventId]);
$ev = $st->fetch(PDO::FETCH_ASSOC);
if (!$ev) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}
$expectedCategory = defined('MOCKER_TICKET_REQUEST_CATEGORY') ? (string) MOCKER_TICKET_REQUEST_CATEGORY : 'ticket';
if ((string) ($ev['category'] ?? 'ticket') !== $expectedCategory) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}
if ((string) $ev['status'] !== 'open') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'closed'], JSON_UNESCAPED_UNICODE);
    exit;
}

$now = time();
if ($ev['ends_at'] !== null && (int) $ev['ends_at'] > 0 && (int) $ev['ends_at'] <= $now) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'ended'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pendingSt = $pdo->prepare(
    'SELECT COUNT(*) FROM ticket_requests WHERE event_id = :eid AND user_id = :uid AND status = \'pending\''
);
$pendingSt->execute([':eid' => $eventId, ':uid' => $uid]);
if ((int) $pendingSt->fetchColumn() > 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'pending_exists'], JSON_UNESCAPED_UNICODE);
    exit;
}

$userSt = $pdo->prepare('SELECT username FROM users WHERE id = :id LIMIT 1');
$userSt->execute([':id' => $uid]);
$userRow = $userSt->fetch(PDO::FETCH_ASSOC);
$username = $userRow ? trim((string) $userRow['username']) : '';

$perTicket = (float) ($ev['investment_per_ticket'] ?? 1000);
$eligible = mocker_ticket_calc_eligible($investmentAmount, $perTicket);

$pdo->prepare(
    'INSERT INTO ticket_requests (
        event_id, user_id, username, site_username, investment_amount, investment_at,
        ticket_ref, tickets_eligible, tickets_granted, status, admin_note, created_at
    ) VALUES (
        :eid, :uid, :un, :site, :amt, :inv, :ref, :elig, 0, \'pending\', \'\', :t
    )'
)->execute([
    ':eid' => $eventId,
    ':uid' => $uid,
    ':un' => mocker_utf8_substr($username, 0, 80),
    ':site' => mocker_utf8_substr($siteUsername, 0, 120),
    ':amt' => round($investmentAmount, 2),
    ':inv' => $investmentAt,
    ':ref' => $ticketRef,
    ':elig' => $eligible,
    ':t' => $now,
]);
$requestId = (int) $pdo->lastInsertId();
if ($requestId > 0) {
    try {
        mocker_level_award_ticket_request($pdo, $uid, $requestId);
    } catch (Throwable $e) {
        /* ignore level errors */
    }
}

echo json_encode(
    [
        'ok' => true,
        'id' => $requestId,
        'ticketsEligible' => $eligible,
    ],
    JSON_UNESCAPED_UNICODE
);
