<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>
<?php 
$settings = Engine_Api::_()->getApi('settings', 'core'); 
$otpsms_signup_phonenumber = $settings->getSetting('otpsms.signup.phonenumber', 0);

if(!empty($otpsms_signup_phonenumber)) {
  $getCountry = Engine_Api::_()->getDbTable('countries', 'core')->getCountry(Engine_Api::_()->getApi('settings', 'core')->getSetting('otpsms.default.countries','US'));
  if(!empty($getCountry)) {
    $country = Engine_Api::_()->getItem('core_country', $getCountry);
  }
}
?>
<?php if( empty($this->sent) ): ?>
  <?php echo $this->form->render($this) ?>
<?php else: ?>
  <div class="auth_forgot_success_tip text-center">
    <div class="auth_page_icon">
      <svg xmlns="http://www.w3.org/2000/svg" width="80px" height="80px" viewBox="0 0 1024 1024"><path fill="#000000" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm-55.808 536.384-99.52-99.584a38.4 38.4 0 1 0-54.336 54.336l126.72 126.72a38.272 38.272 0 0 0 54.336 0l262.4-262.464a38.4 38.4 0 1 0-54.272-54.336L456.192 600.384z"/></svg>
    </div>
    <p class="text-center mb-3 pb-3"><?php echo $this->translate("USER_VIEWS_SCRIPTS_AUTH_FORGOT_DESCRIPTION") ?></p>
    <a href="<?php echo $this->url(array(), 'default', true) ?>" class="back_login_button"><?php echo $this->translate("Back to Home") ?></a>
  </div>
  <script>
    setTimeout(function(){
      window.location = '<?php echo $this->url(array('action' => 'reset', 'code' => $this->code, 'uid' => $this->user->getIdentity())); ?>'; 
    },100);
  </script>
<?php endif; ?>

<script type="text/javascript">
  
  en4.core.runonce.add(function() {
    scriptJquery(scriptJquery('#signup_pop_wrap').html()).appendTo('#append-script-data');
    scriptJquery('#signup_pop_wrap').remove();
  });

  var formCheck = false;
  AttachEventListerSE('submit', '#user_form_auth_forgot', function(e) {
    if(!formCheck) {
      e.preventDefault();
      
      // Check if all required fields are filled out
      var formData = new FormData(this);
      //formData.append('formName', 'User_Form_Auth_Forgot');
      scriptJquery('#core_submit_forgot').html('<i class="fas fa-spinner fa-spin"></i>');

      var url = en4.core.baseUrl + 'user/auth/forgot';
      (scriptJquery.ajax({
        url : url,
        type: "POST",
        dataType: 'json',
        contentType:false,
        processData: false,
        cache: false,
        data: formData,
        success : function(response) {
          scriptJquery('#core_submit_forgot').html('<?php echo $this->translate("Send Code"); ?>');
          if(response.status) {
            if(scriptJquery('#form_errors').length)
              scriptJquery('#form_errors').remove();
            sendEmailCode();
            // show popup
            scriptJquery('#user_signup_email_btn').trigger('click');
          } else {
            if(scriptJquery('#form_errors').length)
              scriptJquery('#form_errors').remove();
            var errors = '<ul class="form-errors" id="form_errors">';
            for (var i = 0; i < response.error_message.length; i++) {
              var error_message = response.error_message[i];
              if(error_message.isRequired) {
                errors += '<li>'+error_message.label+'<ul class="errors"><li>'+error_message.errorMessage+'</li></ul></li>';
              }
            }
            errors += '</ul>';
            scriptJquery('.form-elements').prepend(errors);
            //scriptJquery('html, body').animate({
           //   scrollTop: scriptJquery('#form_errors').offset().top
           // }, 2000);
          }
        }
      }));
      return false;
    } else {
      return true;
    }
  });

  <?php //if( $settings->getSetting('user.signup.enabletwostep', 0) == 1 || !empty($otpsms_signup_phonenumber)) { ?>
    en4.core.runonce.add(function() {
      <?php if(!empty($otpsms_signup_phonenumber)) { ?>
        scriptJquery('#email-element').prepend(scriptJquery('#forgot_country_code').html());
        scriptJquery('#forgot_country_code').remove();
        
        scriptJquery('#country_code').selectize({
          onInitialize: function(){
            var $select = scriptJquery('#country_code');
            var selectize = $select[0].selectize; 
            
            if(typeof selectize.options[selectize.items[0]] != 'undefined') {
              var image = selectize.options[selectize.items[0]].image;
              
              scriptJquery(selectize.$control[0]).find('.item').remove();
              if(typeof image != 'undefined') {
                scriptJquery(selectize.$control[0]).prepend(`<div class="item" data-value="${selectize.options[selectize.items[0]].value.split('_')[0]}"><img src="${image}" height="20" width="20"> +${selectize.options[selectize.items[0]].value.split('_')[0]}</div>`);
              } else {
                scriptJquery(selectize.$control[0]).prepend(`<div class="item" data-value="<?php echo $country->phonecode; ?>"> +<?php echo $country->phonecode; ?></div>`);
              }
            } else {
              <?php  if(!empty($country->icon)) { 
                if(!empty($country->icon)) {
                  $path = Engine_Api::_()->core()->getFileUrl($country->icon, true); 
                ?>
                scriptJquery(selectize.$control[0]).prepend(`<div class="item" data-value="<?php echo $country->phonecode; ?>"><img src="<?php echo $path['image']; ?>" height="20" width="20" alt="<?php echo $path['alt_text'] ?? ''; ?>"> +<?php echo $country->phonecode; ?></div>`);
                <?php } else { ?>
                scriptJquery(selectize.$control[0]).prepend(`<div class="item" data-value="<?php echo $country->phonecode; ?>"> +<?php echo $country->phonecode; ?></div>`);
                <?php } ?>
              <?php } else { ?>
                scriptJquery(selectize.$control[0]).prepend(`<div class="item" data-value="<?php echo $country->phonecode; ?>"> +<?php echo $country->phonecode; ?></div>`);
              <?php } ?>
            }
          },
          render: {
            option: function (data, escape) {
              if(data.image) {
                return '<div><img src="' + data.image + '" alt="' + escape(data.text) + '" style="width: 20px; height: 20px;"> ' + escape(data.text) + '</div>';
              } else {
                return '<div>' + escape(data.text) + '</div>';
              }
            },
          },
          onDropdownClose: function(dropdown) {
            var that = scriptJquery(dropdown).prev().find('.item');
            var image = scriptJquery('.selectize-dropdown-content').find(`[data-value="${that.data('value')}"]`).find('img').attr('src');
            if(typeof image != 'undefined') {
							var altText = scriptJquery('.selectize-dropdown-content').find(`[data-value="${that.data('value')}"]`).find('img').attr('alt');
							
              that.html(`<img src="${image}" alt="${altText}" height="20" width="20"> +${that.data('value').split('_')[0]}`);
            } else {
              if(typeof that.find('img') != 'undefined' && that.find('img').length) {
                that.html(`<img src="${that.find('img').attr('src')}" height="20" width="20"> +${that.data('value').split('_')[0]}`);
              } else {
                that.html(`+${that.data('value').split('_')[0]}`);
              }
            }
          },
        });
        scriptJquery('#country_code').hide();
      <?php } ?>

      if(scriptJquery('#country_code').val())
        scriptJquery('#countrycode').val(scriptJquery('#country_code').val());
    });
    
    AttachEventListerSE('keyup', '#email', function(e) {
      var emailVal = scriptJquery("#email").val();
      //if(emailVal === '') {
        scriptJquery("#verify_email").remove().hide();
      //}
      <?php if(!empty($otpsms_signup_phonenumber)) { ?>
        if(emailVal.match(/^\d+$/)) {
          scriptJquery('#country_code_element').show();
          scriptJquery('#email-wrapper').addClass('country_code_main');
          //scriptJquery('#country_code').show();
        } else {
          scriptJquery('#country_code_element').hide();
          scriptJquery('#email-wrapper').removeClass('country_code_main');
          //scriptJquery('#country_code').hide();
        }
      <?php } ?>
    });
    
    function sendEmailCode() {
      var email = scriptJquery('#email').val();
      var country_code = scriptJquery('#country_code').val();
      if(!email.match(/^\d+$/)) {
        scriptJquery('#otp_timer').hide();
      }
      var url = en4.core.baseUrl + 'core/otp/sendotp';
      (scriptJquery.ajax({
        url : url,
        dataType: 'json',
        data : {
          format : 'json',
          email : email,
          country_code : country_code,
          type: 'forgot',
        },
        success : function(response) {
          if(response.status) {
            if(country_code) {
              otpsmsTimerData(email);
            }
            scriptJquery('#user_signup_email').show();
            scriptJquery('#send_signup_form').show();
            scriptJquery("#core_loading_cont_overlay").hide();
            scriptJquery('#validEmail').val(email);
          }
        }
      }));
    }
    
    function validateTwoStepCode() {
    
      var code = scriptJquery('#otp_code').val();
      if(code === '') {
        scriptJquery('#error_message').show().html("<span><?php echo $this->string()->escapeJavascript($this->translate('The security code you have entered is not correct. Please check your code and try again.')); ?></span>");
        return;
      }
	  scriptJquery(".core_loading_cont_overlay").show();
      var email = scriptJquery('#validEmail').val();
      scriptJquery("#core_loading_cont_overlayf").show();
      var url = en4.core.baseUrl + 'core/otp/validateotp';
      (scriptJquery.ajax({
        url : url,
        dataType: 'json',
        data : {
          format : 'json',
          email : email,
          code: code,
          type: 'forgot',
        },
        success : function(response) {
          scriptJquery("#core_loading_cont_overlayf").hide();
		  scriptJquery(".core_loading_cont_overlay").hide();
          if(response.status) {
            document.getElementById('send_signup_form').innerHTML = "<div class='success_msg success_msg m-2''><span>"+response.message+"</span></div>";
            formCheck = true;
            scriptJquery('#cancel_verify_otp').trigger('click');
            closeVerifyPopup();
            scriptJquery('#submit_signup').trigger('click');
          } else {
            scriptJquery('#error_message').show().html(response.message);
          }
        }
      }));
    }
    
    function closeVerifyPopup() {
      scriptJquery('#user_signup_email').hide();
      scriptJquery('#send_signup_form').hide();
	  scriptJquery('#otp_code').val('');
	  scriptJquery('#error_message').html("");
    }
    
    AttachEventListerSE('click', '#verify_otp', function(e){
      validateTwoStepCode();
    });
    
    AttachEventListerSE('click', '#resend_otp', function(e){
      resendOtpCode();
    });
    
    var resendHTML;
    function resendOtpCode() {
      if(scriptJquery('#resend_otp').hasClass('active'))
        return;
      scriptJquery('#resend_otp').html('<i class="fas fa-spinner fa-spin"></i>');
      scriptJquery('#resend_otp').addClass('active');
      resendHTML = scriptJquery('#resend_otp').html();
      scriptJquery.ajax({
        dataType: 'json',
        url: en4.core.baseUrl + 'core/otp/sendotp',
        method: 'post',
        data: {
          format: 'json',
          email: scriptJquery('#email').val(),
          country_code: scriptJquery('#country_code').val(),
          type: 'forgot',
        },
        success: function(responseJSON) {
          scriptJquery('#resend_otp').removeClass('active');
          if (responseJSON.status) {
            scriptJquery('#resend_otp').html('<?php echo $this->translate("Resend OTP"); ?>');
            scriptJquery('#resend_otp').hide();
            scriptJquery('#otp_timer').html(responseJSON.timerdata);
          } else if(responseJSON.error == 1 && responseJSON.message) {
            scriptJquery('#resend_otp').hide();
            scriptJquery('#otp_timer').html(responseJSON.message);
          }
        }
      });
    }
  <?php //} ?>
</script>
<?php if(!empty($otpsms_signup_phonenumber)) { ?>
  <?php echo Engine_Api::_()->getDbTable('countries', 'core')->getAllCountryHtml(array('id' => 'forgot_country_code')); ?>
<?php } ?>
<?php echo $this->partial('_otpPopUp.tpl', 'user', array()); ?>

<script type="text/javascript">
  en4.core.runonce.add(function(){
    scriptJquery("body").addClass('authpage')
  })
</script>
