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

// Verify API Hash using enhanced method
verifyAPIHashEnhanced();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Method not allowed', 405);
}

// Get authorization header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
    sendError('Authorization token required', 401);
}

$token = $matches[1];
$payload = verifyJWT($token);

if (!$payload || !isset($payload['user_id'])) {
    sendError('Invalid or expired token', 401);
}

$userId = $payload['user_id'];

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

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

$productId = (int)($input['product_id'] ?? 0);
$quantity = (int)($input['quantity'] ?? 1);
$telegramLink = trim($input['telegram_link'] ?? '');

if ($productId <= 0) {
    sendError('Invalid product ID');
}

if ($quantity <= 0) {
    sendError('Invalid quantity');
}

if (empty($telegramLink)) {
    sendError('Telegram link is required');
}

// Validate telegram link format
if (!preg_match('/^(https?:\/\/)?t\.me\/[a-zA-Z0-9_]{5,}(\/[0-9]+)?$/', $telegramLink)) {
    sendError('Invalid telegram link format. Please use format: t.me/username or t.me/username/123');
}

// Get product details
$stmt = $pdo->prepare("SELECT id, name, price_coins, coin_type, min_order FROM products WHERE id = ? AND is_active = 1");
$stmt->execute([$productId]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    sendError('Product not found');
}

$minOrder = max(1, (int)($product['min_order'] ?? 1));
if ($quantity < $minOrder) {
    sendError("Minimum order for this product is {$minOrder}");
}

// Get user details
$user = getUserById($userId);
if (!$user) {
    sendError('User not found');
}

$totalCoins = $product['price_coins'] * $quantity;

// Check if user has enough coins based on product type
if ($product['coin_type'] === 'free') {
    if ($user['free_coins'] < $totalCoins) {
        sendError('Insufficient free coins');
    }
} else {
    if ($user['coins'] < $totalCoins) {
        sendError('Insufficient coins');
    }
}

// Start transaction
$pdo->beginTransaction();

try {
    // Create order
    $stmt = $pdo->prepare("INSERT INTO orders (user_id, product_id, quantity, total_coins, coin_type, telegram_link, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')");
    $stmt->execute([$userId, $productId, $quantity, $totalCoins, $product['coin_type'], $telegramLink]);
    $orderId = $pdo->lastInsertId();
    
    // Deduct coins from user based on product type
    if ($product['coin_type'] === 'free') {
        $stmt = $pdo->prepare("UPDATE users SET free_coins = free_coins - ? WHERE id = ?");
        $stmt->execute([$totalCoins, $userId]);
        $transactionType = 'free_purchase';
    } else {
        $stmt = $pdo->prepare("UPDATE users SET coins = coins - ? WHERE id = ?");
        $stmt->execute([$totalCoins, $userId]);
        $transactionType = 'purchase';
    }
    
    // Add transaction record
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, coin_type, description) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$userId, $transactionType, -$totalCoins, $product['coin_type'], "Purchase: {$product['name']} x{$quantity}"]);
    
    $pdo->commit();
    
    // Get updated user data
    $stmt = $pdo->prepare("SELECT coins, free_coins FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $updatedUser = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Get order details for response
    $stmt = $pdo->prepare("SELECT o.id, o.user_id, o.product_id, o.quantity, o.total_coins, o.coin_type, o.telegram_link, o.status, o.created_at, p.name as product_name FROM orders o JOIN products p ON o.product_id = p.id WHERE o.id = ?");
    $stmt->execute([$orderId]);
    $orderData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Send Telegram notification to admin
    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)) {
            $coinTypeText = $orderData['coin_type'] === 'free' ? '⭐ رایگان' : '💰 معمولی';
            $text = "🆕 <b>سفارش جدید ثبت شد!</b>\n\n";
            $text .= "🆔 <b>شناسه سفارش:</b> #{$orderData['id']}\n";
            $text .= "👤 <b>کاربر:</b> {$user['full_name']} (@{$user['username']})\n";
            $text .= "📦 <b>محصول:</b> {$orderData['product_name']}\n";
            $text .= "🔢 <b>تعداد:</b> {$orderData['quantity']}\n";
            $text .= "💵 <b>قیمت:</b> {$orderData['total_coins']} سکه ({$coinTypeText})\n";
            $text .= "🔗 <b>لینک تلگرام:</b> {$orderData['telegram_link']}\n";
            $text .= "📅 <b>تاریخ:</b> " . date('Y/m/d H:i', strtotime($orderData['created_at'])) . "\n";
            
            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => '❌ کنسل و ریفاند', 'callback_data' => "cancel_order_{$orderData['id']}"],
                        ['text' => '📤 ارسال به SMM', 'callback_data' => "send_to_smm_{$orderData['id']}"]
                    ],
                    [
                        ['text' => '💸 ارسال به سرویس ارزان', 'callback_data' => "send_to_cheap_{$orderData['id']}"]
                    ]
                ]
            ];
            
            $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
            $data = [
                'chat_id' => $adminId,
                'text' => $text,
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode($keyboard)
            ];
            
            $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) {
        // Don't fail the order if Telegram notification fails
        error_log("Telegram notification error: " . $e->getMessage());
    }

    try {
        sendSystemEmail(
            $pdo,
            'order_created',
            $user['email'],
            [
                'full_name' => $user['full_name'],
                'order_id' => $orderData['id'],
                'product_name' => $orderData['product_name'],
                'quantity' => $orderData['quantity'],
                'total_coins' => $orderData['total_coins']
            ],
            [
                'triggered_by' => 'api_order_create',
                'context' => ['order_id' => $orderData['id'], 'user_id' => $userId]
            ]
        );
    } catch (Exception $e) {
        error_log("Order created email error: " . $e->getMessage());
    }
    
    sendResponse([
        'success' => true,
        'message' => 'Order completed successfully',
        'data' => [
            'id' => (int)$orderData['id'],
            'user_id' => (int)$orderData['user_id'],
            'product_id' => (int)$orderData['product_id'],
            'quantity' => (int)$orderData['quantity'],
            'total_coins' => (int)$orderData['total_coins'],
            'coin_type' => $orderData['coin_type'],
            'telegram_link' => $orderData['telegram_link'],
            'status' => $orderData['status'],
            'created_at' => $orderData['created_at'],
            'product' => [
                'id' => (int)$orderData['product_id'],
                'name' => $orderData['product_name']
            ]
        ],
        'remaining_coins' => $updatedUser['coins'],
        'remaining_free_coins' => $updatedUser['free_coins']
    ], 201);
    
} catch (Exception $e) {
    $pdo->rollBack();
    sendError('Order failed: ' . $e->getMessage());
}
?>
