<?php
/**
 * Agentic Square - Post-Transaction Clearance Landing & Settlement Layer
 * Path: payment-success.php (Main Directory)
 * Core Compliance: Restricted Member Verification, Commission Math & Seller Balance Engine
 */

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;
}

// Retrieve outbound transaction tracking array indices
$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$stripe_session_id = trim($_GET['session_id'] ?? '');

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

try {
    // Begin an isolated database transaction to safeguard monetary metrics
    $pdo->beginTransaction();

    /**
     * TRANSACTION STATUS STATE SETTLER
     * Checks if the order is still 'Pending' for this specific verified customer.
     */
    $checkStmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ? LIMIT 1 FOR UPDATE");
    $checkStmt->execute([$order_id, (int)$_SESSION['user_id']]);
    $order = $checkStmt->fetch();

    if (!$order) {
        $pdo->rollBack();
        header('Location: ' . app_url('index.php?error=order_not_found'));
        exit;
    }

	// If order state is flagged as Pending, commit transactional updates and distribute payouts
	if ($order['payment_status'] === 'Pending') {

        if (($order['payment_method'] ?? '') === 'Stripe') {
            if ($stripe_session_id === '') {
                throw new RuntimeException('Stripe payment verification failed: missing checkout session id.');
            }

            $stripeSecretStmt = $pdo->prepare("SELECT setting_value FROM payment_settings WHERE setting_key = ? LIMIT 1");
            $stripeSecretStmt->execute(['stripe_secret']);
            $stripeSecret = (string)($stripeSecretStmt->fetchColumn() ?: '');

            $stripeSession = stripe_retrieve_checkout_session($stripeSecret, $stripe_session_id);
            $sessionOrderId = (int)($stripeSession['metadata']['order_id'] ?? 0);
            $sessionUserId = (int)($stripeSession['metadata']['user_id'] ?? 0);
            $sessionPaymentStatus = (string)($stripeSession['payment_status'] ?? '');
            $expectedAmount = (int)round((!empty($order['total_amount']) ? (float)$order['total_amount'] : (float)$order['price']) * 100);
            $stripeAmountTotal = (int)($stripeSession['amount_total'] ?? 0);

            if (
                $sessionOrderId !== (int)$order['id']
                || $sessionUserId !== (int)$order['user_id']
                || $sessionPaymentStatus !== 'paid'
                || $stripeAmountTotal !== $expectedAmount
            ) {
                throw new RuntimeException('Stripe payment verification failed. The checkout session does not match this order.');
            }
        }
	        
	        // 1. Mark the primary order record status state to Paid
        $updateOrderStmt = $pdo->prepare("UPDATE orders SET payment_status = 'Paid' WHERE id = ?");
        $updateOrderStmt->execute([$order_id]);

        // 2. Pull global structural commission parameters from general_settings
        $settingsStmt = $pdo->query("SELECT commission_type, commission_rate FROM general_settings WHERE id = 1 LIMIT 1");
        $globalSettings = $settingsStmt->fetch();

        $commission_type = $globalSettings['commission_type'] ?? 'percentage';
        $commission_rate = (float)($globalSettings['commission_rate'] ?? 0.00);

        // Extract payment numbers from item context
	        $order_total = (float)$order['price'];
        $platform_cut = 0.00;

        // Calculate split variables via the correct administrative configuration strategy
        if ($commission_type === 'percentage') {
            $platform_cut = ($order_total * $commission_rate) / 100;
        } elseif ($commission_type === 'fixed') {
            $platform_cut = $commission_rate;
        }

        // Guarantee that the platform split does not exceed the asset's cost boundaries
        if ($platform_cut > $order_total) {
            $platform_cut = $order_total;
        }

	        $seller_payout_yield = isset($order['net_seller_income'])
                ? (float)$order['net_seller_income']
                : ($order_total - $platform_cut);

        // 3. Increment the corresponding vendor record row using user_id from the orders dataset
        // Note: orders table tracks seller_id as the vendor's user_id identifier mapping
        $updateSellerStmt = $pdo->prepare("
            UPDATE sellers 
            SET current_balance = current_balance + :payout, updated_at = NOW() 
            WHERE user_id = :seller_user_id
        ");
        $updateSellerStmt->execute([
            'payout'         => $seller_payout_yield,
            'seller_user_id' => (int)$order['seller_id']
        ]);
    }

    // Commit all structural asset changes smoothly to production tables
    $pdo->commit();

    // Re-fetch the item information matrix data layers for clean workspace views
    $itemStmt = $pdo->prepare("
        SELECT o.*, i.id AS item_registry_id 
        FROM orders o
        LEFT JOIN items i ON o.item_id = i.id
        WHERE o.id = ? LIMIT 1
    ");
    $itemStmt->execute([$order_id]);
	    $orderData = $itemStmt->fetch();
    $orderDisplayTotal = !empty($orderData['total_amount']) ? (float)$orderData['total_amount'] : (float)$orderData['price'];
    $orderTransactionFeeRate = (float)($orderData['transaction_fee_rate'] ?? 0.00);
    $orderTransactionFeeAmount = (float)($orderData['transaction_fee_amount'] ?? 0.00);

} catch (Exception $e) {
    // If anything fails during calculation or writing, immediately restore safe states
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    die("Database State Processing Exception Interruption: " . htmlspecialchars($e->getMessage()));
}

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 flex items-center justify-center">
    <div class="max-w-md w-full px-4 text-center space-y-6">
        
        <div class="glass-card p-8 rounded-3xl border border-slate-800 shadow-2xl space-y-6 relative overflow-hidden bg-gradient-to-b from-slate-950/40 to-slate-950/90">
            <div class="absolute -top-24 -left-24 w-48 h-48 bg-emerald-500/10 blur-3xl rounded-full pointer-events-none"></div>
            
            <div class="w-16 h-16 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 rounded-2xl flex items-center justify-center text-2xl mx-auto shadow-lg shadow-emerald-950/20">
                <i class="fa-solid fa-circle-check animate-bounce"></i>
            </div>

            <div class="space-y-2">
                <h1 class="text-2xl font-black tracking-tight text-white">Payment Authorized Successfully</h1>
                <p class="text-xs text-nftTextGray leading-relaxed px-2">Your payment settlement clearance has completed verification. Invoice state has been securely committed.</p>
            </div>

            <div class="bg-slate-950 p-4 rounded-xl border border-slate-900/80 text-left text-xs space-y-3 font-medium">
                <div class="flex items-center justify-between border-b border-slate-900 pb-2.5">
                    <span class="text-nftTextGray">Transaction Registry ID</span>
                    <span class="font-mono text-white font-bold">#ORD-<?php echo str_pad($orderData['id'], 6, '0', STR_PAD_LEFT); ?></span>
                </div>
                <div class="flex items-center justify-between border-b border-slate-900 pb-2.5">
                    <span class="text-nftTextGray">Acquired Asset Target</span>
                    <span class="text-slate-200 font-semibold truncate max-w-[180px]"><?php echo htmlspecialchars($orderData['item_name']); ?></span>
                </div>
	                <div class="flex items-center justify-between border-b border-slate-900 pb-2.5">
	                    <span class="text-nftTextGray">Item Price</span>
	                    <span class="font-mono font-bold text-white text-sm"><?php echo htmlspecialchars(format_currency($orderData['price']), ENT_QUOTES, 'UTF-8'); ?></span>
	                </div>
	                <div class="flex items-center justify-between border-b border-slate-900 pb-2.5">
	                    <span class="text-nftTextGray">Transaction Fee (<?php echo number_format($orderTransactionFeeRate, 2); ?>%)</span>
	                    <span class="font-mono font-bold text-amber-300 text-sm"><?php echo htmlspecialchars(format_currency($orderTransactionFeeAmount), ENT_QUOTES, 'UTF-8'); ?></span>
	                </div>
	                <div class="flex items-center justify-between border-b border-slate-900 pb-2.5">
	                    <span class="text-nftTextGray">Total Cleared Price</span>
	                    <span class="font-mono font-black text-emerald-400 text-sm"><?php echo htmlspecialchars(format_currency($orderDisplayTotal), ENT_QUOTES, 'UTF-8'); ?></span>
	                </div>
                <div class="flex items-center justify-between pt-0.5">
                    <span class="text-nftTextGray">Database Allocation State</span>
                    <span class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 font-mono font-bold text-[10px] px-2.5 py-0.5 rounded-full uppercase tracking-wider"><i class="fa-solid fa-check text-[8px] mr-1"></i> Paid</span>
                </div>
            </div>

            <div class="pt-2 space-y-3">
                <a href="<?php echo htmlspecialchars(app_url('index.php'), ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-white font-extrabold text-xs uppercase tracking-widest text-center py-3.5 rounded-xl shadow-md block transition-all active:scale-[0.99]">
                    Return To Marketplace Dashboard
                </a>
                <span class="text-[9px] text-nftTextGray block leading-normal font-medium tracking-wide">// Payout Calculated & Transferred to Vendor Balance Registry</span>
            </div>
        </div>
        
    </div>
</div>

<?php 
require_once __DIR__ . '/sections/footer.php';
?>
