 <?php
 // read the parameters from request
 $error = $block->getData('error');
 $apiPaymentUrl = $block->getData('apiPaymentUrl');
 $months_arr = array('01'=>1,'02'=>2,'03'=>3,'04'=>4,'05'=>5,'06'=>6,'07'=>7,'08'=>8,'09'=>9,'10'=>10,'11','12'=>'12');
 $years = range(date('Y'),date('Y')+20);
 
 ?>

<div class="columns">
    <div class="column main">
        <h4>Please Fill API Payment Form</h4>        

<div class="abs-blocks-2columns">

    <?php if(!empty($error)){?>
    <div class="message message-error error">
        <?=$error?>
    </div>
    <?php }?>
    
    <form name="apiPaymentForm" action="<?=$apiPaymentUrl.'?t='.time()?>" method="POST" onsubmit="return validateAPIPaymentForm();">
    <label>Payment Method</label>   
    <table>
    <tr>
    <td style="vertical-align: middle">
    <input type="radio" name="PaymentMethod" value="1"/> Credit Card    
    </td>
    <td style="vertical-align: middle; width:10px;">
    <input type="radio" name="PaymentMethod" value="2"/> 
    </td>
    <td style="vertical-align: middle">
    <img alt="Sadad" title="sadad" src="http://res.cloudinary.com/dzsn7tnuc/image/upload/c_scale,w_160/v1511864961/sadadLogo_low_en_wyw1so.png"/>
    </td>    
    </tr>
    </table> 
    <div 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"/>
 </div>
 <div class="clearfix">&nbsp;</div>
 <div class="field">        
    <label>Card Holder Name</label>
    <input id="card-holder-name" name="CardHolderName" type="text" value="" autocomplete="off" data-validate="required"/>
 </div>
 <div class="clearfix">&nbsp;</div>
 <div class="field">         
    <label>Security Code</label>
    <input id="security-code" name="SecurityCode" type="password"  value="" autocomplete="off" maxlength="4" data-validate="required|cvv"/>
 </div>
 <div class="clearfix">&nbsp;</div>
 <div class="field abs-blocks-2columns">   
    <label>Month Expiry Date</label> 
    <select id="expiry-date-month" name="ExpiryDateMonth" type="text"  value="" maxlength="2" data-validate="required">
      <option value="" />
      <?php foreach($months_arr as $month_val=>$month){?>
      <option value="<?=$month_val?>"><?=$month?></option>
      <?php }?>
    </select> 
 </div>
 <div class="clearfix">&nbsp;</div>
 <div class="field abs-blocks-2columns">   
    <label>Year Expiry Date</label> 
    <select id="expiry-date-year" name="ExpiryDateYear" type="text"  value="" maxlength="2" data-validate="required">
      <option value="" />
      <?php foreach($years as $year){?>
        <option value="<?=substr($year,2)?>"><?=$year?></option>
     <?php }?>
    </select>
 </div> 
 </div>
    
 <div data-payment-method="2">
     <div class="clearfix">&nbsp;</div>
     <div class="field">
        <label>Sadad Account ID</label>
        <input id="sadad-olp-id" name="SadadOlpId" type="text" autocomplete="off"  value="" data-validate="required"/>
     </div>
 </div>
    <div class="clear">&nbsp;</div>
 <button class="action subscribe primary" title="Pay Now" type="submit">
        <span>Pay</span>
 </button>
 </form>
</div>
</div>
</div>
    
<script>
    var rad = document.apiPaymentForm.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 curr = document.querySelectorAll('[data-payment-method="'+this.value+'"]');
            curr[0].style.visibility = "visible";
            curr[0].style.display = "block";
            var input_elems = document.querySelectorAll('[data-payment-method="'+this.value+'"] input, [data-payment-method="'+this.value+'"] select');
            for(i=0; i<input_elems.length; i++){
                input_elems[i].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+'"]');                
            prev_elem[0].style.visibility = "hidden";
            prev_elem[0].style.display = "none";
            var prev_input_elems = document.querySelectorAll('[data-payment-method="'+other_value+'"] input, [data-payment-method="'+other_value+'"] select');
            for(i=0; i<prev_input_elems.length; i++){
                prev_input_elems[i].setAttribute('disabled','disabled');
            }
        };
    }
    function validateAPIPaymentForm(){
        var form_fields = document.querySelectorAll('input[type="text"], select');
        var has_errors = false;
        for(i=0; i<form_fields.length; i++){
            field = form_fields[i];
            if(field.disabled == false){
                validation_rule = field.dataset?field.dataset.validate:'';            
                is_error = false;
                error_msg = "";            
                if(validation_rule){
                    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 credit card number";
                        }else if(validation_rule=='cvv' && !validCVV(field.value)){
                            is_error = true;
                            error_msg = "Invalid CVV number";
                        }
                    }
                
                    has_errors = has_errors || is_error;
                }
            }

            if(is_error){
                field.className += ' required-entry mage-error';
                
                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;
                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);
                }
            }
        }
        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>
 
