<!-- STEP 3: Create PHP Page send Request -->
 <?php
 // read the parameters from request
 $paymentParameters = $block->getData('paymentParams');
 $paymentTypeAllowed = $block->getData('paymentTypeAllowed');
 $redirectURL = (String) $paymentParameters["RedirectURL"];
 $amount = (String) $paymentParameters["Amount"];
 $currencyCode = (String) $paymentParameters["CurrencyISOCode"];
 $transactionID = (String) $paymentParameters["TransactionID"];
 $merchantID = (String) $paymentParameters["MerchantID"];
 $language = (String) $paymentParameters["Language"];
 $messageID = (String) $paymentParameters["MessageID"];
 $secureHashSadad = (String) $paymentParameters["secureHashSadad"];
 $secureHashCreditCard = (String) $paymentParameters["secureHashCreditCard"];
 $themeID = (String) $paymentParameters["ThemeID"];
 $responseBackURL = (String) $paymentParameters["ResponseBackURL"];
 $channel = (String) $paymentParameters["Channel"];
 $quantity = (String) $paymentParameters["Quantity"];
 $version = (String) $paymentParameters["Version"];
 $paymentMethod = (String) $paymentParameters["PaymentMethod"];
 $paymentDescription = (String) $paymentParameters["PaymentDescription"];
 $ItemID = (String)$paymentParameters['ItemID'];
 //optional for sadad
 $sadadOlpId = (String)$paymentParameters['SadadOlpId'];
 $months_arr = array('01'=>'01','02'=>'02','03'=>'03','04'=>'04','05'=>'05','06'=>'06','07'=>'07','08'=>'08','09'=>'09','10'=>'10','11'=>'11','12'=>'12');
 $years = range(date('Y'),date('Y')+20);
 $lang = $block->getData('lang'); 
 ?>

<div class="smartroute-cont-<?=$lang?>">
         <img src="http://res.cloudinary.com/dzsn7tnuc/image/upload/v1516184630/logoStacked_uwoeae.png" alt="PayOne SmartRoute"/>

<div class="columns">
    <div class="column main">

<div class="directpost-form-cont">
 <form action="<?=$redirectURL?>" method="post" name="directPostForm" onsubmit="return validateDirectPostForm();" autocomplete="off">
     <?php if($paymentTypeAllowed=='' || $paymentTypeAllowed=='creditcard'){?>
    <div class="block">    
        <div class="payment-radio-holder">
            <input type="radio" name="PaymentMethod" value="1"/> <?=__('Credit Card') ?>    
        </div>
        <div class="field" data-payment-method="1"> 
 <div class="field">
    <label><?=__('Card Number')?>*</label>
    <input id="card-number"   name="CardNumber" type="text" value="" autocomplete="off" data-validate="required|creditcard" maxlength="23" />
 </div>
    <div class="clearfix">&nbsp;</div>
 <div class="field">
    <label><?=__('Card Holder Name')?>*</label>
    <input id="card-holder-name"   name="CardHolderName" type="text" autocomplete="off" value="" data-validate="required" maxlength="64" />
 </div>
    <div class="clearfix">&nbsp;</div>
 <div class="field">
    <label><?=__('Security Code')?>*</label>
    <input id="security-code"   name="SecurityCode" type="password" autocomplete="off" value="" maxlength="3" data-validate="required|cvv"/>
 </div>
    <div class="clearfix">&nbsp;</div>
   
 <div class="field">       
  <div class="abs-blocks-2columns date-block">   
    <label><?=__('Month Expiry Date') ?>*</label> 
    <select id="expiry-date-month"   name="ExpiryDateMonth" type="text"  value="" maxlength="2" data-validate="required">
     <option value="" >MM</option>
     <?php foreach($months_arr as $month_val => $month){?>
     <option value="<?=$month_val?>"><?=$month?></option>
     <?php }?>
    </select> 
  </div>         
        
 <div class="abs-blocks-2columns date-block">   
    <label><?=__('Year Expiry Date')?>*</label> 
    <select id="expiry-date-year"   name="ExpiryDateYear" type="text"  value="" maxlength="2" data-validate="required">
     <option value="" >YYYY</option>
     <?php foreach($years as $year){?>
     <option value="<?=substr($year,2)?>"><?=$year?></option>
     <?php }?>
    </select>
 </div>
 </div> 
        
        <input name="SecureHash" type="hidden" value="<?=$secureHashCreditCard ?>"/>
        </div>        
    </div>
     <?php }?>
     
     <?php if($paymentTypeAllowed=='' || $paymentTypeAllowed=='sadad'){?>
    <div class="block">    
    <div class="payment-radio-holder custom-icon">
        <input type="radio" name="PaymentMethod" value="2"/> 
        <img alt="Sadad" title="sadad" src="http://res.cloudinary.com/dzsn7tnuc/image/upload/c_scale,w_160/v1511864961/sadadLogo_low_en_wyw1so.png"/>
    </div>
 <div data-payment-method="2">     
     <label><?=__('Sadad Account ID')?>*</label>
     <input id="sadad-olp-id" autocomplete="off" name="SadadOlpId" type="text" value="<?=$sadadOlpId ?>" data-validate="required" maxlength="12"/>     
     <input name="SecureHash" type="hidden" value="<?=$secureHashSadad ?>"/>
 </div>

    </div>
     <?php }?>
 <input name="MerchantID" type="hidden" value="<?=$merchantID?>"/>
 <input name="Amount" type="hidden" value="<?=$amount?>"/>
 <input name="CurrencyISOCode" type="hidden" value="<?=$currencyCode?>"/>
 <input name="Language" type="hidden" value="<?=$language?>"/>
 <input name="MessageID" type="hidden" value="<?=$messageID?>"/>
 <input name="TransactionID" type="hidden" value="<?=$transactionID?>"/>
 <input name="ThemeID" type="hidden" value="<?=$themeID?>"/>
 <input name="ResponseBackURL" type="hidden" value="<?=$responseBackURL?>"/>
 <input name="Quantity" type="hidden" value="<?=$quantity?>"/>
 <input name="Channel" type="hidden" value="<?=$channel?>"/>
 <input name="Version" type="hidden" value="<?=$version?>"/>
 
 <input name="PaymentDescription" type="hidden" value="<?=$paymentDescription?>"/> 
<?php if (!empty($ItemID)): ?>
    <input name="ItemID" type="hidden" value="<?= $ItemID ?>"/>
<?php endif; ?>
 
 
<div class="clearfix"></div>
<div class="block-full">
    <button type="submit" class="action login primary"><?=__('Submit')?></button>
    <button type="cancel" class="action login secondary" onclick="window.location = '<?php echo $this->getUrl('stssmartroute/payment/cancel'); ?>?redirect_home=1'; return false;" class="">
    <?=__('Cancel')?>
    </button> 
 </div>

 </form> 
</div>     
    </div>
</div>        
</div>
<script>
    var rad = document.querySelectorAll('input[name="PaymentMethod"]');
    
    var prev = null;
    for(var i = 0; i < rad.length; i++) {
        rad[i].onclick = function() {
            (prev)? console.log('prev ... '+prev.value):null;
            if(this !== prev) {
                prev = this;
            }
            
            var current_inputs = document.querySelectorAll('[data-payment-method="'+this.value+'"] input, [data-payment-method="'+this.value+'"] select');
            console.log(current_inputs);
            for(jc in current_inputs){
                current_inputs[jc].disabled = false;
            }
            
            var other_value;
            if(this.value==1){
                other_value = 2;                
            }else{
                other_value = 1;
            }
            var prev_elem = document.querySelectorAll('[data-payment-method="'+other_value+'"]');                
            var prev_inputs = document.querySelectorAll('[data-payment-method="'+other_value+'"] input, [data-payment-method="'+other_value+'"] select');
            console.log(prev_inputs);
            for(jv in prev_inputs){                
                error_fields = document.querySelectorAll('#error'+prev_inputs[jv].id);
                prev_inputs[jv].disabled = 'disabled';                
                if(error_fields.length==1){
                    elem = error_fields[0];
                    elem.parentNode.removeChild(elem);                    
                    prev_inputs[jv].classList.remove("mage-error");
                    prev_inputs[jv].classList.remove("error-added");                    
                }                
                if(prev_inputs[jv].type !== 'hidden'){
                    prev_inputs[jv].value = '';
                }
            }
        };
    }
    rad[0].click();
    
    function validateDirectPostForm(){
        var form_fields = document.querySelectorAll('input[type="text"], select,input[type="password"]');
        var has_errors = false;
        for(i=0; i<form_fields.length; i++){
            field = form_fields[i];

            validation_rule = field.dataset?field.dataset.validate:'';            
            is_error = false;
            error_msg = "";
            console.log(validation_rule);
            if(validation_rule && field.disabled === false){
               var validations = validation_rule.split("|");
                for(j=0;j<validations.length;j++){
                    validation_rule = validations[j];
                    
                    if(validation_rule == 'required' && field.value==""){                    
                        is_error = true;
                        error_msg = "<?=__('Field is required') ?>";
                    }else if(validation_rule=='creditcard' && !validCreditCard(field.value)){
                        is_error = true;
                        error_msg = "<?=__('Invalid Card Number') ?>";
                    }else if(validation_rule=='cvv'){
                        if(field.value==""){
                            is_error = true;
                            error_msg = "<?=__('Field is required') ?>";   
                        }else if(!validCVV(field.value)){
                            is_error = true;
                            error_msg = "<?=__('Invalid Security Code')?>";
                        }
                    }
                }
                
                has_errors = has_errors || is_error;
            }

            if(is_error){
                if(!field.classList.contains('required-entry')){
                    field.className += ' required-entry';   
                }                
                if(!field.classList.contains('validation-failed')){
                    field.className += ' validation-failed';   
                }
                error_fields = document.querySelectorAll('#error'+field.id);
                if(error_fields.length==1){
                    var error_el = error_fields[0];
                }else{
                    var error_el = document.createElement("div");
                }
                error_el.className='mage-error error-added';                
                error_el.innerHTML = error_msg;
                field.className += ' mage-error';
                error_el.setAttribute("generated",true);
                error_el.setAttribute("for",field.id);
                error_el.setAttribute("id",'error'+field.id);
                insertAfter(error_el, field);
            }else{
                error_fields = document.querySelectorAll('#error'+field.id);
                if(error_fields.length==1){
                    elem = error_fields[0];
                    elem.parentNode.removeChild(elem);
                }
                field.classList.remove("mage-error");
                field.classList.remove("error-added");
            }
        }
        return !has_errors;
    }
    
    function insertAfter(newNode, referenceNode) {
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    }
    
    // takes the form field value and returns true on valid number
    function validCreditCard(value) {
    // accept only digits, dashes or spaces
    if (/[^0-9-\s]+/.test(value)) return false;

    // The Luhn Algorithm. It's so pretty.
    var nCheck = 0, nDigit = 0, bEven = false;
    value = value.replace(/\D/g, "");

    for (var n = value.length - 1; n >= 0; n--) {
        var cDigit = value.charAt(n),
              nDigit = parseInt(cDigit, 10);

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

        nCheck += nDigit;
        bEven = !bEven;
    }

    return (nCheck % 10) == 0;
    }    
    
    function validCVV(value){        
        ret = value.search(/^[0-9]{3,4}$/);                
        return ret==0;
    }
</script>     
