<?php
/**
 * Agentic Square - High-Performance Transactional Processing Console
 * Path: buy-now.php (Main Directory)
 * Core Compliance: Restricted Secure Member Account Interface
 */

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

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

/**
 * STRICT ACCESS GUARD CONTEXT INTERCEPTOR
 */
if (!isset($_SESSION['user_id'])) {
    $current_id = isset($_GET['item_id']) ? (int)$_GET['item_id'] : 0;
    $_SESSION['redirect_on_auth'] = app_url('buy-now.php?item_id=' . $current_id);
    header('Location: ' . app_url('login.php?error=authentication_required'));
    exit;
}

// Extract product identification attributes safely
$item_id = isset($_GET['item_id']) ? (int)$_GET['item_id'] : 0;

if ($item_id <= 0) {
    header('Location: ' . app_url('index.php'));
    exit;
}

/**
 * PAYMENT UTILITY SETTINGS LOADER
 */
function getPaymentGatewaysConfig($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;
    }
}

// Fetch active payment settings properties
$paypal_status = getPaymentGatewaysConfig($pdo, 'paypal_status', 'inactive');
$stripe_status = getPaymentGatewaysConfig($pdo, 'stripe_status', 'inactive');

// Stop processing if absolutely zero gateways are active globally
$gateways_available = ($paypal_status === 'active' || $stripe_status === 'active');

try {
    /**
     * TARGET SPECIFICATION DATA RECOVERY MATRIX
     */
    $stmt = $pdo->prepare("
        SELECT i.*, c.category_name, s.user_id AS seller_user_id, s.seller_name 
        FROM items i 
        LEFT JOIN categories c ON i.category_id = c.id 
        LEFT JOIN sellers s ON i.seller_id = s.id 
        WHERE i.id = ? AND i.status = 'active' 
        LIMIT 1
    ");
    $stmt->execute([$item_id]);
    $item = $stmt->fetch();

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

    /**
     * VISITOR DATA HYDRATION LAYER
     */
    $userStmt = $pdo->prepare("SELECT email FROM users WHERE id = ? LIMIT 1");
    $userStmt->execute([$_SESSION['user_id']]);
    $currentUser = $userStmt->fetch();

    $customer_name  = $_SESSION['user_name'] ?? 'Authorized Buyer'; 
    $customer_email = $currentUser['email'] ?? ($_SESSION['user_email'] ?? 'consumer@domain.local');
    $customer_phone = '';

    /**
     * LIVE SNAPSHOT CAPTURE: GLOBAL COMMISSION INFRASTRUCTURE SETTINGS
     */
    $settingsStmt = $pdo->query("SELECT commission_type, commission_rate, transaction_fee_rate FROM general_settings WHERE id = 1 LIMIT 1");
    $globalSettings = $settingsStmt->fetch();

    $current_commission_type = $globalSettings['commission_type'] ?? 'percentage';
    $current_commission_rate = (float)($globalSettings['commission_rate'] ?? 0.00);
    $current_transaction_fee_rate = max(0.00, (float)($globalSettings['transaction_fee_rate'] ?? 0.00));
    $gross_item_price = (float)$item['amount'];
    $transaction_fee_amount = round(($gross_item_price * $current_transaction_fee_rate) / 100, 2);
    $total_payable_amount = round($gross_item_price + $transaction_fee_amount, 2);

	} catch (Exception $e) {
    die("Core Gateway Trace Exception Interruption: " . htmlspecialchars($e->getMessage()));
}

$error_msg = '';

/**
 * COMMITMENT POST SUBMISSION PARSER
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_transaction'])) {
    $input_phone   = trim($_POST['customer_phone'] ?? '');
    $input_gateway = trim($_POST['payment_method'] ?? '');

    if (!$gateways_available) {
        $error_msg = "Transaction terminated. No external gateway channels are currently configured by the systems operator.";
    } elseif (empty($input_gateway)) {
        $error_msg = "Please select an active checkout processing method to complete execution.";
    } elseif (($input_gateway === 'PayPal' && $paypal_status !== 'active') || ($input_gateway === 'Stripe' && $stripe_status !== 'active')) {
        $error_msg = "The chosen checkout infrastructure method is unavailable. Please select another payment route.";
    } else {
        try {
            /**
             * DYNAMIC TRANSACTION COMMISSIONS AND ALLOCATION BALANCING ENGINE
             */
	            $calculated_deduction = 0.00;

            if ($current_commission_type === 'percentage') {
                $calculated_deduction = ($gross_item_price * $current_commission_rate) / 100;
            } else {
                $calculated_deduction = $current_commission_rate; // Flat fee deduction execution
            }

            // Enforce minimum floor limits to prevent negative allocation anomalies
            $net_seller_income = max(0.00, $gross_item_price - $calculated_deduction);

            /**
             * SECURE ORDER PERSISTENCE CALL WITH COMPREHENSIVE REVENUE RECONCILIATION
             */
            $orderInsert = $pdo->prepare("
                INSERT INTO orders (
                    user_id, customer_name, customer_email, customer_phone, 
	                    item_id, item_name, seller_id, price, transaction_fee_rate, transaction_fee_amount, total_amount, payment_method,
	                    commission_type, commission_rate, net_seller_income, payment_status
	                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	            ");
	            
	            // Exactly 16 elements mapping cleanly to exactly 16 placeholders:
	            $orderInsert->execute([
	                (int)$_SESSION['user_id'],      // 1. user_id
                $customer_name,                 // 2. customer_name
                $customer_email,                // 3. customer_email
                $input_phone,                   // 4. customer_phone
                (int)$item['id'],               // 5. item_id
	                $item['item_name'],             // 6. item_name
	                (int)$item['seller_user_id'],   // 7. seller_id
	                $gross_item_price,              // 8. price
	                $current_transaction_fee_rate,  // 9. transaction_fee_rate
	                $transaction_fee_amount,        // 10. transaction_fee_amount
	                $total_payable_amount,          // 11. total_amount
	                $input_gateway,                 // 12. payment_method
	                $current_commission_type,       // 13. commission_type
	                $current_commission_rate,       // 14. commission_rate
	                $net_seller_income,             // 15. net_seller_income
	                'Pending'                       // 16. payment_status
	            ]);

            $order_id = $pdo->lastInsertId();
            
            // Route seamlessly over to process workflows
            header('Location: ' . app_url('checkout-process.php?order_id=' . $order_id . '&gateway=' . urlencode($input_gateway)));
            exit;

        } catch (Exception $e) {
            $error_msg = "Order Transaction Pipeline Error Exception: " . $e->getMessage();
        }
    }
}

// Construct User Interface Frame Stack Order
require_once __DIR__ . '/sections/header.php';
require_once __DIR__ . '/sections/navbar.php';
?>

<div class="bg-nftDark text-white antialiased min-h-screen pt-28 pb-20">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
        
        <div class="flex items-center space-x-2 text-xs font-bold uppercase tracking-widest text-nftTextGray">
            <a href="<?php echo htmlspecialchars(app_url('index.php'), ENT_QUOTES, 'UTF-8'); ?>" class="hover:text-nftAccentCyan transition-colors">Marketplace</a>
            <span>/</span>
            <span class="hover:text-nftAccentCyan transition-colors"><?php echo htmlspecialchars($item['item_name']); ?></span>
            <span>/</span>
            <span class="text-nftAccentCyan">Checkout Billing Module</span>
        </div>

        <div>
            <h1 class="text-3xl font-black tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-white to-nftAccentPurple">Billing &amp; Acquisition Invoice Checkout</h1>
            <p class="text-xs text-nftTextGray mt-1">Please inspect and verify purchase order details before authorizing network transactional processing.</p>
        </div>

        <?php if (!empty($error_msg)): ?>
            <div class="p-4 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs font-mono text-rose-400 flex items-center gap-2.5">
                <i class="fa-solid fa-triangle-exclamation text-base"></i> <?php echo htmlspecialchars($error_msg); ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="" class="grid grid-cols-1 lg:grid-cols-5 gap-8 items-stretch">
            
            <div class="lg:col-span-3 flex flex-col justify-between space-y-6">
                
                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-xl flex-1">
                    <h3 class="text-xs font-bold uppercase text-nftAccentCyan tracking-wider border-b border-slate-900 pb-3">// Customer Identity Profiling Card</h3>
                    
                    <div class="grid grid-cols-1 gap-4 text-xs">
                        <div class="grid grid-cols-2 gap-2 bg-slate-950/40 p-3 rounded-xl border border-slate-900">
                            <div>
                                <span class="text-nftTextGray block mb-0.5">User Account Session ID</span>
                                <span class="font-mono font-bold text-white">#<?php echo str_pad($_SESSION['user_id'], 5, '0', STR_PAD_LEFT); ?></span>
                            </div>
                            <div>
                                <span class="text-nftTextGray block mb-0.5">Assigned Core Email</span>
                                <span class="text-slate-300 font-semibold truncate block"><?php echo htmlspecialchars($customer_email); ?></span>
                            </div>
                        </div>

                        <div class="space-y-1.5">
                            <label class="text-nftTextGray font-bold uppercase tracking-wide block">Customer Full Name Reference</label>
                            <input type="text" readonly value="<?php echo htmlspecialchars(htmlspecialchars_decode($customer_name, ENT_QUOTES)); ?>" class="w-full bg-slate-950/60 border border-slate-900/80 rounded-xl px-4 py-3 text-slate-400 font-medium text-xs focus:outline-none cursor-not-allowed">
                        </div>

                        <div class="space-y-1.5">
                            <label class="text-nftTextGray font-bold uppercase tracking-wide block">Contact Phone Number</label>
                            <input type="text" name="customer_phone" value="<?php echo htmlspecialchars($customer_phone); ?>" class="w-full bg-slate-950 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-white text-xs font-mono transition-colors" placeholder="+1 (555) 000-0000">
                        </div>
                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-xl">
                    <h3 class="text-xs font-bold uppercase text-nftAccentPurple tracking-wider border-b border-slate-900 pb-3">// Transaction Checkout Settlement Framework</h3>
                    
                    <?php if (!$gateways_available): ?>
                        <div class="p-4 bg-amber-500/5 border border-amber-500/10 rounded-xl text-center text-xs text-amber-400 font-medium">
                            <i class="fa-solid fa-circle-nodes block text-lg mb-2 opacity-60"></i>
                            Offline Framework Status: No payment gateways are currently active. Please contact site administration.
                        </div>
                    <?php else: ?>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            
                            <?php if ($paypal_status === 'active'): ?>
                                <label class="relative flex items-center justify-between p-4 bg-slate-950 border border-slate-900 rounded-xl cursor-pointer hover:border-blue-500/40 selection-payment-gateway group transition-all">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-9 h-9 bg-blue-500/10 border border-blue-500/20 text-blue-400 rounded-lg flex items-center justify-center text-base">
                                            <i class="fa-brands fa-paypal"></i>
                                        </div>
                                        <div>
                                            <span class="text-xs font-bold block text-white">PayPal Central Terminal</span>
                                            <span class="text-[10px] text-nftTextGray">Smart account settlement</span>
                                        </div>
                                    </div>
                                    <input type="radio" name="payment_method" value="PayPal" checked class="accent-nftAccentCyan h-3.5 w-3.5">
                                </label>
                            <?php endif; ?>

                            <?php if ($stripe_status === 'active'): ?>
                                <label class="relative flex items-center justify-between p-4 bg-slate-950 border border-slate-900 rounded-xl cursor-pointer hover:border-indigo-500/40 selection-payment-gateway group transition-all">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-9 h-9 bg-indigo-500/10 border border-indigo-500/20 text-indigo-400 rounded-lg flex items-center justify-center text-base">
                                            <i class="fa-brands fa-stripe-s"></i>
                                        </div>
                                        <div>
                                            <span class="text-xs font-bold block text-white">Stripe Credit Processing</span>
                                            <span class="text-[10px] text-nftTextGray">Inline card clearance</span>
                                        </div>
                                    </div>
                                    <input type="radio" name="payment_method" value="Stripe" <?php echo ($paypal_status !== 'active') ? 'checked' : ''; ?> class="accent-nftAccentCyan h-3.5 w-3.5">
                                </label>
                            <?php endif; ?>

                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="lg:col-span-2 flex flex-col h-full">
                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-5 shadow-xl bg-gradient-to-b from-slate-950/40 to-slate-950/90 flex flex-col justify-between h-full flex-1">
                    
                    <div class="space-y-5">
                        <h3 class="text-xs font-bold uppercase text-slate-400 tracking-wider border-b border-slate-900 pb-3">// Order Valuation Overview</h3>
                        
                        <div class="space-y-4 text-xs font-medium">
                            <div class="space-y-1 bg-slate-950 p-3 rounded-xl border border-slate-900">
                                <span class="text-[10px] uppercase text-nftTextGray block">Acquisition Target Asset Name</span>
                                <span class="text-white font-bold block text-sm truncate" title="<?php echo htmlspecialchars($item['item_name']); ?>">
                                    <?php echo htmlspecialchars($item['item_name']); ?>
                                </span>
                                <span class="text-[10px] font-mono text-nftAccentCyan block mt-1">Item Reference Registry ID: #<?php echo htmlspecialchars($item['id']); ?></span>
                            </div>

                            <div class="divide-y divide-slate-900">
                                <div class="flex items-center justify-between py-2.5">
                                    <span class="text-nftTextGray">Vendor User ID</span>
                                    <span class="font-mono text-slate-300">#USER-<?php echo str_pad($item['seller_user_id'], 5, '0', STR_PAD_LEFT); ?></span>
                                </div>
                                <div class="flex items-center justify-between py-2.5">
                                    <span class="text-nftTextGray">Order Settlement State</span>
                                    <span class="bg-amber-500/10 border border-amber-500/20 text-amber-400 font-mono font-bold text-[10px] px-2 py-0.5 rounded uppercase">Pending Authorization</span>
                                </div>
	                                <div class="flex items-center justify-between py-2.5">
	                                    <span class="text-nftTextGray">Item License Price</span>
	                                    <span class="font-mono text-white font-bold"><?php echo htmlspecialchars(format_currency($gross_item_price), ENT_QUOTES, 'UTF-8'); ?></span>
	                                </div>
	                                <div class="flex items-center justify-between py-2.5">
	                                    <span class="text-nftTextGray">Transaction Fee (<?php echo number_format($current_transaction_fee_rate, 2); ?>%)</span>
	                                    <span class="font-mono text-amber-300 font-bold"><?php echo htmlspecialchars(format_currency($transaction_fee_amount), ENT_QUOTES, 'UTF-8'); ?></span>
	                                </div>
	                                <div class="flex items-center justify-between py-3 border-t border-slate-900">
	                                    <span class="text-sm text-white font-bold">Total Payable Amount</span>
	                                    <span class="text-2xl font-black font-mono text-emerald-400"><?php echo htmlspecialchars(format_currency($total_payable_amount), ENT_QUOTES, 'UTF-8'); ?></span>
	                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="pt-4 lg:pt-0 space-y-3 mt-auto">
                        <button type="submit" name="process_transaction" <?php echo (!$gateways_available) ? 'disabled class="w-full bg-slate-800 text-slate-500 cursor-not-allowed font-extrabold text-xs uppercase tracking-widest text-center py-4 rounded-xl shadow-md"' : 'class="w-full bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple hover:from-nftAccentCyan hover:to-nftAccentPurple/90 text-white font-extrabold text-xs uppercase tracking-widest text-center py-4 rounded-xl shadow-md block transition-all active:scale-[0.99]"'; ?>>
                            <i class="fa-solid fa-lock mr-1.5 text-[10px]"></i> Authorize Payment Request &rarr;
                        </button>
                        <span class="text-[10px] text-nftTextGray text-center block leading-normal">Secured commercial connection pipeline framework protocol. Continuous protection applied.</span>
                    </div>
                    
                </div>
            </div>

        </form>

    </div>
</div>

<?php 
// Finalize Construction Order Stack Pipeline Flow
require_once __DIR__ . '/sections/footer.php';
?>
