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

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Start logging
error_log("=== PURCHASE VERIFICATION 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'));

// Verify API Hash
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 verification): " . $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'] ?? '';
$purchaseToken = $input['purchase_token'] ?? '';
$orderId = $input['order_id'] ?? '';

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

// Validate input
if (empty($token) || empty($productId) || empty($purchaseToken) || empty($orderId)) {
    error_log("❌ Missing required fields");
    sendError('Token, product_id, purchase_token, and order_id are required');
}

// Verify JWT token
$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 {
    // Get package details first
    $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));
    
    // Verify with Google Play (simplified - in production, use Google Play Developer API)
    // For now, we'll trust the client and verify the purchase token format
    // Google Play purchase tokens can contain letters, numbers, dots, hyphens, and underscores
    if (!preg_match('/^[A-Za-z0-9._-]+$/', $purchaseToken)) {
        error_log("❌ Invalid purchase token format");
        sendError('Invalid purchase token', 400);
    }
    
    // Check if purchase already exists by purchase_token or order_id
    $stmt = $pdo->prepare("SELECT id, status FROM coin_purchases WHERE purchase_token = ? OR order_id = ?");
    $stmt->execute([$purchaseToken, $orderId]);
    $existingPurchase = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existingPurchase) {
        if ($existingPurchase['status'] === 'completed') {
            error_log("❌ Purchase already completed");
            sendError('Purchase already completed', 409);
        } else {
            error_log("⚠️ Purchase exists but not completed, updating...");
        }
    }
    
    // Check if there's a pending purchase for this user and product (created by initiate_purchase)
    if (!$existingPurchase) {
        $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]);
        $pendingPurchase = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($pendingPurchase) {
            error_log("✅ Found pending purchase ID: " . $pendingPurchase['id'] . ", will update it");
            $existingPurchase = $pendingPurchase;
        }
    }
    
    // Start transaction
    $pdo->beginTransaction();
    error_log("Database transaction started");
    
    if ($existingPurchase) {
        // Update existing purchase (either by token/order_id or pending purchase)
        $stmt = $pdo->prepare("
            UPDATE coin_purchases 
            SET purchase_token = ?, order_id = ?, status = 'completed', purchase_time = NOW(), updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$purchaseToken, $orderId, $existingPurchase['id']]);
        $purchaseId = $existingPurchase['id'];
        error_log("Updated existing purchase ID: " . $purchaseId);
    } else {
        // Create new purchase record (fallback - should not happen if initiate_purchase was called)
        $stmt = $pdo->prepare("
            INSERT INTO coin_purchases (user_id, package_id, product_id, purchase_token, order_id, coins, price, currency, status, purchase_time, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, 'EUR', 'completed', NOW(), NOW())
        ");
        $stmt->execute([$userId, $package['id'], $productId, $purchaseToken, $orderId, $package['coins'], $package['price']]);
        $purchaseId = $pdo->lastInsertId();
        error_log("Created new purchase ID: " . $purchaseId);
    }
    
    // Add coins to user
    $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
    $updateResult = $stmt->execute([$package['coins'], $userId]);
    error_log("Update users result: " . ($updateResult ? "SUCCESS" : "FAILED"));
    
    // Add transaction record
    $stmt = $pdo->prepare("
        INSERT INTO transactions (user_id, type, amount, coin_type, description, created_at) 
        VALUES (?, 'purchase', ?, 'regular', 'Coin package purchase: " . $package['name'] . "', NOW())
    ");
    $transactionResult = $stmt->execute([$userId, $package['coins']]);
    error_log("Insert transactions result: " . ($transactionResult ? "SUCCESS" : "FAILED"));
    
    $pdo->commit();
    error_log("Database transaction committed successfully");
    
    // Get updated user data
    $stmt = $pdo->prepare("SELECT coins, free_coins FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userAfter = $stmt->fetch(PDO::FETCH_ASSOC);
    error_log("User data after purchase: " . json_encode($userAfter));
    
    $responseData = [
        'purchase_id' => $purchaseId,
        'package_name' => $package['name'],
        'coins_added' => $package['coins'],
        'total_coins' => $userAfter['coins'],
        'total_free_coins' => $userAfter['free_coins']
    ];
    
    $response = [
        'success' => true,
        'message' => 'Purchase verified and coins added successfully',
        'data' => $responseData
    ];
    
    error_log("✅ Success response: " . json_encode($response));
    error_log("=== PURCHASE VERIFICATION API CALL END ===");
    
    notifyAdminCoinPurchase(
        $pdo,
        $userId,
        $purchaseId,
        $package['name'],
        $package['coins'],
        $package['price'],
        'completed',
        [
            'order_id' => $orderId,
            'purchase_token' => $purchaseToken,
            'total_coins' => $userAfter['coins'],
            'additional_note' => 'سکه‌ها با موفقیت به حساب کاربر اضافه شد.'
        ]
    );

    try {
        $stmt = $pdo->prepare("SELECT full_name, email FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $emailUser = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($emailUser && !empty($emailUser['email'])) {
            sendSystemEmail(
                $pdo,
                'purchase_success',
                $emailUser['email'],
                [
                    'full_name' => $emailUser['full_name'],
                    'item_name' => $package['name'],
                    'quantity' => '1',
                    'amount_text' => number_format($package['coins']) . ' سکه'
                ],
                [
                    'triggered_by' => 'api_verify_purchase',
                    'context' => ['purchase_id' => $purchaseId, 'user_id' => $userId]
                ]
            );
        }
    } catch (Exception $e) {
        error_log("Purchase success email error: " . $e->getMessage());
    }
    
    sendResponse($response);
    
} catch (Exception $e) {
    error_log("❌ Exception occurred: " . $e->getMessage());
    error_log("Exception stack trace: " . $e->getTraceAsString());
    
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
        error_log("Database transaction rolled back");
    }
    
    error_log("=== PURCHASE VERIFICATION API CALL END WITH ERROR ===");
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>
