<?php
/**
 * Update Payment Details for Binance Order
 * Allows admin to manually add payment details (IBAN, bank name, etc.)
 */

require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/binance-settings.php';

require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: orders.php');
    exit;
}

$orderId = $_POST['order_id'] ?? null;
$orderNo = $_POST['order_no'] ?? null;
$iban = strtoupper(str_replace(' ', '', $_POST['iban'] ?? ''));
$bankName = $_POST['bank_name'] ?? 'Revolut';
$name = $_POST['name'] ?? '';

if (!$orderId || !$orderNo || empty($iban)) {
    $_SESSION['error'] = 'Missing required fields. IBAN is required.';
    header("Location: order-details.php?id=$orderId");
    exit;
}

// Validate IBAN format
if (!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,30}$/', $iban)) {
    $_SESSION['error'] = 'Invalid IBAN format. Please enter a valid IBAN.';
    header("Location: order-details.php?id=$orderId");
    exit;
}

try {
    // Get current order
    $stmt = $pdo->prepare("SELECT * FROM binance_p2p_orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        $_SESSION['error'] = 'Order not found.';
        header('Location: orders.php');
        exit;
    }
    
    // Prepare payment details
    $paymentDetails = [
        'iban' => $iban,
        'bank_name' => $bankName,
        'name' => $name
    ];
    
    // Merge with existing payment details if any
    $existingDetails = $order['payment_details'] ? json_decode($order['payment_details'], true) : [];
    if (is_array($existingDetails)) {
        $paymentDetails = array_merge($existingDetails, $paymentDetails);
    }
    
    // Update order with payment details
    $stmt = $pdo->prepare("
        UPDATE binance_p2p_orders 
        SET payment_details = ?,
            requires_manual_review = 0,
            payment_status = 'pending',
            updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([json_encode($paymentDetails), $orderId]);
    
    // Log the update
    error_log("Payment details manually added for order $orderNo: IBAN=" . substr($iban, 0, 4) . "****");
    
    // Trigger payment processing by including process-payment.php
    // Get order data for processing
    $orderData = json_decode($order['binance_raw_data'], true) ?: [];
    $orderData['payment_details'] = $paymentDetails;
    $orderData['fiatCurrency'] = $order['fiat_currency'];
    $orderData['fiat_amount'] = $order['fiat_amount'];
    $orderData['fiatAmount'] = $order['fiat_amount'];
    
    // Include process-payment.php to trigger automatic payment
    $baseDir = dirname(__DIR__);
    require_once $baseDir . '/api/process-payment.php';
    
    // Process the payment
    $settings = new BinanceP2PSettings($pdo);
    $result = processBinanceOrderPayment($orderId, $orderNo, $orderData, $pdo, $settings);
    
    if ($result['success']) {
        $_SESSION['success'] = 'Payment details saved and payment processing initiated successfully!';
    } else {
        $_SESSION['warning'] = 'Payment details saved, but payment processing failed: ' . ($result['error'] ?? 'Unknown error');
    }
    
    header("Location: order-details.php?id=$orderId");
    exit;
    
} catch (Exception $e) {
    error_log("Error updating payment details: " . $e->getMessage());
    $_SESSION['error'] = 'Error updating payment details: ' . $e->getMessage();
    header("Location: order-details.php?id=$orderId");
    exit;
}

