<?php
declare(strict_types=1);

/**
 * /profile/coins_live.php
 *
 * JSON endpoint для автооновлення VM Coins.
 *
 * Відповідає за:
 * - повернення поточного балансу користувача
 * - повернення total earned / total spent
 * - безпечну роботу тільки для авторизованого користувача
 * - no-cache JSON-відповідь для frontend polling
 */

require_once __DIR__ . '/../includes/start.php';
require_login();

$vmCoinsLibPath = __DIR__ . '/../functional/VMCoins/_lib.php';
if (is_file($vmCoinsLibPath)) {
    require_once $vmCoinsLibPath;
}

if (!function_exists('vmc_live_json')) {
    function vmc_live_json(array $data, int $code = 200): void
    {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Pragma: no-cache');
        header('Expires: 0');
        header('X-Content-Type-Options: nosniff');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
}

if (!function_exists('vmc_live_db_has_column')) {
    function vmc_live_db_has_column(PDO $pdo, string $table, string $column): bool
    {
        try {
            $st = $pdo->prepare("
                SELECT 1
                FROM information_schema.columns
                WHERE table_schema = DATABASE()
                  AND table_name = ?
                  AND column_name = ?
                LIMIT 1
            ");
            $st->execute([$table, $column]);
            return (bool)$st->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

$pdo = (isset($pdo) && $pdo instanceof PDO) ? $pdo : db();
$me  = $me ?? current_user();

$userId = (int)(is_array($me) ? ($me['id'] ?? 0) : 0);
if ($userId <= 0) {
    vmc_live_json(['ok' => false, 'error' => 'auth'], 401);
}

if (session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

$hasBalance = vmc_live_db_has_column($pdo, 'users', 'vm_coins_balance');
$hasEarned  = vmc_live_db_has_column($pdo, 'users', 'vm_coins_earned_total');
$hasSpent   = vmc_live_db_has_column($pdo, 'users', 'vm_coins_spent_total');
$hasUpdated = vmc_live_db_has_column($pdo, 'users', 'vm_coins_updated_at');

$select = ['id'];
if ($hasBalance) $select[] = 'vm_coins_balance';
if ($hasEarned)  $select[] = 'vm_coins_earned_total';
if ($hasSpent)   $select[] = 'vm_coins_spent_total';
if ($hasUpdated) $select[] = 'vm_coins_updated_at';

if (count($select) === 1) {
    vmc_live_json([
        'ok' => true,
        'balance' => 0,
        'earned_total' => 0,
        'spent_total' => 0,
        'updated_at' => null,
    ]);
}

try {
    $st = $pdo->prepare("SELECT " . implode(',', $select) . " FROM users WHERE id = ? LIMIT 1");
    $st->execute([$userId]);
    $row = $st->fetch(PDO::FETCH_ASSOC) ?: null;

    if (!$row) {
        vmc_live_json(['ok' => false, 'error' => 'user_not_found'], 404);
    }

    $balance = $hasBalance ? (int)($row['vm_coins_balance'] ?? 0) : 0;

    if (function_exists('vmc_get_balance')) {
        try {
            $balance = vmc_get_balance($pdo, $userId);
        } catch (Throwable $e) {
            // fallback above
        }
    }

    vmc_live_json([
        'ok' => true,
        'balance' => $balance,
        'earned_total' => $hasEarned ? (int)($row['vm_coins_earned_total'] ?? 0) : 0,
        'spent_total' => $hasSpent ? (int)($row['vm_coins_spent_total'] ?? 0) : 0,
        'updated_at' => $hasUpdated ? (string)($row['vm_coins_updated_at'] ?? '') : null,
        'server_time' => date('Y-m-d H:i:s'),
    ]);
} catch (Throwable $e) {
    vmc_live_json([
        'ok' => false,
        'error' => 'server',
    ], 500);
}