<!DOCTYPE html>
<html>
<head>
    <title>Geidea Checkout</title>
    <script src="https://www.merchant.geidea.net/hpp/geideaCheckout.min.js"></script>
    <script>
        function createAndStartPayment() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '<?= base_url("modules/backend/agents/create-session") ?>');
            xhr.setRequestHeader('Content-Type', 'application/json');

            xhr.onload = function() {
                if (xhr.status === 200) {
                    var sessionId = xhr.responseText.trim();
                    startPayment(sessionId);
                } else {
                    alert('Error: ' + xhr.statusText);
                }
            };

            xhr.onerror = function() {
                alert('Error: Network Error');
            };

            var data = {
                amount: 10.00,
                currency: "SAR",
                callbackUrl: "https://www.example.com/callback",
                merchantReferenceId: "AGENT-" + Date.now(),
                language: "en"
            };

            xhr.send(JSON.stringify(data));
        }

        function startPayment(sessionId) {
            var payment = new GeideaCheckout(onSuccess, onError, onCancel);
            payment.startPayment(sessionId);
        }

        let onSuccess = function(data) {
            alert('Success: ' + JSON.stringify(data));
        };

        let onError = function(data) {
            alert('Error: ' + JSON.stringify(data));
        };

        let onCancel = function(data) {
            alert('Cancelled: ' + JSON.stringify(data));
        };
    </script>
</head>
<body>
    <button onclick="createAndStartPayment()">Pay with Geidea</button>
</body>
</html>
