<?php
require_once '../../includes/functions.php';
setCORSHeaders();

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

error_log("=== INITIATE PURCHASE API CALL START ===");
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Request Headers: " . json_encode(getallheaders()));
error_log("Request Body: " . file_get_contents('php://input'));

verifyAPIHash();

function notifyAdminCoinPurchase($pdo, $userId, $purchaseId, $packageName, $coins, $price, $status, array $context = [])
{
    try {
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ('telegram_bot_token', 'telegram_admin_id')");
        $settings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
        $botToken = $settings['telegram_bot_token'] ?? '';
        $adminId = $settings['telegram_admin_id'] ?? '';
        if (empty($botToken) || empty($adminId)) {
            return;
        }
        $stmt = $pdo->prepare("SELECT username, full_name, email FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return;
        }
        $statusText = $status === 'completed' ? '✅ وضعیت: پرداخت تکمیل شد' : '⏳ وضعیت: در انتظار پرداخت';
        $header = $status === 'completed' ? '✅ <b>خرید سکه تکمیل شد</b>' : '🆕 <b>خرید سکه جدید ثبت شد</b>';
        $text = "{$header}\n\n";
        $text .= "🆔 <b>شناسه خرید:</b> #{$purchaseId}\n";
        $text .= "👤 <b>کاربر:</b> {$user['full_name']} (@{$user['username']})\n";
        $text .= "📧 <b>ایمیل:</b> {$user['email']}\n";
        $text .= "🎁 <b>پکیج:</b> {$packageName}\n";
        $text .= "💰 <b>سکه:</b> " . number_format($coins) . "\n";
        $text .= "💵 <b>مبلغ:</b> " . number_format($price, 2) . " €\n";
        $text .= "{$statusText}\n";
        if (!empty($context['order_id'])) {
            $text .= "🧾 <b>Order ID:</b> {$context['order_id']}\n";
        }
        if (!empty($context['purchase_token'])) {
            $tokenShort = substr($context['purchase_token'], 0, 8) . '...' . substr($context['purchase_token'], -4);
            $text .= "🔑 <b>Purchase Token:</b> {$tokenShort}\n";
        }
        if (!empty($context['total_coins'])) {
            $text .= "📦 <b>سکه فعلی کاربر:</b> " . number_format($context['total_coins']) . "\n";
        }
        if (!empty($context['additional_note'])) {
            $text .= "{$context['additional_note']}\n";
        }
        $text .= "📅 <b>تاریخ:</b> " . date('Y/m/d H:i');
        $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
        $data = [
            'chat_id' => $adminId,
            'text' => $text,
            'parse_mode' => 'HTML'
        ];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_exec($ch);
        curl_close($ch);
    } catch (Exception $e) {
        error_log("Telegram notification error (coin purchase): " . $e->getMessage());
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_log("❌ Invalid request method");
    sendError('Method not allowed', 405);
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    error_log("❌ Invalid JSON data");
    sendError('Invalid JSON data');
}

$token = $input['token'] ?? '';
$productId = $input['product_id'] ?? '';

error_log("Token: " . substr($token, 0, 20) . "...");
error_log("Product ID: " . $productId);

if (empty($token) || empty($productId)) {
    error_log("❌ Missing required fields");
    sendError('Token and product_id are required');
}

$payload = verifyJWT($token);
if (!$payload) {
    error_log("❌ Invalid JWT token");
    sendError('Invalid or expired token', 401);
}

$userId = $payload['user_id'];
error_log("User ID: " . $userId);

try {
    $stmt = $pdo->prepare("SELECT id, name, coins, price FROM coin_packages WHERE product_id = ? AND is_active = 1");
    $stmt->execute([$productId]);
    $package = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$package) {
        error_log("❌ Package not found for product_id: " . $productId);
        sendError('Package not found', 404);
    }
    
    error_log("Package found: " . json_encode($package));
    
    $stmt = $pdo->prepare("
        SELECT id, status 
        FROM coin_purchases 
        WHERE user_id = ? AND product_id = ? AND (purchase_token IS NULL OR purchase_token = '') AND status = 'pending'
        ORDER BY created_at DESC
        LIMIT 1
    ");
    $stmt->execute([$userId, $productId]);
    $existingPending = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existingPending) {
        error_log("⚠️ Pending purchase already exists, returning existing ID: " . $existingPending['id']);
        $purchaseId = $existingPending['id'];
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO coin_purchases (user_id, package_id, product_id, purchase_token, order_id, coins, price, currency, status, created_at) 
            VALUES (?, ?, ?, NULL, NULL, ?, ?, 'EUR', 'pending', NOW())
        ");
        $stmt->execute([$userId, $package['id'], $productId, $package['coins'], $package['price']]);
        $purchaseId = $pdo->lastInsertId();
        error_log("✅ Created new pending purchase ID: " . $purchaseId);
        
        notifyAdminCoinPurchase(
            $pdo,
            $userId,
            $purchaseId,
            $package['name'],
            $package['coins'],
            $package['price'],
            'pending',
            [
                'additional_note' => 'این خرید در انتظار تأیید پرداخت است.'
            ]
        );
    }
    
    $responseData = [
        'purchase_id' => $purchaseId,
        'product_id' => $productId,
        'package_name' => $package['name'],
        'coins' => $package['coins'],
        'price' => $package['price'],
        'status' => 'pending'
    ];
    
    $response = [
        'success' => true,
        'message' => 'Purchase initiated successfully',
        'data' => $responseData
    ];
    
    error_log("✅ Success response: " . json_encode($response));
    error_log("=== INITIATE PURCHASE API CALL END ===");
    
    sendResponse($response);
    
} catch (Exception $e) {
    error_log("❌ Exception occurred: " . $e->getMessage());
    error_log("Exception stack trace: " . $e->getTraceAsString());
    error_log("=== INITIATE PURCHASE API CALL END WITH ERROR ===");
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>

