<?php
/**
 * Agentic Square - Gateway Integration Execution Hub & Router
 * Path: checkout-process.php (Main Directory)
 * Core Compliance: Secure Parameter Matrix Handoff Layer
 */

// Initialize Primary Application Execution Configs
require_once __DIR__ . '/config/config.php';
ensure_transaction_fee_schema();
require_once __DIR__ . '/integrations/stripe/stripe-checkout.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * STRICT ACCESS GUARD CONTEXT INTERCEPTOR
 */
if (!isset($_SESSION['user_id'])) {
    header('Location: ' . app_url('login.php?error=authentication_required'));
    exit;
}

// Intercept routing variables safely from dynamic request parameters
$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$gateway  = isset($_GET['gateway']) ? trim($_GET['gateway']) : '';

if ($order_id <= 0 || empty($gateway)) {
    header('Location: ' . app_url('index.php?error=invalid_transaction_parameters'));
    exit;
}

/**
 * PAYMENT UTILITY SETTINGS LOADER
 */
function getProcessorSetting($pdo, $key, $default = '') {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM payment_settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        return $row ? $row['setting_value'] : $default;
    } catch (Exception $e) {
        return $default;
    }
}

try {
    /**
     * VERIFY PENDING ORDER MATRIX STRUCTURE
     */
    $orderStmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ? AND payment_status = 'Pending' LIMIT 1");
    $orderStmt->execute([$order_id, (int)$_SESSION['user_id']]);
    $order = $orderStmt->fetch();

    if (!$order) {
        header('Location: ' . app_url('index.php?error=order_not_eligible'));
        exit;
    }

    // Determine target execution path via structural strategy matching
    if ($gateway === 'PayPal') {
        
        $paypal_status = getProcessorSetting($pdo, 'paypal_status', 'inactive');
        $paypal_email  = getProcessorSetting($pdo, 'paypal_email', '');

        if ($paypal_status !== 'active' || empty($paypal_email)) {
            header('Location: ' . app_url('buy-now.php?item_id=' . $order['item_id'] . '&error=paypal_gateway_offline'));
            exit;
        }

        // Dynamically build clean return and cancel strings pointing to your main directory files
        $return_url = APP_URL . "/payment-success.php?order_id=" . $order['id'];
        $cancel_url = APP_URL . "/cancel-payment.php?order_id=" . $order['id'];

        // Live Production Endpoint Routing
        $paypal_url = "https://www.paypal.com/cgi-bin/webscr";
        
        // Scrub dynamic text variables to ensure strict string compliance
        $payableAmount = !empty($order['total_amount']) ? (float)$order['total_amount'] : (float)$order['price'];
        $clean_amount = number_format($payableAmount, 2, '.', '');
        $clean_email  = trim($paypal_email);
        $clean_item   = trim($order['item_name']);

        $paypal_fields = [
            'cmd'           => '_xclick',
            'business'      => $clean_email,
            'item_name'     => $clean_item,
            'item_number'   => (string)$order['item_id'],
            'amount'        => $clean_amount,
            'currency_code' => get_site_currency(),
            'no_shipping'   => '1',
            'no_note'       => '1',
            // Salted unique custom key pairing prevents PayPal anti-fraud pipeline blockages
            'custom'        => (string)$order['id'] . '_' . time(),
            'return'        => $return_url,
            'cancel_return' => $cancel_url
        ];

        // Output minimalist dark auto-submit execution engine interface
        require_once __DIR__ . '/sections/header.php';
        ?>
        <div class="bg-nftDark text-white antialiased min-h-screen flex items-center justify-center">
            <div class="text-center space-y-4 max-w-sm glass-card p-8 rounded-3xl border border-slate-900 shadow-2xl">
                <div class="w-12 h-12 bg-blue-500/10 border border-blue-500/20 text-blue-400 rounded-xl flex items-center justify-center text-xl mx-auto shadow-md">
                    <i class="fa-brands fa-paypal animate-pulse"></i>
                </div>
                <div class="space-y-1.5">
                    <h3 class="text-sm font-bold uppercase tracking-wider text-white">Opening Secure PayPal Window...</h3>
                    <p class="text-[11px] text-nftTextGray leading-relaxed">Connecting safely to international payment rails. Please do not close or refresh this frame.</p>
                </div>
                
                <form id="paypal_auto_submit_form" action="<?php echo $paypal_url; ?>" method="post" class="hidden">
                    <?php foreach ($paypal_fields as $name => $value): ?>
                        <input type="hidden" name="<?php echo htmlspecialchars($name); ?>" value="<?php echo htmlspecialchars($value); ?>">
                    <?php endforeach; ?>
                </form>
            </div>
        </div>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                document.getElementById('paypal_auto_submit_form').submit();
            });
        </script>
        </body>
        </html>
        <?php
        exit;

	} elseif ($gateway === 'Stripe') {
	        
	        $stripe_status = getProcessorSetting($pdo, 'stripe_status', 'inactive');
	        $stripe_secret = getProcessorSetting($pdo, 'stripe_secret', '');
	        $stripe_key    = getProcessorSetting($pdo, 'stripe_key', '');
            $currency = get_site_currency();
	
	        if ($stripe_status !== 'active' || empty($stripe_secret) || empty($stripe_key)) {
	            header('Location: ' . app_url('buy-now.php?item_id=' . $order['item_id'] . '&error=stripe_gateway_offline'));
	            exit;
	        }
	
            $success_url = APP_URL . "/payment-success.php?order_id=" . $order['id'] . "&session_id={CHECKOUT_SESSION_ID}";
            $cancel_url = APP_URL . "/cancel-payment.php?order_id=" . $order['id'];

            $stripeSession = stripe_create_checkout_session(
                $stripe_secret,
                $order,
                $currency,
                $success_url,
                $cancel_url
            );

            if (empty($stripeSession['url'])) {
                throw new RuntimeException('Stripe checkout session did not return a redirect URL.');
            }

	        header('Location: ' . $stripeSession['url']);
	        exit;

    } else {
        header('Location: ' . app_url('buy-now.php?item_id=' . $order['item_id'] . '&error=unsupported_gateway_framework'));
        exit;
    }

} catch (Exception $e) {
    die("Routing Architecture Interruption Exception: " . htmlspecialchars($e->getMessage()));
}
