<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/market_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) ?: [];
$itemId = trim((string) ($input['itemId'] ?? ''));
if ($itemId === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'item'], JSON_UNESCAPED_UNICODE);
    exit;
}

$stockResult = market_decrement_stock($itemId);
if (!($stockResult['ok'] ?? false)) {
    $err = (string) ($stockResult['error'] ?? 'market');
    if ($err === 'out_of_stock') {
        http_response_code(409);
        echo json_encode(['ok' => false, 'error' => 'out_of_stock'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($err === 'not_found') {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => $err], JSON_UNESCAPED_UNICODE);
    exit;
}

$item = is_array($stockResult['item'] ?? null) ? $stockResult['item'] : [];
$stockAfter = (int) ($stockResult['stock'] ?? market_item_stock($item));

$price = isset($item['price']) ? (int) $item['price'] : 0;
if ($price <= 0) {
    market_increment_stock($itemId, 1);
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'price'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

try {
    $pdo->beginTransaction();
    $up = $pdo->prepare('UPDATE users SET coins = coins - :p WHERE id = :id AND coins >= :p2');
    $up->execute([':p' => $price, ':id' => $uid, ':p2' => $price]);
    if ($up->rowCount() !== 1) {
        $pdo->rollBack();
        market_increment_stock($itemId, 1);
        $st = $pdo->prepare('SELECT coins FROM users WHERE id = :id');
        $st->execute([':id' => $uid]);
        $urow = $st->fetch();
        $bal = $urow ? (int) $urow['coins'] : 0;
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'funds', 'coins' => $bal], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $st = $pdo->prepare('SELECT coins FROM users WHERE id = :id');
    $st->execute([':id' => $uid]);
    $newCoins = (int) ($st->fetch()['coins'] ?? 0);

    $ins = $pdo->prepare(
        'INSERT INTO purchases (user_id, item_id, item_title, price, status, created_at) VALUES (:uid, :iid, :tit, :pr, :st, :t)'
    );
    $ins->execute([
        ':uid' => $uid,
        ':iid' => (string) ($item['id'] ?? $itemId),
        ':tit' => (string) ($item['title'] ?? $itemId),
        ':pr' => $price,
        ':st' => 'pending',
        ':t' => time(),
    ]);

    $pdo->commit();
} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    market_increment_stock($itemId, 1);
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(
    [
        'ok' => true,
        'user' => [
            'coins' => $newCoins,
        ],
        'item' => [
            'id' => (string) ($item['id'] ?? $itemId),
            'title' => (string) ($item['title'] ?? ''),
            'stock' => $stockAfter,
        ],
    ],
    JSON_UNESCAPED_UNICODE
);
