<?php
declare(strict_types=1);

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

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

const MOCKER_DAILY_BONUS_COINS = 25;

function mocker_daily_bonus_calendar_day(int $unixTs): string
{
    $tz = new DateTimeZone('Europe/Istanbul');

    return (new DateTime('@' . $unixTs))->setTimezone($tz)->format('Y-m-d');
}

function mocker_daily_bonus_today_key(): string
{
    $tz = new DateTimeZone('Europe/Istanbul');

    return (new DateTime('now', $tz))->format('Y-m-d');
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;

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

if ($method === 'GET') {
    if ($uid <= 0) {
        echo json_encode(
            [
                'ok' => true,
                'authenticated' => false,
                'amount' => MOCKER_DAILY_BONUS_COINS,
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }
    $st = $pdo->prepare('SELECT coins, last_daily_bonus_at FROM users WHERE id = :id LIMIT 1');
    $st->execute([':id' => $uid]);
    $row = $st->fetch();
    if (!$row) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'user'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $last = isset($row['last_daily_bonus_at']) ? (int) $row['last_daily_bonus_at'] : 0;
    $today = mocker_daily_bonus_today_key();
    $canClaim = $last <= 0 || mocker_daily_bonus_calendar_day($last) !== $today;
    echo json_encode(
        [
            'ok' => true,
            'authenticated' => true,
            'amount' => MOCKER_DAILY_BONUS_COINS,
            'coins' => (int) $row['coins'],
            'can_claim' => $canClaim,
        ],
        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();

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

$now = time();
$today = mocker_daily_bonus_today_key();

try {
    $pdo->beginTransaction();
    $st = $pdo->prepare('SELECT id, coins, last_daily_bonus_at FROM users WHERE id = :id LIMIT 1');
    $st->execute([':id' => $uid]);
    $row = $st->fetch();
    if (!$row) {
        $pdo->rollBack();
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'user'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $last = isset($row['last_daily_bonus_at']) ? (int) $row['last_daily_bonus_at'] : 0;
    if ($last > 0 && mocker_daily_bonus_calendar_day($last) === $today) {
        $pdo->rollBack();
        echo json_encode(
            [
                'ok' => false,
                'error' => 'already_claimed',
                'coins' => (int) $row['coins'],
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }
    $up = $pdo->prepare(
        'UPDATE users SET coins = coins + :add, last_daily_bonus_at = :t WHERE id = :id'
    );
    $up->execute([
        ':add' => MOCKER_DAILY_BONUS_COINS,
        ':t' => $now,
        ':id' => $uid,
    ]);
    $coins = (int) $row['coins'] + MOCKER_DAILY_BONUS_COINS;
    $pdo->commit();
    echo json_encode(
        [
            'ok' => true,
            'added' => MOCKER_DAILY_BONUS_COINS,
            'coins' => $coins,
        ],
        JSON_UNESCAPED_UNICODE
    );
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
}
