<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Pay $1000</title>
    <script src="https://www.paypal.com/sdk/js?client-id={{ env('PAYPAL_SANDBOX_CLIENT_ID') }}"></script>
</head>

<body>
    <a class="btn btn-primary m-3" href="{{ route('processTransaction') }}">Pay $1000</a>
    <div id="paypalCheckoutContainer"></div>
    @if(\Session::has('error'))
    <div class="alert alert-danger">{{ \Session::get('error') }}</div>
    {{ \Session::forget('error') }}
    @endif
    @if(\Session::has('success'))
    <div class="alert alert-success">{{ \Session::get('success') }}</div>
    {{ \Session::forget('success') }}
    @endif
    <script type="text/javascript">
        <?php $rootPath = "";
        define("PAYPAL_ENVIRONMENT", "sandbox");
        if (isset($_SERVER['SERVER_NAME'])) {
            $url = @($_SERVER["HTTPS"] != 'on') ? 'http://' . $_SERVER["SERVER_NAME"] : 'https://' . $_SERVER["SERVER_NAME"];
            $url .= ($_SERVER["SERVER_PORT"] !== 80) ? ":" . $_SERVER["SERVER_PORT"] : "";
            $url .= $_SERVER["REQUEST_URI"];
        } else {
            $url = "";
        }

        define("URL", array(

            "current" => $url,

            "services" => array(
                "orderCreate" => 'api/createOrder.php',
                "orderGet" => 'api/getOrderDetails.php',
                "orderPatch" => 'api/patchOrder.php',
                "orderCapture" => 'api/captureOrder.php'
            ),

            "redirectUrls" => array(
                "returnUrl" => 'pages/success.php',
                "cancelUrl" => 'pages/cancel.php',
            )
        ));
        $baseUrl = str_replace("index.php", "", URL['current']);
        ?>
        paypal.Buttons({

            // Set your environment
            env: '<?= PAYPAL_ENVIRONMENT ?>',

            // Set style of buttons
            style: {
                layout: 'vertical', // horizontal | vertical
                size: 'responsive', // medium | large | responsive
                shape: 'pill', // pill | rect
                color: 'gold', // gold | blue | silver | black,
                fundingicons: false, // true | false,
                tagline: false // true | false,
            },

            // Wait for the PayPal button to be clicked
            createOrder: function() {
                let formData = new FormData();
                formData.append('item_amt', document.getElementById("camera_amount").value);
                formData.append('tax_amt', document.getElementById("tax_amt").value);
                formData.append('handling_fee', document.getElementById("handling_fee").value);
                formData.append('insurance_fee', document.getElementById("insurance_fee").value);
                formData.append('shipping_amt', document.getElementById("shipping_amt").value);
                formData.append('shipping_discount', document.getElementById("shipping_discount").value);
                formData.append('total_amt', document.getElementById("total_amt").value);
                formData.append('currency', document.getElementById("currency_Code").value);
                formData.append('return_url', '<?= $baseUrl . URL["redirectUrls"]["returnUrl"] ?>' + '?commit=true');
                formData.append('cancel_url', '<?= $baseUrl . URL["redirectUrls"]["cancelUrl"] ?>');

                return fetch(
                    '<?= $rootPath . URL['services']['orderCreate'] ?>', {
                        method: 'POST',
                        body: formData
                    }
                ).then(function(response) {
                    return response.json();
                }).then(function(resJson) {
                    console.log('Order ID: ' + resJson.data.id);
                    return resJson.data.id;
                });
            },

            // Wait for the payment to be authorized by the customer
            onApprove: function(data, actions) {
                return fetch(
                    '<?= $rootPath . URL['services']['orderGet'] ?>', {
                        method: 'GET'
                    }
                ).then(function(res) {
                    return res.json();
                }).then(function(res) {
                    window.location.href = 'pages/success.php';
                });
            }

        }).render('#paypalCheckoutContainer');
    </script>
</body>

</html>