<?php
// Premium Razorpay-inspired UI for CodexVertex
require_once 'backend/config.php';

// Configuration Defaults
$upi_id = "6282839967-2@ybl";
$amount = 0.00; 
$user_id = ""; 
$merchant_name = "CodexVertex";
$return_url = "";
$order_id = $_GET['order_id'] ?? null;

if ($order_id) {
    // Fetch Order Details from DB
    $res = supabase_request('GET', 'transactions?order_id=eq.' . $order_id);
    if ($res['status'] == 200 && !empty($res['data'])) {
        $order = $res['data'][0];
        $amount = (float)$order['amount'];
        $user_id = $order['customer_id'] ?? $order['user_id'];
        $return_url = $order['return_url'] ?? "";
        
        // Fetch Merchant Name
        if (!empty($order['merchant_id'])) {
            $m_res = supabase_request('GET', 'merchants?id=eq.' . $order['merchant_id']);
            if (!empty($m_res['data'])) {
                $merchant_name = $m_res['data'][0]['business_name'];
            }
        }
    }
} else {
    // Demo Mode if no order_id
    $amount = 1.00;
    $merchant_name = "CodexVertex Demo";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure Checkout - CodexVertex</title>
    <!-- Google Fonts: Inter -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        :root {
            --primary-blue: #1159b3;
            --bg-gray: #f4f7fa;
            --text-dark: #1a1a1a;
            --text-muted: #6b7280;
            --card-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }

        body {
            background-color: var(--bg-gray);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            color: var(--text-dark);
        }

        .checkout-container {
            width: 100%;
            max-width: 420px;
            background: #fff;
            min-height: 100vh;
            position: relative;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        @media (min-width: 480px) {
            .checkout-container {
                min-height: auto;
                border-radius: 24px;
                box-shadow: 0 20px 50px rgba(0, 0, 0, 0.1);
                margin: 20px;
            }
        }

        /* Header Section */
        .header {
            background-color: var(--primary-blue);
            color: #fff;
            padding: 20px 24px 60px 24px;
            text-align: center;
            position: relative;
        }

        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.75rem;
            font-weight: 500;
            margin-bottom: 24px;
            opacity: 0.9;
        }

        .back-btn {
            font-size: 1.2rem;
            cursor: pointer;
        }

        .header h1 {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .amount-display {
            font-size: 2.2rem;
            font-weight: 800;
            margin-bottom: 4px;
        }

        .amount-words {
            font-size: 0.85rem;
            opacity: 0.8;
            font-style: italic;
        }

        /* Main Section */
        .main-content {
            padding: 0 24px 24px 24px;
            margin-top: -40px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* QR Card */
        .qr-card {
            background: #fff;
            width: 100%;
            border-radius: 16px;
            padding: 24px;
            box-shadow: var(--card-shadow);
            text-align: center;
            margin-bottom: 24px;
            border: 1px solid #edf2f7;
        }

        .qr-header {
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 12px;
        }

        .or-divider {
            position: relative;
            margin: 16px 0;
            color: var(--text-muted);
            font-size: 0.75rem;
            font-weight: 600;
        }

        .or-divider::before, .or-divider::after {
            content: "";
            position: absolute;
            top: 50%;
            width: 40%;
            height: 1px;
            background: #e2e8f0;
        }

        .or-divider::before { left: 0; }
        .or-divider::after { right: 0; }

        .qr-image {
            width: 180px;
            height: 180px;
            margin: 0 auto;
            padding: 8px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
        }

        /* App Icons Section */
        .pay-via-label {
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--text-muted);
            margin-bottom: 16px;
        }

        .app-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
            width: 100%;
            margin-bottom: 24px;
        }

        .app-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 6px;
            text-decoration: none;
        }

        .app-icon-wrap {
            width: 65px;
            height: 65px;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #fff;
            transition: border-color 0.2s;
        }

        .app-item:hover .app-icon-wrap {
            border-color: var(--primary-blue);
        }

        .app-icon-wrap img {
            width: 40px;
            height: 40px;
            object-fit: contain;
        }

        .app-name {
            font-size: 0.65rem;
            font-weight: 600;
            color: var(--text-muted);
        }

        /* Pay Button */
        .pay-btn {
            width: 100%;
            background-color: var(--primary-blue);
            color: #fff;
            border: none;
            padding: 16px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            transition: background 0.2s;
            margin-bottom: 16px;
        }

        .pay-btn:hover {
            background-color: #0d4a96;
        }

        .merchant-note {
            font-size: 0.8rem;
            color: var(--text-muted);
            text-align: center;
            margin-bottom: 30px;
        }

        /* Footer */
        .footer {
            padding: 20px 24px;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .footer-left {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            color: var(--text-muted);
        }

        .footer-right {
            text-align: right;
        }

        .secured-badge {
            background: #fff;
            border: 1px solid #e2e8f0;
            padding: 6px 10px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .secured-badge-text {
            font-size: 0.65rem;
            font-weight: 700;
            line-height: 1.1;
            text-align: left;
        }

        .secured-badge-text span {
            color: var(--primary-blue);
            display: block;
        }

        /* Status Animations */
        .polling-status {
            display: flex;
            align-items: center;
            gap: 10px;
            justify-content: center;
            margin-top: 10px;
            font-size: 0.85rem;
            color: var(--primary-blue);
            font-weight: 600;
        }

        .pulse {
            width: 8px;
            height: 8px;
            background: var(--primary-blue);
            border-radius: 50%;
            animation: pulse-animation 1.5s infinite;
        }

        @keyframes pulse-animation {
            0% { box-shadow: 0 0 0 0px rgba(17, 89, 179, 0.4); }
            100% { box-shadow: 0 0 0 10px rgba(17, 89, 179, 0); }
        }

        /* Success Overlay */
        #success-overlay {
            display: none;
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            background: #fff;
            z-index: 100;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            padding: 40px;
        }

        .success-circle {
            width: 80px;
            height: 80px;
            background: #27ae60;
            color: white;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 2.5rem;
            margin-bottom: 24px;
        }

        .success-title { font-size: 1.5rem; font-weight: 800; color: #1a1a1a; margin-bottom: 8px; }
        .success-subtitle { font-size: 0.9rem; color: #6b7280; }
    </style>
</head>
<body>

<div class="checkout-container">
    <!-- Header -->
    <div class="header">
        <div class="header-top">
            <span class="back-btn">←</span>
            <span id="orderIdText">ORDER #...</span>
        </div>
        <h1>Payment Gateway</h1>
        <div class="amount-display">₹<?php echo number_format($amount, 2); ?></div>
        <div class="amount-words">Payment for <?php echo $merchant_name; ?></div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- QR Wrapper -->
        <div class="qr-card">
            <div class="qr-header">Scan QR to Pay securely</div>
            <div class="or-divider">OR</div>
            
            <?php
            // Minimal link for personal IDs to avoid fraud triggers
            $upi_payload = "upi://pay?pa=$upi_id&pn=" . urlencode($merchant_name) . "&am=$amount&cu=INR";
            $qr_src = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" . urlencode($upi_payload);
            ?>
            
            <div class="qr-image" id="qrContainer">
                <img src="<?php echo $qr_src; ?>" alt="QR Code" style="width: 100%; height: 100%;">
            </div>

            <div class="polling-status" id="pollingStatus" style="margin-top: 15px;">
                <div class="pulse"></div>
                <span>Waiting for payment...</span>
            </div>
            
            <div style="margin-top: 15px; font-size: 0.75rem; color: #e74c3c; font-weight: 600;">
                Note: If 'Pay with App' is declined, please Scan QR or Copy UPI ID
            </div>
        </div>

        <div class="pay-via-label">Pay via UPI App</div>

        <!-- Copy UPI Section (The PRO Fix) -->
        <div style="width: 100%; background: #f8fafc; border: 1.5px dashed #cbd5e1; border-radius: 12px; padding: 12px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
            <div style="text-align: left;">
                <div style="font-size: 0.65rem; color: #64748b; font-weight: 700; text-transform: uppercase;">UPI ID</div>
                <div style="font-size: 0.9rem; font-weight: 700; color: #1e293b;" id="upiIdVal"><?php echo $upi_id; ?></div>
            </div>
            <button onclick="copyUpi()" style="background: #1159b3; color: white; border: none; padding: 8px 15px; border-radius: 8px; font-size: 0.75rem; font-weight: 700; cursor: pointer;" id="copyBtn">Copy</button>
        </div>

        <!-- Main Pay Button -->
        <a href="<?php echo $upi_payload; ?>" class="pay-btn" id="payWithAppBtn">
            Pay with App <span style="font-size: 1.2rem;">→</span>
        </a>

        <div class="merchant-note">
            You are paying ₹<?php echo number_format($amount, 2); ?> to <b><?php echo $merchant_name; ?></b>
        </div>
    </div>

    <!-- Footer -->
    <div class="footer">
        <div class="footer-left">
            🔒 100% Secure Payments 🔒
        </div>
        <div class="footer-right">
            <div class="secured-badge">
                <div class="secured-badge-text">
                    Secured by<br>
                    <span>CodexVertex</span>
                </div>
                <img src="https://cdn-icons-png.flaticon.com/512/1162/1162234.png" alt="Security" width="20">
            </div>
        </div>
    </div>

    <!-- Success Overlay -->
    <div id="success-overlay">
        <div class="success-circle">✓</div>
        <div class="success-title">Payment Successful</div>
        <div class="success-subtitle">Order ID: <span id="successOrderId"></span></div>
        <div class="success-subtitle">Wallet credited successfully.</div>
    </div>
</div>

<script>
let currentOrderId = "<?php echo $order_id; ?>";

$(document).ready(function() {
    if (currentOrderId && currentOrderId !== "") {
        // Order already exists, just show ID and start polling
        $('#orderIdText').text('ORDER #' + currentOrderId.split('_')[1]); 
        startPolling();
    } else {
        // No order ID in URL, create a new demo order
        $.ajax({
            url: 'backend/create_order.php',
            method: 'POST',
            data: JSON.stringify({ amount: <?php echo $amount; ?>, user_id: '<?php echo $user_id; ?>' }),
            contentType: 'application/json',
            success: function(response) {
                let res = JSON.parse(response);
                if(res.status === 'success') {
                    currentOrderId = res.order_id;
                    $('#orderIdText').text('ORDER #' + currentOrderId.split('_')[1]);
                    startPolling();
                } else {
                    alert("Order Creation Error: " + res.message);
                }
            }
        });
    }

    $('.back-btn').click(() => history.back());
});

function copyUpi() {
    const upiId = $('#upiIdVal').text();
    navigator.clipboard.writeText(upiId).then(() => {
        $('#copyBtn').text('Copied!').css('background', '#27ae60');
        setTimeout(() => {
            $('#copyBtn').text('Copy').css('background', '#1159b3');
        }, 2000);
    });
}

function startPolling() {
    let checkInterval = setInterval(function() {
        $.ajax({
            url: 'backend/check_payment.php?order_id=' + currentOrderId,
            method: 'GET',
            success: function(response) {
                let res = JSON.parse(response);
                if(res.payment_status === 'completed') {
                    clearInterval(checkInterval);
                    showSuccess();
                }
            }
        });
    }, 3000);
}

function showSuccess() {
    $('#successOrderId').text(currentOrderId);
    $('#success-overlay').css('display', 'flex');
    let returnUrl = "<?php echo $return_url; ?>";
    setTimeout(() => {
        if (returnUrl && returnUrl !== "") {
            window.location.href = returnUrl;
        } else {
            window.location.reload();
        }
    }, 4000);
}
</script>

</body>
</html>
