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

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

$transaction = null;

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

// Update transaction status to cancelled if it was processing
if ($transaction && in_array($transaction['status'], ['pending', 'processing'])) {
    $stmt = $db->prepare("
        UPDATE payment_transactions
        SET status = 'cancelled', processed_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$transaction['id']]);

    sendPaymentNotification('payment_failed', $transaction['transaction_id']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Cancelled | 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">
        <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-times-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">Your payment was cancelled. No charges were made to your account.</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">Reference</span>
                        <span class="font-mono font-bold text-slate-700"><?php echo htmlspecialchars($transaction['reference_number']); ?></span>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        <div class="flex flex-col sm:flex-row gap-3 justify-center">
            <a href="checkout.php" class="inline-flex items-center justify-center gap-2 px-6 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>
            <a href="cart.php" class="inline-flex items-center justify-center gap-2 px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-bold hover:bg-slate-200 transition-all">
                <i class="fas fa-home"></i> My Cart
            </a>
        </div>
    </div>
</body>
</html>
