<?php
/**
 * Flutterwave Payment Handler
 * Digital Product Store
 */

require_once __DIR__ . '/../config/database.php';
require_login();

$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;

if (!$order_id) {
    set_flash_message('Invalid order.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

$order = get_order_by_id($order_id);

if (!$order || $order['user_id'] != get_current_user_id()) {
    set_flash_message('Order not found.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get Flutterwave settings
$flutterwave = get_payment_gateway('flutterwave');

if (!$flutterwave) {
    set_flash_message('Flutterwave is not configured.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

$config = $flutterwave['config'];
$public_key = $config['public_key'] ?? '';
$secret_key = $config['secret_key'] ?? '';

if (empty($public_key) || empty($secret_key)) {
    set_flash_message('Flutterwave is not properly configured.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

// Generate transaction reference
$tx_ref = $order['order_number'] . '_' . time();

// Store reference
$stmt = $pdo->prepare("UPDATE orders SET payment_id = ? WHERE id = ?");
$stmt->execute([$tx_ref, $order_id]);

// Record transaction
record_payment_transaction($order_id, 'flutterwave', $tx_ref, $order['total']);

$redirect_url = BASE_URL . '/payment/flutterwave-callback.php?order_id=' . $order_id;

// Flutterwave inline payment page
?>
<!DOCTYPE html>
<html>
<head>
    <title>Flutterwave Payment</title>
    <script src="https://checkout.flutterwave.com/v3.js"></script>
</head>
<body>
    <div style="text-align: center; padding: 50px;">
        <h2>Processing Payment...</h2>
        <p>Please wait while we redirect you to Flutterwave...</p>
    </div>
    
    <script>
    window.onload = function() {
        FlutterwaveCheckout({
            public_key: "<?php echo $public_key; ?>",
            tx_ref: "<?php echo $tx_ref; ?>",
            amount: <?php echo $order['total']; ?>,
            currency: "<?php echo get_setting('currency_code', 'USD'); ?>",
            payment_options: "card, banktransfer, ussd",
            redirect_url: "<?php echo $redirect_url; ?>",
            meta: {
                order_id: "<?php echo $order_id; ?>",
                order_number: "<?php echo $order['order_number']; ?>"
            },
            customer: {
                email: "<?php echo $order['customer_email']; ?>",
                name: "<?php echo $order['customer_name']; ?>"
            },
            customizations: {
                title: "<?php echo get_setting('site_name', 'Digital Store'); ?>",
                description: "Order <?php echo $order['order_number']; ?>"
            },
            callback: function(data) {
                window.location.href = "<?php echo $redirect_url; ?>&transaction_id=" + data.transaction_id + "&status=" + data.status;
            },
            onclose: function() {
                window.location.href = "<?php echo BASE_URL; ?>/checkout.php";
            }
        });
    };
    </script>
</body>
</html>
