<?php
// File: public/api/bootstrap.php
declare(strict_types=1);

use App\{Env, DB, Logger};

require __DIR__.'/../../../src/Env.php';
require __DIR__.'/../../../src/Logger.php';
require __DIR__.'/../../../src/DB.php';

App\Env::load(__DIR__ . '/../../../.env');

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

/**
 * پاسخ استاندارد JSON
 */
function json_ok($data = [], int $code = 200): void {
    http_response_code($code);
    echo json_encode(['ok' => true, 'data' => $data], JSON_UNESCAPED_UNICODE);
    exit;
}

function json_error(string $message, int $code = 400): void {
    http_response_code($code);
    echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * تأیید initData تلگرام WebApp
 * Front باید مقدار window.Telegram.WebApp.initData را بفرستد.
 */
function verify_telegram_webapp(): array {
    $initData = $_POST['initData'] ?? ($_SERVER['HTTP_X_TELEGRAM_INIT_DATA'] ?? null);
    if (!$initData) {
        json_error('Missing initData', 401);
    }

    parse_str($initData, $data);
    if (!isset($data['hash'])) {
        json_error('Invalid initData: no hash', 401);
    }

    $hash = $data['hash'];
    unset($data['hash']);

    ksort($data);
    $checkStringParts = [];
    foreach ($data as $k => $v) {
        $checkStringParts[] = $k . '=' . $v;
    }
    $checkString = implode("\n", $checkStringParts);

    $botToken = Env::get('BOT_TOKEN') ?: Env::get('TELEGRAM_BOT_TOKEN');
    if (!$botToken) {
        json_error('Bot token not configured', 500);
    }

    $secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
    $calcHash = hash_hmac('sha256', $checkString, $secretKey);

    if (isset($data['auth_date']) && (time() - (int)$data['auth_date']) > 86400) {
        json_error('Expired initData', 401);
    }

    if (!hash_equals($calcHash, $hash)) {
        json_error('Invalid initData hash', 401);
    }

    // user فیلد user خودش JSON است
    $userJson = $data['user'] ?? null;
    if (!$userJson) {
        json_error('No user in initData', 401);
    }

    $user = json_decode($userJson, true);
    if (!is_array($user) || !isset($user['id'])) {
        json_error('Invalid user data', 401);
    }

    return $user;
}

/**
 * گرفتن کاربر از DB و تشخیص ادمین
 */
function current_user(): array {
    $tgUser = verify_telegram_webapp();
    $uid = (int)$tgUser['id'];

    $pdo = DB::pdo();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$uid]);
    $row = $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$row) {
        // اگر در DB نبود، بسازیم به عنوان کاربر عادی
        $stmt = $pdo->prepare("INSERT INTO users (id, username, first_name, last_name, is_admin) 
                               VALUES (:id, :un, :fn, :ln, 0)");
        $stmt->execute([
            ':id' => $uid,
            ':un' => $tgUser['username'] ?? null,
            ':fn' => $tgUser['first_name'] ?? null,
            ':ln' => $tgUser['last_name'] ?? null,
        ]);
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$uid]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    $row['tg_raw'] = $tgUser;
    return $row;
}

function require_admin(array $user): void {
    $uid = (int)($user['id'] ?? 0);
    $dbAdmin = (int)($user['is_admin'] ?? 0) === 1;
    if (!$dbAdmin && !function_exists('isAdmin')) {
        require_once __DIR__ . '/config.php';
    }
    if (!$dbAdmin && !(function_exists('isAdmin') && isAdmin($uid))) {
        json_error('Only admin allowed', 403);
    }
}
