<?php
// Telegram Webhook Handler
require_once(__DIR__ . '/config/config.php');
require_once(__DIR__ . '/classes/Database.php');
require_once(__DIR__ . '/classes/TelegramBot.php');
require_once(__DIR__ . '/classes/Payment.php');

// Log all incoming requests
error_log('=== TELEGRAM WEBHOOK ===');
error_log('Request Method: ' . $_SERVER['REQUEST_METHOD']);
error_log('Request Body: ' . file_get_contents('php://input'));

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die('Method not allowed');
}

// Get the incoming update from Telegram
$update = json_decode(file_get_contents('php://input'), true);

if (!$update) {
    error_log('No update received');
    http_response_code(400);
    die('Bad request');
}

error_log('Update received: ' . json_encode($update));

// Get bot token and chat ID from database
$db = Database::getInstance();
$paymentDetails = $db->fetch('SELECT telegram_bot_token, telegram_admin_chat_id FROM payment_details LIMIT 1');

if (!$paymentDetails || empty($paymentDetails['telegram_bot_token'])) {
    error_log('Bot token not configured');
    http_response_code(400);
    die('Bot not configured');
}

// Initialize Telegram bot
$telegram = new TelegramBot($paymentDetails['telegram_bot_token'], $paymentDetails['telegram_admin_chat_id']);

// Handle callback query (button clicks)
if (isset($update['callback_query'])) {
    error_log('Callback query received');
    $callbackQuery = $update['callback_query'];
    $data = $callbackQuery['data'] ?? '';
    
    error_log('Callback data: ' . $data);
    
    // Parse callback data format: action_orderid
    list($action, $orderId) = explode('_', $data, 2);
    
    error_log('Action: ' . $action . ', OrderID: ' . $orderId);
    
    // Get payment order
    $order = $db->fetch('SELECT * FROM payment_orders WHERE order_id = ?', [$orderId]);
    
    if (!$order) {
        error_log('Order not found: ' . $orderId);
        $telegram->sendAdminMessage("❌ Order not found: " . $orderId);
        http_response_code(200);
        die('OK');
    }
    
    error_log('Order found: ' . json_encode($order));
    
    if ($action === 'approve') {
        error_log('Approving payment: ' . $orderId);
        
        // Update order status to approved
        $updated = $db->update('payment_orders',
            ['status' => 'approved'],
            'order_id = ?',
            ['order_id' => $orderId]
        );
        
        if ($updated) {
            error_log('Payment approved successfully');
            
            // Add credits to user's wallet
            $payment = new Payment();
            $result = $payment->addCredits($order['user_id'], $order['amount'], 'Payment approval: ' . $orderId);
            
            if ($result) {
                error_log('Credits added to user wallet');
                $telegram->sendAdminMessage("✅ PAYMENT APPROVED\n\nOrder: " . $orderId . "\nUser ID: " . $order['user_id'] . "\nAmount: ₹" . $order['amount']);
            } else {
                error_log('Failed to add credits');
                $telegram->sendAdminMessage("⚠️ Payment approved but failed to add credits");
            }
        } else {
            error_log('Failed to update payment status');
            $telegram->sendAdminMessage("❌ Failed to approve payment");
        }
    } elseif ($action === 'reject') {
        error_log('Rejecting payment: ' . $orderId);
        
        // Update order status to failed
        $updated = $db->update('payment_orders',
            ['status' => 'failed'],
            'order_id = ?',
            ['order_id' => $orderId]
        );
        
        if ($updated) {
            error_log('Payment rejected successfully');
            $telegram->sendAdminMessage("❌ PAYMENT REJECTED\n\nOrder: " . $orderId . "\nReason: Admin rejected");
        } else {
            error_log('Failed to reject payment');
            $telegram->sendAdminMessage("❌ Failed to reject payment");
        }
    }
    
    // Answer callback query (remove loading state from button)
    $url = 'https://api.telegram.org/bot' . $paymentDetails['telegram_bot_token'] . '/answerCallbackQuery';
    $data = [
        'callback_query_id' => $callbackQuery['id'],
        'text' => 'Processing...',
        'show_alert' => false
    ];
    
    $options = [
        'http' => [
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => http_build_query($data)
        ]
    ];
    
    $context = stream_context_create($options);
    @file_get_contents($url, false, $context);
    
    error_log('Callback answer sent');
}

// Return 200 OK to acknowledge receipt
http_response_code(200);
echo 'OK';
?>
