<?php
/**
 * Get current user info
 */
require_once 'config.php';

// v27.52: only a Telegram-verified identity may reach this endpoint when
// MINIAPP_REQUIRE_INITDATA is on (default). config.php already enforces that,
// but we double-check here because this endpoint can MINT a signup bonus.
$verifiedUid = function_exists('miniapp_authenticated_user_id') ? miniapp_authenticated_user_id() : 0;

$userId = $_GET['user_id'] ?? $_POST['user_id'] ?? null;

if (!$userId) {
    echo json_encode(['ok' => false, 'error' => 'user_id required'], JSON_UNESCAPED_UNICODE);
    exit;
}

$userId = (int)$userId;

// If identity verification is required, never create a bonus-bearing account
// for an unverified caller. (Reading is also blocked centrally; this is defense in depth.)
$bonusAllowed = ($verifiedUid === $userId);

// Get user
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    // Signup bonus (configurable, one-time, atomic).
    $signupBonus = (int)(function_exists('getSetting') ? getSetting('signup_bonus_toman', '15000') : '15000');
    if (!$bonusAllowed) $signupBonus = 0; // unverified callers get no money

    $isNewUser = true;

    // Atomic insert. INSERT IGNORE guarantees that two concurrent requests for the
    // same new user cannot both create the account (and thus cannot double-credit).
    $ins = $pdo->prepare("INSERT IGNORE INTO users (id, balance) VALUES (?, ?)");
    $ins->execute([$userId, $signupBonus]);
    $createdNow = $ins->rowCount() === 1;

    // Only record the gift transaction if WE actually created the row AND a bonus was granted.
    if ($createdNow && $signupBonus > 0) {
        $stmt = $pdo->prepare("
            INSERT INTO wallet_transactions (user_id, amount, type, status, description)
            VALUES (?, ?, 'ADMIN', 'COMPLETED', 'هدیه ثبت‌نام')
        ");
        $stmt->execute([$userId, $signupBonus]);
    }

    // Re-read authoritative balance (handles the race where another request created it).
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch() ?: [
        'id' => $userId, 'username' => null, 'first_name' => null,
        'balance' => $signupBonus, 'is_admin' => 0,
    ];
    $user['is_admin'] = isAdmin($userId) ? 1 : (int)($user['is_admin'] ?? 0);

    // Only send the welcome message if we are the request that actually created the account.
    if ($createdNow) {
    // ارسال پیام خوش‌آمد از طریق ربات
    $welcomeMsg = "🎉 **به فروشگاه GEM ACC خوش آمدید!** 🎉\n\n";
    $welcomeMsg .= "سلام کاربر عزیز 👋\n\n";
    $welcomeMsg .= "━━━━━━━━━━━━━━━━━━━━\n";
    $welcomeMsg .= "🎁 **هدیه ویژه ثبت‌نام**\n";
    $welcomeMsg .= "💰 مبلغ **" . number_format($signupBonus) . " تومان** به کیف پول شما اضافه شد.\n";
    $welcomeMsg .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $welcomeMsg .= "🛒 در **GEM ACC** می‌توانید سرویس‌ها و اکانت‌های دیجیتال معتبر تهیه کنید:\n";
    $welcomeMsg .= "🌐 OpenVPN | L2TP\n";
    $welcomeMsg .= "🌀 Windscribe Original\n";
    $welcomeMsg .= "💎 سرویس‌ها و محصولات جدید که به‌زودی اضافه می‌شوند\n\n";
    $welcomeMsg .= "✨ با موجودی هدیه می‌توانید بخشی از هزینه خریدتان را پرداخت کنید و سفارش‌های خود را از بخش «سرویس‌های من» پیگیری کنید.\n\n";
    $welcomeMsg .= "🚀 برای شروع از ربات یا مینی‌اپ استفاده کنید.\n";
    $welcomeMsg .= "🛍 خرید سرویس | 💎 کیف پول | 🎓 آموزش | ❓ سوالات متداول";

    if ($signupBonus <= 0) {
        // No bonus configured: trim the gift lines so the message stays truthful.
        $welcomeMsg = "🎉 **به فروشگاه GEM ACC خوش آمدید!** 🎉\n\nسلام کاربر عزیز 👋\n\n🛍 خرید سرویس | 💎 کیف پول | 🎓 آموزش | ❓ سوالات متداول";
    }

    tg('sendMessage', [
        'chat_id'    => $userId,
        'text'       => $welcomeMsg,
        'parse_mode' => 'Markdown',
    ]);

    // لاگ
    error_log("New user via miniapp: {$userId} bonus={$signupBonus}");
    } // end if($createdNow)
} else {
    $user['is_admin'] = isAdmin($userId) ? 1 : (int)$user['is_admin'];
}

$purchaseStmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_id=? AND status='DELIVERED'");
$purchaseStmt->execute([$userId]);
$successfulPurchases = (int)$purchaseStmt->fetchColumn();
$stars = max(1, min(5, 1 + intdiv($successfulPurchases, 3)));

// Get services count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM deliveries WHERE user_id = ?");
$stmt->execute([$userId]);
$servicesCount = (int)$stmt->fetchColumn();

// Get avatar info
$stmt = $pdo->prepare("SELECT current_avatar FROM user_avatars WHERE user_id = ?");
$stmt->execute([$userId]);
$currentAvatar = (int)$stmt->fetchColumn() ?: 1;

echo json_encode([
    'ok'   => true,
    'data' => [
        'id'                   => (int)$user['id'],
        'username'             => $user['username'],
        'first_name'           => $user['first_name'],
        'credit'               => (int)($user['balance'] ?? 0),
        'is_admin'             => (int)$user['is_admin'],
        'active_services_count'=> $servicesCount,
        'current_avatar'       => $currentAvatar,
        'total_purchases'      => (int)($user['total_purchases'] ?? 0),
        'successful_purchases' => $successfulPurchases,
        'user_rating'          => $stars,
        'user_rating_emoji'    => str_repeat('⭐', $stars),
    ],
], JSON_UNESCAPED_UNICODE);
