<?php
/**
 * Manually Generate and Upload Proof Image for Existing Order
 * Usage: php generate-proof-image.php <order_no>
 * Example: php generate-proof-image.php 22830717934168264704
 */

// Enable error display for CLI debugging
if (php_sapi_name() === 'cli') {
    ini_set('display_errors', '1');
    ini_set('log_errors', '1');
    error_reporting(E_ALL);
    ini_set('output_buffering', '0');
    ini_set('session.auto_start', '0');
    
    // Clear any existing output buffers
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
} else {
    // For web requests, suppress output
    ini_set('display_errors', '0');
}

// Prevent execution via web browser (CLI only)
$isWebRequest = (
    isset($_SERVER['HTTP_HOST']) ||
    isset($_SERVER['REQUEST_METHOD']) ||
    (isset($_SERVER['SERVER_SOFTWARE']) && php_sapi_name() !== 'cli')
);

if ($isWebRequest && php_sapi_name() !== 'cli') {
    http_response_code(403);
    die('This script can only be run from command line.');
}

// Get order number from command line argument
$orderNo = $argv[1] ?? null;

if (empty($orderNo)) {
    echo "Usage: php generate-proof-image.php <order_no>\n";
    echo "Example: php generate-proof-image.php 22830717934168264704\n";
    exit(1);
}

// Immediate output to verify script is running
echo "Script started. Processing order: $orderNo\n";
flush();

// Set base directory for includes
$baseDir = dirname(__DIR__);
echo "Base directory: $baseDir\n";
flush();

// Load required files
echo "Loading includes...\n";
flush();
require_once $baseDir . '/includes/config.php';
echo "✓ config.php loaded\n";
flush();
require_once $baseDir . '/includes/binance-api.php';
echo "✓ binance-api.php loaded\n";
flush();
require_once $baseDir . '/includes/binance-settings.php';
echo "✓ binance-settings.php loaded\n";
flush();
require_once $baseDir . '/includes/functions.php';
echo "✓ functions.php loaded\n";
flush();
require_once $baseDir . '/includes/proof-image-generator.php';
echo "✓ proof-image-generator.php loaded\n";
flush();

set_time_limit(120); // 2 minutes timeout

// Function to log and echo for testing
function genLog($message) {
    error_log($message);
    echo $message . "\n";
}

genLog("=== Generate Proof Image for Order $orderNo ===");

try {
    $settings = new BinanceP2PSettings($pdo);
    
    // Get order details from database
    genLog("Fetching order details from database...");
    $stmt = $pdo->prepare("
        SELECT 
            id, 
            order_no, 
            payment_details, 
            fiat_currency, 
            fiat_amount,
            usdc_amount_sent,
            exchange_rate_used,
            bridge_transfer_id,
            tx_hash,
            payment_processed_at
        FROM binance_p2p_orders
        WHERE order_no = ?
    ");
    $stmt->execute([$orderNo]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        genLog("ERROR: Order $orderNo not found in database");
        exit(1);
    }
    
    genLog("Order found:");
    genLog("  - Order ID: " . $order['id']);
    genLog("  - Order Status: " . ($order['order_status'] ?? 'N/A'));
    genLog("  - Payment Processed At: " . ($order['payment_processed_at'] ?? 'N/A'));
    
    // Parse payment details
    $paymentDetails = json_decode($order['payment_details'] ?? '{}', true);
    $receiverName = $paymentDetails['name'] ?? $paymentDetails['receiver_name'] ?? $paymentDetails['account_holder_name'] ?? 'N/A';
    $iban = $paymentDetails['iban'] ?? $paymentDetails['IBAN'] ?? 'N/A';
    $bankName = $paymentDetails['bank_name'] ?? $paymentDetails['Bank Name'] ?? 'N/A';
    
    genLog("Payment Details:");
    genLog("  - Receiver Name: $receiverName");
    genLog("  - IBAN: $iban");
    genLog("  - Bank Name: $bankName");
    
    // Prepare image data
    $imageData = [
        'date' => $order['payment_processed_at'] ?? date('Y-m-d H:i:s'),
        'usdc_amount' => floatval($order['usdc_amount_sent'] ?? 0),
        'eur_amount' => floatval($order['fiat_amount'] ?? 0),
        'exchange_rate' => $order['exchange_rate_used'] ?? 'N/A',
        'bridge_transfer_id' => $order['bridge_transfer_id'] ?? 'N/A',
        'receiver_name' => $receiverName,
        'iban' => $iban,
        'bank_name' => $bankName,
        'sepa_instant' => false // Default to false (safer assumption)
    ];
    
    genLog("Image Data Prepared:");
    genLog("  - Date: " . $imageData['date']);
    genLog("  - USDC Amount: " . $imageData['usdc_amount']);
    genLog("  - EUR Amount: " . $imageData['eur_amount']);
    genLog("  - Exchange Rate: " . $imageData['exchange_rate']);
    genLog("  - Bridge Transfer ID: " . $imageData['bridge_transfer_id']);
    
    // Create directory for proof images if it doesn't exist
    $proofDir = $baseDir . '/proofs';
    if (!is_dir($proofDir)) {
        mkdir($proofDir, 0755, true);
        genLog("Created proofs directory: $proofDir");
    }
    
    // Generate image
    genLog("Generating proof image...");
    $imagePath = $proofDir . '/proof_' . $orderNo . '_' . time() . '.jpg';
    $imageGenerated = generateProofOfPaymentImage($imageData, $imagePath);
    
    if (!$imageGenerated) {
        genLog("ERROR: Failed to generate image");
        exit(1);
    }
    
    // Verify image file was actually created
    if (!file_exists($imagePath)) {
        genLog("ERROR: Image file was not created at: $imagePath");
        genLog("Check PHP GD extension and file permissions");
        exit(1);
    }
    
    $fileSize = filesize($imagePath);
    genLog("✓ Image generated successfully: $imagePath");
    genLog("  - File size: " . number_format($fileSize / 1024, 2) . " KB");
    
    // Get Binance API credentials
    $apiKey = $settings->getBinanceApiKey();
    $secretKey = $settings->getBinanceSecretKey();
    
    if (empty($apiKey) || empty($secretKey)) {
        genLog("ERROR: Binance API credentials not configured");
        exit(1);
    }
    
    $binance = new BinanceP2PAPI($apiKey, $secretKey);
    
    // Get pre-signed URL
    genLog("Requesting pre-signed URL from Binance...");
    genLog("Note: This endpoint is limited to 36 requests per minute per user");
    
    // Generate image name from order number and timestamp
    $imageName = 'proof_' . $orderNo . '_' . time() . '.jpg';
    genLog("Image name: $imageName");
    
    $presignedResult = $binance->getImagePreSignedUrl($imageName);
    
    if (isset($presignedResult['error'])) {
        genLog("ERROR getting pre-signed URL: " . $presignedResult['error']);
        if (isset($presignedResult['code'])) {
            genLog("Error Code: " . $presignedResult['code']);
        }
        if (isset($presignedResult['http_code'])) {
            genLog("HTTP Code: " . $presignedResult['http_code']);
        }
        if (isset($presignedResult['response'])) {
            genLog("Full Response: " . json_encode($presignedResult['response'], JSON_PRETTY_PRINT));
        }
        genLog("");
        genLog("Possible causes:");
        genLog("1. API key doesn't have permission for chat/image endpoint");
        genLog("2. Rate limit exceeded (36 requests/minute)");
        genLog("3. API key restrictions (IP whitelist, etc.)");
        genLog("4. This endpoint may require P2P Merchant API key (not regular API key)");
        genLog("");
        genLog("NOTE: Image was generated successfully but NOT uploaded.");
        genLog("Image saved at: $imagePath");
        genLog("You can manually upload this image or check API key permissions.");
        genLog("");
        genLog("To fix:");
        genLog("1. Check Binance API key permissions - ensure P2P/C2C features are enabled");
        genLog("2. Verify you're using a P2P Merchant API key (not regular trading API key)");
        genLog("3. Check if IP whitelist is enabled and includes your server IP");
        genLog("4. Wait 1 minute and try again (rate limit: 36/min)");
        // Don't delete the image - keep it for manual upload or debugging
        exit(1);
    }
    
    $preSignedUrl = $presignedResult['preSignedUrl'] ?? null;
    $imageUrl = $presignedResult['imageUrl'] ?? null;
    
    if (!$preSignedUrl || !$imageUrl) {
        genLog("ERROR: Invalid response from pre-signed URL API");
        genLog("Response: " . json_encode($presignedResult, JSON_PRETTY_PRINT));
        genLog("");
        genLog("NOTE: Image was generated successfully but NOT uploaded.");
        genLog("Image saved at: $imagePath");
        // Don't delete the image - keep it for manual upload or debugging
        exit(1);
    }
    
    genLog("✓ Pre-signed URL received");
    genLog("  - Pre-signed URL: " . substr($preSignedUrl, 0, 100) . "...");
    genLog("  - Image URL: $imageUrl");
    
    // Upload image to pre-signed URL
    genLog("Uploading image to Binance...");
    $uploadResult = $binance->uploadImageToPreSignedUrl($preSignedUrl, $imagePath);
    
    if (!$uploadResult['success']) {
        genLog("ERROR uploading image: " . ($uploadResult['error'] ?? 'Unknown error'));
        genLog("");
        genLog("NOTE: Image was generated successfully but upload failed.");
        genLog("Image saved at: $imagePath");
        genLog("You can manually upload this image or retry later.");
        // Don't delete the image - keep it for manual upload or debugging
        exit(1);
    }
    
    genLog("✓ Image uploaded successfully to Binance");
    
    // Store image URL in database
    genLog("Saving image URL to database...");
    $stmt = $pdo->prepare("
        UPDATE binance_p2p_orders
        SET proof_image_url = ?,
            updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$imageUrl, $order['id']]);
    
    genLog("✓ Image URL saved to database");
    
    // Clean up local image file after upload
    if (file_exists($imagePath)) {
        @unlink($imagePath);
        genLog("✓ Local image file cleaned up");
    }
    
    genLog("=== SUCCESS ===");
    genLog("Proof image generated and uploaded successfully!");
    genLog("Image URL: $imageUrl");
    genLog("You can now test sending it using: php api/test-send-image.php $orderNo");
    
    // Clean output buffer
    if (php_sapi_name() === 'cli' && ob_get_level() > 0) {
        ob_end_clean();
    }
    
} catch (Exception $e) {
    genLog("FATAL ERROR: " . $e->getMessage());
    genLog("Stack trace: " . $e->getTraceAsString());
    
    if (php_sapi_name() === 'cli' && ob_get_level() > 0) {
        ob_end_clean();
    }
    
    exit(1);
}

