<?php
/**
 * Manually Set Proof Image URL for an Order
 * Use this if you have uploaded the image manually or have the image URL from another source
 * 
 * Usage: php manual-set-image-url.php <order_no> <image_url>
 * Example: php manual-set-image-url.php 22830717934168264704 https://static.binance.com/image.jpg
 */

// CRITICAL: Suppress ALL output BEFORE anything else (CLI only)
if (php_sapi_name() === 'cli') {
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ini_set('output_buffering', '0');
    ini_set('session.auto_start', '0');
    
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    
    ob_start();
}

// 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 and image URL from command line arguments
$orderNo = $argv[1] ?? null;
$imageUrl = $argv[2] ?? null;

if (empty($orderNo) || empty($imageUrl)) {
    echo "Usage: php manual-set-image-url.php <order_no> <image_url>\n";
    echo "Example: php manual-set-image-url.php 22830717934168264704 https://static.binance.com/image.jpg\n";
    exit(1);
}

// Set base directory for includes
$baseDir = dirname(__DIR__);

// Load required files
require_once $baseDir . '/includes/config.php';

set_time_limit(30);

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

setLog("=== Manually Set Proof Image URL for Order $orderNo ===");

try {
    // Get order from database
    setLog("Checking order in database...");
    $stmt = $pdo->prepare("
        SELECT id, order_no, proof_image_url
        FROM binance_p2p_orders
        WHERE order_no = ?
    ");
    $stmt->execute([$orderNo]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        setLog("ERROR: Order $orderNo not found in database");
        exit(1);
    }
    
    setLog("Order found (ID: " . $order['id'] . ")");
    if (!empty($order['proof_image_url'])) {
        setLog("Current image URL: " . $order['proof_image_url']);
        setLog("This will be replaced with the new URL.");
    }
    
    // Validate URL format
    if (!filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        setLog("ERROR: Invalid URL format: $imageUrl");
        exit(1);
    }
    
    // Update database
    setLog("Updating database with new image URL...");
    $stmt = $pdo->prepare("
        UPDATE binance_p2p_orders
        SET proof_image_url = ?,
            updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$imageUrl, $order['id']]);
    
    setLog("✓ Image URL saved successfully!");
    setLog("New image URL: $imageUrl");
    setLog("");
    setLog("You can now test sending it using:");
    setLog("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) {
    setLog("FATAL ERROR: " . $e->getMessage());
    setLog("Stack trace: " . $e->getTraceAsString());
    
    if (php_sapi_name() === 'cli' && ob_get_level() > 0) {
        ob_end_clean();
    }
    
    exit(1);
}

