<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';
require_once '../includes/payments.php';
require_once '../config/payment_security.php';

PaymentSecurity::setSecurityHeaders();

$db = getDB();
$userId = $_SESSION['user_id'] ?? null;
$user = getUserContext();

// Get lookup parameters
$transactionId = $_GET['txn'] ?? $_GET['transaction_id'] ?? null;
$paypalOrderId = $_GET['token'] ?? null;
$paynowRef = $_GET['ref'] ?? $_GET['reference'] ?? null;

$transaction = null;
$statusMessage = '';
$statusType = '';

if ($paypalOrderId) {
    $stmt = $db->prepare("
        SELECT pt.* FROM payment_transactions pt
        WHERE JSON_EXTRACT(pt.gateway_metadata, '$.paypal_order_id') = ?
        AND pt.user_id = ?
        ORDER BY pt.id DESC LIMIT 1
    ");
    $stmt->execute([$paypalOrderId, $userId]);
    $transaction = $stmt->fetch();

} elseif ($paynowRef) {
    $stmt = $db->prepare("
        SELECT * FROM payment_transactions
        WHERE reference_number = ? AND user_id = ?
        ORDER BY id DESC LIMIT 1
    ");
    $stmt->execute([$paynowRef, $userId]);
    $transaction = $stmt->fetch();

} elseif ($transactionId) {
    $stmt = $db->prepare("
        SELECT * FROM payment_transactions
        WHERE transaction_id = ? AND user_id = ?
        ORDER BY id DESC LIMIT 1
    ");
    $stmt->execute([$transactionId, $userId]);
    $transaction = $stmt->fetch();
}

if (!$transaction) {
    $statusMessage = 'Transaction not found. Please contact support if you believe this is an error.';
    $statusType = 'error';
} else {
    $status = $transaction['status'];
    $gatewayName = $transaction['gateway_name'];

    switch ($status) {
        case 'completed':
            $statusMessage = 'Payment successful! You have been enrolled in your selected courses.';
            $statusType = 'success';
            break;
        case 'failed':
            $statusMessage = 'Payment failed. Please try again or contact support.';
            $statusType = 'error';
            break;
        case 'cancelled':
            $statusMessage = 'Payment was cancelled. You can try again from your cart.';
            $statusType = 'warning';
            break;
        case 'processing':
        case 'pending':
            $statusMessage = 'Payment is being processed. Please wait while we confirm your payment.';
            $statusType = 'info';
            break;
        default:
            $statusMessage = 'Payment status: ' . ucfirst($status);
            $statusType = 'info';
    }
}

// If payment is completed but not yet processed (e.g., webhook hasn't fired), try processing
if ($transaction && $transaction['status'] === 'completed') {
    try {
        $gateway = new PaymentGateway($transaction['gateway_name'], $transaction['gateway_type']);
        $gateway->processSuccessfulPayment($transaction['transaction_id']);
    } catch (Exception $e) {
        error_log('Payment return processing error: ' . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Return | Mutalex Academy</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-slate-50 min-h-screen flex items-center justify-center p-4">
    <div class="max-w-md w-full bg-white rounded-3xl shadow-xl border border-slate-200 p-8 text-center">
        <?php if ($statusType === 'success'): ?>
            <div class="w-20 h-20 bg-green-100 text-green-500 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="fas fa-check-circle text-4xl"></i>
            </div>
            <h2 class="text-2xl font-bold text-slate-900 mb-2">Payment Successful!</h2>
            <p class="text-slate-500 mb-6"><?php echo htmlspecialchars($statusMessage); ?></p>
            <?php if ($transaction): ?>
                <div class="p-4 bg-slate-50 rounded-2xl border border-slate-200 text-left mb-6">
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-slate-500">Transaction ID</span>
                            <span class="font-mono font-bold text-slate-700"><?php echo htmlspecialchars($transaction['transaction_id']); ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-slate-500">Amount</span>
                            <span class="font-bold text-green-600">$<?php echo number_format($transaction['final_amount'], 2); ?></span>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            <a href="courses.php" class="inline-flex items-center justify-center gap-2 px-8 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all">
                <i class="fas fa-graduation-cap"></i> My Courses
            </a>

        <?php elseif ($statusType === 'error'): ?>
            <div class="w-20 h-20 bg-red-100 text-red-500 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="fas fa-times-circle text-4xl"></i>
            </div>
            <h2 class="text-2xl font-bold text-slate-900 mb-2">Payment Failed</h2>
            <p class="text-slate-500 mb-6"><?php echo htmlspecialchars($statusMessage); ?></p>
            <a href="checkout.php" class="inline-flex items-center justify-center gap-2 px-8 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all">
                <i class="fas fa-redo"></i> Try Again
            </a>

        <?php elseif ($statusType === 'warning'): ?>
            <div class="w-20 h-20 bg-yellow-100 text-yellow-600 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="fas fa-exclamation-circle text-4xl"></i>
            </div>
            <h2 class="text-2xl font-bold text-slate-900 mb-2">Payment Cancelled</h2>
            <p class="text-slate-500 mb-6"><?php echo htmlspecialchars($statusMessage); ?></p>
            <a href="checkout.php" class="inline-flex items-center justify-center gap-2 px-8 py-3 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all">
                <i class="fas fa-shopping-cart"></i> Return to Checkout
            </a>

        <?php else: ?>
            <div class="w-20 h-20 bg-blue-100 text-blue-500 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="fas fa-spinner fa-spin text-4xl"></i>
            </div>
            <h2 class="text-2xl font-bold text-slate-900 mb-2">Processing Payment</h2>
            <p class="text-slate-500 mb-6"><?php echo htmlspecialchars($statusMessage); ?></p>
            <p class="text-xs text-slate-400 mb-4">Please do not close this page while we confirm your payment.</p>
            <?php if ($transaction): ?>
                <script>
                    let transactionId = '<?php echo htmlspecialchars($transaction['transaction_id']); ?>';
                    let attempts = 0;
                    const maxAttempts = 20;

                    function checkStatus() {
                        attempts++;
                        fetch('../api/payments.php?transaction_id=' + encodeURIComponent(transactionId))
                            .then(response => response.json())
                            .then(data => {
                                if (data.success && (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled')) {
                                    window.location.href = 'payment_return.php?txn=' + encodeURIComponent(transactionId);
                                } else if (attempts >= maxAttempts) {
                                    document.querySelector('.text-slate-500').textContent = 'This is taking longer than expected. You will be notified once payment is confirmed.';
                                } else {
                                    setTimeout(checkStatus, 3000);
                                }
                            })
                            .catch(() => {
                                if (attempts < maxAttempts) setTimeout(checkStatus, 3000);
                            });
                    }
                    setTimeout(checkStatus, 2000);
                </script>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</body>
</html>
