<?php
require_once("./config/db_config.php");
class FlywirePaymentGateway{

    public $domainURL;
    function __construct() {
        $this->domainURL = domainURL;
    }
    public function createOrder($paymentDetails, $gatewayDetails)
    {
        $nameParts = explode(' ', $paymentDetails['name']);
        $env = $gatewayDetails['env'];
        $recipient = $gatewayDetails['recipient'];
        $amount = $paymentDetails['amount']*100;
        if(isset($paymentDetails['studentCode']))
        {
            $paymentDetails['code'] = $paymentDetails['studentCode'];
        }
        $student_id = isset($paymentDetails['code'])?$paymentDetails['code']:'';
        $sender_first_name = $nameParts[0];
        $sender_last_name = isset($nameParts[1]) ? $nameParts[1] : $nameParts[0];
        $sender_phone = $paymentDetails['phoneNo'];
        $sender_email = $paymentDetails['email'];
        $order_id = $gatewayDetails['order_id'];
        $callback_id = $gatewayDetails['callback_id'];
        $returnUrl =  isset($paymentDetails['redirectURL'])?$this->domainURL.'/paymentResponse.php?donationId='.$callback_id.'&redirect='.rawurlencode($paymentDetails['redirectURL']):$this->domainURL.'/paymentResponse.php';

        $html = <<<HTML
                        <!DOCTYPE html>
                        <html>
                        <head>
                        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                        <script src="https://payment.flywire.com/assets/js/checkout.js"></script>
                        </head>
                        <body>
                        <div>
                        <button id="checkout-button" style="display:none">Paga aqui</button>
                        </div>
                        <script>
                        var config = {
                            env: "{$env}",
                            recipient: "{$recipient}",
                            locale: "en-EN",
                            amount: "{$amount}",
                            //sender_country: "US",
                            // sender_state: "AL",
                            // sender_first_name: "{$sender_first_name}",
                            // sender_last_name: "{$sender_last_name}",
                            //sender_address1: "HARSON",
                            // sender_phone: "{$sender_phone}",
                            //sender_city: "HARSON",
                            // sender_email: "{$sender_email}",
                            displayPayerInformation: false,
                            student_id : "{$student_id}",
                            student_first_name : "{$sender_first_name}",
                            student_last_name : "{$sender_last_name}",
                            order_id: "{$order_id}",
                            callback_id: "{$callback_id}",
                            callback_version: "2",
                            callback_url: "{$this->domainURL}/notificationURL.php",
                            return_url: "{$returnUrl}",
                            theme: {
                                header: true,
                                footer: true,
                                closeButton: false
                            }
                        };

                        window.onload = function() {
                            window.flywire.Checkout.render(config, "#checkout-button");
                            document.getElementById('checkout-button').click();
                        }


                        </script>
                        </body>
                        </html>
                    HTML;

        return $html;
    }

    public function fetchOrder($data)
    {
        $gateWayData =  json_decode($data['gatewayConfig'] , true);
        $orderUrl =  $gateWayData['orderUrl'];
        $url = $orderUrl . '/' . $data['txnId'];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'X-Authentication-Key: '.$gateWayData['X-Authentication-Key'],
            ),
        )
        );
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response , true);
    }

    public function getReq($req)
    {
        $msg = [
            "msg" => "Unfortunately , your transaction could not be processed. Please try again later.<br/><br/>Lamentablemente, no se pudo procesar su transacción. Inténtelo nuevamente más tarde.",
            "status" => false
        ];

        if(isset($req['reference']) && isset($req['status']))
        {
            if($req['status'] === 'success')
            {
                $msg = [
                    "msg" => "Fee Payment is successful !!!.<br /><br />Thank you for the payment. Your Transaction id is ".$req['reference'].".<br /> Please close the window. <br/><br/>Gracias. Tu pago se realizó de manera exitosa.<br/>Tu ID de transacción es ".$req['reference']." <br/>Hemos enviado el recibo de esta operación a tu correo electrónico<br/>Ahora puedes cerrar la ventana.",
                    "status" => true
                ];
            }else if($req['status'] === 'initiated')
            {
                $msg = [
                    "msg" => "<strong>Next Steps :</strong><br/>After obtaining the challan form or bank deposit you must complete it with the requested details using the account number corresponding to the designated bank.<br/>Once the payment is confirmed, the deposit confirmation receipt will be available for download on the portal. <br/><strong>Próximos pasos :</strong><br/>Luego de obtener el formulario o depósito bancario debe completarlo con los datos solicitados utilizando el número de cuenta correspondiente al banco designado.<br/>Una vez que el pago sea confirmado, el recibo de confirmación de depósito estará disponible para ser descargado en el portal.<br/>",
                    "status" => true
                ]; 
            }

        }
        return $msg;
    }
}
