<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
header('Cache-Control: public, max-age=30');

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

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
$now = time();
$category = defined('MOCKER_TICKETS_PUBLIC_CATEGORY') ? (string) MOCKER_TICKETS_PUBLIC_CATEGORY : 'ticket';

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, title, description, sponsor_id, sponsor_title, logo_url, site_url, prize_description,
            winner_count, ticket_cost, max_entries_per_user, status, ends_at, created_at, drawn_at
     FROM ticket_events
     WHERE category = :cat AND status IN ('open', 'closed', 'drawn')
     ORDER BY CASE status WHEN 'open' THEN 0 WHEN 'closed' THEN 1 ELSE 2 END, created_at DESC
     LIMIT 50"
);
$st->execute([':cat' => $category]);
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
$events = [];

foreach ($rows as $r) {
    $eid = (int) $r['id'];
    $status = (string) $r['status'];
    if ($status === 'open' && $r['ends_at'] !== null && (int) $r['ends_at'] > 0 && (int) $r['ends_at'] <= $now) {
        $pdo->prepare("UPDATE ticket_events SET status = 'closed' WHERE id = :id AND status = 'open'")
            ->execute([':id' => $eid]);
        $status = 'closed';
        $r['status'] = 'closed';
    }

    $cntSt = $pdo->prepare('SELECT COUNT(*) FROM ticket_entries WHERE event_id = :eid');
    $cntSt->execute([':eid' => $eid]);
    $participantCount = (int) $cntSt->fetchColumn();

    $winners = [];
    if ($status === 'drawn') {
        $wSt = $pdo->prepare(
            'SELECT e.ticket_code, e.user_id, u.username
             FROM ticket_entries e
             INNER JOIN users u ON u.id = e.user_id
             WHERE e.event_id = :eid AND e.is_winner = 1
             ORDER BY e.id ASC'
        );
        $wSt->execute([':eid' => $eid]);
        foreach ($wSt->fetchAll(PDO::FETCH_ASSOC) as $w) {
            $winners[] = [
                'username' => (string) $w['username'],
                'ticketCode' => (string) $w['ticket_code'],
            ];
        }
    }

    $myEntries = [];
    if ($uid > 0) {
        $mSt = $pdo->prepare(
            'SELECT ticket_code, is_winner, created_at FROM ticket_entries WHERE event_id = :eid AND user_id = :uid ORDER BY id ASC'
        );
        $mSt->execute([':eid' => $eid, ':uid' => $uid]);
        foreach ($mSt->fetchAll(PDO::FETCH_ASSOC) as $m) {
            $myEntries[] = [
                'ticketCode' => (string) $m['ticket_code'],
                'isWinner' => (int) $m['is_winner'] === 1,
                'createdAt' => (int) $m['created_at'],
            ];
        }
    }

    $events[] = mocker_ticket_event_row_to_public($r, $participantCount, $winners, $myEntries);
}

echo json_encode(['ok' => true, 'events' => $events, 'serverTime' => $now], JSON_UNESCAPED_UNICODE);
