<?php 
$letter_email_required = '';
$letter_email_disabled = 'disabled';
if(!empty($is_show_option_to_send_letter_selected)){
    $letter_email_required = 'required';
    $letter_email_disabled = '';
}


$domain = APP_SERVER_HOST_URL;
if(isset($personalize) && !empty($personalize->domain)){
    $www = "";
    if($personalize->is_www == 1){
        $www = "www.";
    }
    $domain = $personalize->domain_type.$www.$personalize->domain."/";
}        

$new_client_link = CLIENT_PORTAL_DOMAIN.'client/addclientbylink/'.$cmsuser->zapier_appkey;
$cmsuser->affiliate_unique_key = APP_SERVER_HOST_URL.'affiliate/addaffiliatebylink/'.$cmsuser->affiliate_unique_key;

?>

<style type="text/css">
  div .ka-main-content{
    text-align: left;
  }
  
</style>

<div class="row">
<div class="col-md-12">
<div class="box box-primary">
<div class="box-body">
<div class="row">
	<div class="col-md-6">
		<h3 class="box-title no-margin">
                    <span> 
                    <?php
                    if(!empty($cmsuser['img_path'])){
                    ?>
                        <img src="<?php echo $this->request->webroot.$cmsuser['img_path'];?>" style="width:25px;height:25px;">
                    <?php
                    } else{
                    ?>
                        <img src="<?php echo $this->request->webroot.'media/companies/dummy-image.jpg'?>" style="width:25px;height:25px;">
                    <?php
                        }
                    ?></span> Edit Profile
                </h3>
	</div>
</div>
</div>
</div> 
</div>             
</div>

        <div class="box box-primary">
        <!-- /.box-header -->
        <div class="box-body">
          <div class="row">
            <div class="col-md-6">
             <?= $this->Form->create($cmsuser,array('enctype'=>'multipart/form-data','id'=>'profile-form')) ?>
                <input type="hidden" name="step_status" value="<?php echo $step_status;?>">
                <div class="form-group" style="display: none;">
                  <?php 
                          echo $this->Form->input('previous_img_path', array('type' => 'hidden','value'=>$cmsuser['img_path']));
                          echo $this->Form->input('previous_logo', array('type' => 'hidden','value'=>$cmsuser['logo']));
                      echo $this->Form->input('language', array('options' => $languages,'class'=>'form-control'));
                  ?>
                </div>
                <!-- /.form-group -->
                <div class="form-group">
                  <?php echo $this->Form->input('username', array('class' => 'form-control required', 'placeholder' => __('Username'),'disabled'=>true,'required'=>false));?>
                </div>
                
                <div class="form-group">
                  <?php echo $this->Form->input('email', array('class' => 'form-control required', 'placeholder' => __('Email')));?>
                </div>
                <!-- /.form-group -->
                <div class="form-group">
                  <?php echo $this->Form->input('password', array('class' => 'form-control required','id' => 'password1', 'placeholder' => __('Password')));?>
                </div>
                <!-- /.form-group -->
                <div class="form-group">
                  <?php echo $this->Form->password('retype_password', array('id' => 'password2', 'class' => 'form-control required', 'placeholder' => __('Retype Password'), 'value' => $cmsuser->password));?>
                </div>
              <!-- /.form-group -->
                
                <div class="form-group">
                  <?php echo $this->Form->input('website', array('class' => 'form-control', 'placeholder' => __('e.g, https://www.example.com or https://example.com')));?>
                </div>
                <div class="form-group">
                  <?php echo $this->Form->input('company_name', array('class' => 'form-control', 'placeholder' => __('Company name')));?>
                </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('phone', array('type'=>'text','class' => 'form-control', 'placeholder' => __('Phone')));?>
                    </div>
              
                <div class="form-group">
                        <?php echo $this->Form->input('contact_email', array('class' => 'form-control', 'placeholder' => __('Contact Email')));?>
                </div>
                <div class="form-group">
                        <?php echo $this->Form->input('contact_name', array('class' => 'form-control', 'placeholder' => __('Contact Name'),'required'=>true));?>
                    </div>
                    <div class="form-group">
                        <label for="time_zone">Time zone</label>
                        <?php echo $this->Form->select('time_zone',$time_zone_list, array('empty'=>'Please select','class' => 'form-control', 'placeholder' => __('Timezone')));?>
                    </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('address_one', array('class' => 'form-control', 'placeholder' => __('Address one')));?>
                    </div>
                    
                <div class="row">
                    <div class="col-md-6">
              <!-- /.form-group -->
                        <div class="form-group">
                          <?php 
                                  echo $this->Form->input('img_path', array('type' => 'file', 'label' => __('Profile Picture (max. '.PROFILE_IMAGE_SIZE['width'].' x '.PROFILE_IMAGE_SIZE['height'].')')));
                          ?><br/>
                          <?php
                              if(file_exists($cmsuser['img_path'])){
                          ?>
                              <img src="<?php echo $this->request->webroot.$cmsuser['img_path'];?>" style="width:70px;height:50px;">
                              <?php
                                  } else{
                              ?>
                              <img src="<?php echo $this->request->webroot.'images/customer_service.png'?>" style="width:70px;height:50px;">
                              <?php
                                  }
                              ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <input type="hidden" name="logo_jpg" value=""/>
                            <div class="form-group">
                              <?php 
                                      echo $this->Form->input('logo', array('type' => 'file','id'=>'image_data','label' => __('Logo (max. '.LOGO_SIZE['width'].' x '.LOGO_SIZE['height'].')')));
                              ?><br/>
                              <?php
                                  if(file_exists("cmsuser_logo/".$cmsuser['logo'])){
                              ?>
                                  <img src="<?php echo $this->request->webroot."cmsuser_logo/".$cmsuser['logo'];?>" style="width:70px;height:50px;">
                                  <?php
                                      } else{
                                  ?>
                                  <img src="<?php echo $this->request->webroot.'media/companies/no-image.png'?>" style="width:70px;height:50px;">
                                  <?php
                                      }
                                  ?>
                            </div>
                        </div>
                    </div>
              <!-- /.form-group -->
            </div>

            <div class="col-md-6">
                <div class="col-md-12">
                    
                    <div class="form-group">
                        <?php echo $this->Form->input('address_two', array('class' => 'form-control', 'placeholder' => __('Address two')));?>
                    </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('city', array('class' => 'form-control', 'placeholder' => __('City')));?>
                    </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('state', array('class' => 'form-control', 'placeholder' => __('State')));?>
                    </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('address_zip', array('class' => 'form-control', 'placeholder' => __('Zipcode')));?>
                    </div>
                    
                    <div class="form-group">
                        <label for="">Zapier Appkey</label>
                        <a class="js-copy" href="#"><i class="fa fa-copy pull-right btn-small">Copy</i></a>
                        <?php echo $this->Form->input('zapier_appkey', array('label'=>false,'class' => 'form-control', 'placeholder' => __('App key'),'readonly'=>true));?>
                    </div>
                    <div class="form-group">
                        <a class="js-copy-link" href="#"><i class="fa fa-copy pull-right btn-small">Copy</i></a>
                        <label for="">Client Registration Link: </label>
                        <p style="word-break: break-all;">
                            <a target="_blank" href="<?php echo $new_client_link; ?>"><?php echo $new_client_link;?></a>  
                        </p>
                    </div>
                    <div class="form-group">
                        <a class="js-copy-link" href="#"><i class="fa fa-copy pull-right btn-small">Copy</i></a>
                        <label for="">Affiliate Registration Link: </label>
                        <p style="word-break: break-all;">
                            <a target="_blank" href="<?php echo $cmsuser->affiliate_unique_key; ?>"><?php echo $cmsuser->affiliate_unique_key; ?></a>  
                        </p>
                    </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('identity_iq_link', array('type'=>'text','label'=>'Identity IQ Setup Link','class' => 'form-control', 'placeholder' => __('Identity IQ Setup Link')));?>
                    </div>
                    <div class="form-group">
                        <?php echo $this->Form->input('smart_credit_link', array('type'=>'text','label'=>'Smart Credit Setup Link','class' => 'form-control', 'placeholder' => __('Smart Credit Setup Link')));?>
                    </div> 
                    
                    <div class="form-group">
                        <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_client_credit_login_details" value="1" <?php echo $is_client_credit_login_details; ?> /> 
                        Yes I want My client to Add Credit Report Login Details
                    </label>
                </div>
                    </div> 
                </div>
                <div class="col-md-12">
                    <div class="row">

                        <div class="col-md-6">
                          <div class="form-group">
                            <?php echo 'Registered IP :';?>
                          </div>
                        </div>

                        <div class="col-md-6">
                          <div class="form-group">
                            <?php echo $cmsuser->ip;?>
                          </div>
                        </div>

                    </div>

                    <div class="row">

                        <div class="col-md-6">
                          <div class="form-group">
                            <?php echo 'Pcakage Name & Price :';?>
                          </div>
                        </div>

                        <div class="col-md-6">
                          <div class="form-group">
                            <?php 
                            if(!empty($packageInfo)){
                              foreach ($packageInfo as $key => $value) {
                                echo $value->package->name.' ( '.$value->package->price.' '.UNIT.' )'.'<br>';
                              }
                            } ?>
                          </div>
                        </div>

                    </div>
                    <div class="row">
                        <div class="col-md-6">  </div>
                    </div>
                </div>
                
			 
            </div>

          </div>
            <div class="row">
                <div class="col-md-12">
                    <h3 class="box-title">
                    <span> 
                                            
                    </span> General Settings
                </h3>
                </div>
                <div class="col-md-12">
                    <div class="box box-primary"></div>
                </div>
            </div>
          <div class="row">
            <div class="col-md-4">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_receive_notification" value="1" <?php echo $is_receive_notification_selcted; ?> /> Receive  Notification on Letter  Sending
                    </label>
                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_default_checked_letterstrem_return_address_checkbox" value="1" <?php echo $is_default_checked_letterstrem_return_address_checkbox; ?> /> Turn on the default letterstream return address
                    </label>
                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_auto_login_enable" value="1" <?php echo $is_auto_login_enable; ?> /> Turn on client auto login after registration
                    </label>
                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_default_checked_saved_letter" value="1" <?php echo $is_default_checked_saved_letter; ?> /> Make Save Letters For later as Default
                    </label>
                </div>
            </div>
            <div class="col-md-4">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_show_option_to_send_letter" value="1" <?php echo $is_show_option_to_send_letter_selected; ?> /> Display Letter Sending Option on Velocity
                    </label>
                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_default_checked_send_email_checkbox" value="1" <?php echo $is_default_checked_send_email_checkbox; ?> /> Turn on the default send email
                    </label>
                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="is_allow_store_letters" value="1" <?php echo $is_allow_store_letters; ?> /> Turn on the save letters
                    </label>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label>Letter Sending Email Signature</label>
                    <?php 
                    $placeholder = "Regards,\nYour company name";
                    echo $this->Form->textarea('letter_email_signature', array('value'=>$isletter_email_signature,'class' => 'form-control pull-left letter-sign-textarea',$letter_email_required,$letter_email_disabled,'placeholder'=>$placeholder));?>
                </div>
            </div>
          </div>
          <!-- /.row -->
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
          <?= $this->Form->button(__('Submit'), ['class' => 'btn btn-success btn-flat ','id' => 'btnSubmit']) ?>
        </div>
        <?= $this->Form->end() ?>
      </div>
<script src="<?php echo $this->request->webroot; ?>js/jquery-1.11.2.js"></script>
<?php echo $this->Html->script('jsvalidate/validate-latest.js'); ?>
<?php echo $this->Html->script('jsvalidate/custom_validation_methods.js?1.0.3'); ?>
<script type="text/javascript">
$.validator.addMethod('isValidHttpUrl', function (value, element, param) {
    return isValidHttpUrl(value)
}, 'Invalid domain');

$.validator.addMethod('validateDomain', function (value, element, param) {
    var regex = `((http|https)://)(www.)?
                [a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]
                {2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)`;
    
    return !regex.test(value);
}, 'Domain value invalid');

function isValidHttpUrl(string) {
  let url;
  
  try {
    url = new URL(string);
  } catch (_) {
    return false;  
  }

  return url.protocol === "http:" || url.protocol === "https:";
}



     $('#profile-form').validate({
          rules:{
              //'website':{'isValidHttpUrl':true},
              'email':{
                  required: true,
                  email:true,
                  maxlength:70
              },
              'password':{
                    required: true,
                    minlength: 6
              },
              'retype_password':{
                    required: true,
                    equalTo: "#password1",
                    minlength: 6
              }
//              ,
//              'logo':{
//                    filesize: 1
//              }
          },
          messages:{
              'retype_password':{
                required: "Please enter password again",
                equalTo: "Confirm Password doesn't match",
                minlength: "Password length must be greater than six"
              }
          },
          submitHandler: function (form) {
              var step_status = '<?php echo $step_status;?>'
              if(step_status == 0){
                Swal.fire({
                    width:'40rem',
                    text: "Congratulations! You Have Completed your First Step. Would you like to Continue Setting Up Your system ?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes',
                    cancelButtonText:'No'
                }).then((result) => {
                  if (result.value) {
                    $('#profile-form').submit();
                  }
                })
              }else{
                 form.submit();
              }
          }
     });
    $(document).ready(function () {
//        $("#btnSubmit").submit(function () {
//            var password = $("#password1").val();
//            var confirmPassword = $("#password2").val();
//            if (password != confirmPassword) {
//                alert("Passwords do not match.");
//                return false;
//            }
//            var step_status = '<?php echo $step_status;?>'
//            if(step_status == 0){
//                event.preventDefault();

//                
//            }else{
//                return true;
//            }
//        });
    });

    $('input[name=is_show_option_to_send_letter]').click(function(){
        $('.letter-sign-textarea').attr('required',false);
        if($(this).prop('checked')){
            $('.letter-sign-textarea').attr('disabled',false);
            $('.letter-sign-textarea').attr('required',true);
        }else{
            //$('.letter-sign-textarea').val('');
            $('.letter-sign-textarea').attr('disabled',true);
        }
    })
    

</script>
<script>
   $("#image_data").on('change',function(){

        var url = $(this).val();
        //alert(url);
       // console.log(url);

        uploadPhotos(url);
    });

    function uploadPhotos(url){
    // Read in file
    var file = event.target.files[0];
    var fixed_width = '<?php echo UPLOAD_MEDIA_WIDTH; ?>';
    var fixed_height = '<?php echo UPLOAD_MEDIA_HEIGHT; ?>';

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
       // console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    //max_size = fixed_width,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > fixed_width) {
                        height *= fixed_width / width;
                        width = fixed_width;
                    }
                } else {
                    if (height > fixed_height) {
                        width *= fixed_height / height;
                        height = fixed_height;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                 $("input[name=logo_jpg]").val(dataUrl);
                var resizedImage = dataURLToBlob(dataUrl);
//                console.log('resizedImage');
//                console.log(dataUrl);
//                console.log(resizedImage);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });

            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
};

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }
//    console.log('in blob');
    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);

    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
   //console.log(rawLength);
    var myblob = new Blob([uInt8Array], {type: contentType});
     //console.log(myblob);
    return myblob;

}
/* End Utility function to convert a canvas to a BLOB      */

/* Handle image resized events */
$(document).on("imageResized", function (event) {
    console.log(event);
    $("input[name=logo_jpg]").val(event.url);
    
    
});

  $('.js-copy').click(function() {
      event.preventDefault();
    var text = $('input[name=zapier_appkey]').val();
    var el = $(this);
    copyToClipboard(text, el);
  });

</script>

