<?php

class kavehajaxLogin {

      public $options;
      public $code;

      public function __construct() {
        $this->options = get_option('kaveh_frame');
        add_action('template_redirect', [ $this , 'handleAjaxLogin' ]);
      }

      public function startSession($phone) {
        // Check if the verification code transient exists
        $verification_code = get_transient('verification_code_' . $phone);
    
        if (!empty($verification_code)) {
            // Transient exists, use the stored code
            $this->code = $verification_code;
        } else {
            // Generate a new verification code
            $verification_code = rand(1000,9999);
            
            // Store the verification code in transient for 2 minutes
            set_transient('verification_code_' . $phone, $verification_code, 2 * MINUTE_IN_SECONDS);
    
            // Assign the generated code to $this->code
            $this->code = $verification_code;
        }
    }

      

      public function handleAjaxLogin() {
          
          global $wp_query;
          $method = $wp_query->get('rewrite_ajax');
          if (!$method) {
              return;
          }
          switch ($method) {
              case 'smslogin':
                $phone = $_POST['phone'];
                $this->startSession($phone);
                $user_id = false;
                $numberWithoutFirstZero = ltrim( $phone, '0');
                global $wpdb;
                $query = $wpdb->prepare(
                    "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'billing_phone' AND meta_value = %s
                    UNION
                    SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'digits_phone_no' AND meta_value = %s",
                    $phone,
                    $numberWithoutFirstZero
                );
                $user_ids = $wpdb->get_col($query);
                if (!empty($user_ids)) {
                    $user_id = $user_ids[0];
                    $mobile   = $phone;
                    $code = $this->code;
                    $bodyId   = $this->options['kaveh_pattern_sms'];
                    $username = $this->options['kaveh_username_sms'];
                    $password = $this->options['kaveh_password_sms'];
                    $fromnum = $this->options['kaveh_number_sms'];
                    $bodyId = $this->options['kaveh_pattern_sms'];
                    $message = $this->options['kaveh_matn_raygansms'];
                    $api = $this->options['kaveh_password_api'];
                    if($this->options['kaveh_sms_gateway'] === 'option-1'):
                      kavehsms::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-2'):
                      kavehsms::smsir($api, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-3'):
                      kavehsms::melipayamak($username, $password, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-4'):
                      kavehsms::kavehnegar($api, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-5'):
                      kavehsms::raygansms($username, $password, $mobile, $message, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-6'):
                      kavehsms::webone($username, $password, $fromnum,$mobile, $message, $code);
                    endif;  
                    $response = array(
                        'result' => 'success',
                    );
                    wp_send_json($response);
                }
                else{
                    $mobile   = $phone;
                    $code = $this->code;
                    $bodyId   = $this->options['kaveh_pattern_sms'];
                    $username = $this->options['kaveh_username_sms'];
                    $password = $this->options['kaveh_password_sms'];
                    $fromnum = $this->options['kaveh_number_sms'];
                    $bodyId = $this->options['kaveh_pattern_sms'];
                    $message = $this->options['kaveh_matn_raygansms'];
                    $api = $this->options['kaveh_password_api'];
                    if($this->options['kaveh_sms_gateway'] === 'option-1'):
                      kavehsms::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-2'):
                      kavehsms::smsir($api, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-3'):
                      kavehsms::melipayamak($username, $password, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-4'):
                      kavehsms::kavehnegar($api, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-5'):
                      kavehsms::raygansms($username, $password, $mobile, $message, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-6'):
                      kavehsms::webone($username, $password, $fromnum,$mobile, $message, $code);
                    endif;  
                    $response = array(
                        'result' => 'error',
                    );
                    wp_send_json($response);
                }
              break;
              case 'formfinal':
              $phone = $_POST['phone'];
              $this->startSession($phone);
              $code = (int)$_POST['code'];
              $fname = $_POST['fname'];
              $lname = $_POST['lname'];
              $password = $_POST['pass'];
              $user_id = false;
              $numberWithoutFirstZero = ltrim( $phone, '0');
              global $wpdb;
              $query = $wpdb->prepare(
                  "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'billing_phone' AND meta_value = %s
                  UNION
                  SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'digits_phone_no' AND meta_value = %s",
                  $phone,
                  $numberWithoutFirstZero
              );
              $user_ids = $wpdb->get_col($query);
              if (!empty($user_ids)) {
                  $user_id = $user_ids[0];
                  if($this->code == $code){
                    wp_set_current_user($user_id);
                    wp_set_auth_cookie($user_id, true, false);
                    $response = array(
                        'result' => 'success',
                    );
                    wp_send_json($response);
                }else{
                    $response = array(
                        'result' => 'error',
                    );
                    wp_send_json($response);
                }
              }else{
                if($this->code == $code){
                    $user_id = wp_insert_user([
                        'first_name' => $fname,
                        'last_name' => $lname,
                        'display_name ' => $fname . ' ' . $lname,
                        'user_login' => $phone,
                        'user_pass' => $password,
                        'role' => 'customer',
                        'meta_input'   => array(
                            'billing_phone' => $phone,
                            'phone'         => $phone,
                        ),
                    ]);
                    wp_set_current_user($user_id);
                    wp_set_auth_cookie($user_id);
                    $response = array(
                        'result' => 'success',
                    );
                    wp_send_json($response);
                }else{
                    $response = array(
                        'result' => 'error',
                    );
                    wp_send_json($response);
                }
            }
            break;
            case 'passlogin':

              $password = $_POST['password'];
              if(isset($_POST['phone']) && !empty($_POST['phone'])){

                $phone = $_POST['phone'];
                $numberWithoutFirstZero = ltrim( $phone, '0');
                global $wpdb;
                $query = $wpdb->prepare(
                    "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'billing_phone' AND meta_value = %s
                    UNION
                    SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'digits_phone_no' AND meta_value = %s",
                    $phone,
                    $numberWithoutFirstZero
                );
                $user_ids = $wpdb->get_col($query);
                if (!empty($user_ids)) {
                    $user_id = $user_ids[0];
                    $user = get_user_by( 'ID', $user_id );
                    if (wp_check_password($password, $user->user_pass, $user->ID)) {
                      // Password is correct, log the user in
                      wp_set_current_user($user->ID);
                      wp_set_auth_cookie($user->ID, true, false);
                      $response = array(
                        'result' => 'success',
                      );
                      wp_send_json($response);
                      
                    }else{
                      $response = array(
                        'result' => 'wrong',
                      );
                      wp_send_json($response);
                    }

                }else{
                    $response = array(
                      'result' => 'error',
                    );
                    wp_send_json($response);
                }

              }

              if(isset($_POST['email']) && !empty($_POST['email'])){

                $email = $_POST['email'];
                $user_by_email = get_user_by('email', $email);
                $user_by_billing_email = get_users([
                    'meta_key' => 'billing_email',
                    'meta_value' => $email,
                    'number' => 1,
                ]);
                if(!empty($user_by_email)){
                  $user = $user_by_email;
                }
                if(!empty($user_by_billing_email)){
                  $user = $user_by_billing_email;
                }
                if ($user) {
                  $user = $user[0];
                  if (wp_check_password($password, $user->user_pass, $user->ID)) {
                    // Password is correct, log the user in
                    wp_set_current_user($user->ID);
                    wp_set_auth_cookie($user->ID);
                    $response = array(
                      'result' => 'success',
                    );
                    wp_send_json($response);

                  }else{

                    $response = array(
                      'result' => 'wrong',
                    );
                    wp_send_json($response);

                  }

                }else{

                  $response = array(
                    'result' => 'error',
                  );
                  wp_send_json($response);

                }

              }
            break;
            case 'passformfinal':

              $fname = $_POST['fname'];
              $lname = $_POST['lname'];
              $password = $_POST['password'];
              if(isset($_POST['phone']) && !empty($_POST['phone'])){

                $phone = $_POST['phone'];
                $user_id = wp_insert_user([
                    'first_name' => $fname,
                    'last_name' => $lname,
                    'display_name ' => $fname . ' ' . $lname,
                    'user_login' => $phone,
                    'user_pass' => $password,
                    'role' => 'customer',
                    'meta_input'   => array(
                        'billing_phone' => $phone,
                        'phone'         => $phone,
                    ),
                ]);
                if($user_id){

                    wp_set_current_user($user_id);
                    wp_set_auth_cookie($user_id);
                    $response = array(
                        'result' => 'success',
                    );
                    wp_send_json($response);

                }else{

                  $response = array(
                      'result' => 'error',
                  );
                  wp_send_json($response);

                }
              }

              if(isset($_POST['email']) && !empty($_POST['email'])){

                $email = $_POST['email'];
                $user_id = wp_insert_user([
                  'first_name' => $fname,
                  'last_name' => $lname,
                  'display_name ' => $fname . ' ' . $lname,
                  'user_login' => $email,
                  'user_pass' => $password,
                  'user_email' => $email,
                  'role' => 'customer',
                  'meta_input'   => array(
                      'billing_email' => $email,
                      'email'         => $email,
                  ),
              ]);
              if($user_id){

                  wp_set_current_user($user_id);
                  wp_set_auth_cookie($user_id);
                  $response = array(
                      'result' => 'success',
                  );
                  wp_send_json($response);

              }else{

                $response = array(
                    'result' => 'error',
                );
                wp_send_json($response);

              }

              }

            break;
            case 'forgotform':

              if(isset($_POST['phone']) && !empty($_POST['phone'])){
                $phone = $_POST['phone'];
                $numberWithoutFirstZero = ltrim( $phone, '0');
                global $wpdb;
                $query = $wpdb->prepare(
                    "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'billing_phone' AND meta_value = %s
                    UNION
                    SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'digits_phone_no' AND meta_value = %s",
                    $phone,
                    $numberWithoutFirstZero
                );
                $user_ids = $wpdb->get_col($query);
                if (!empty($user_ids)) {
                    $this->startSession($phone);
                    $user_id = $user_ids[0];
                    $user = get_user_by( 'ID', $user_id );
                    $mobile   = $phone;
                    $code = $this->code;
                    $bodyId   = $this->options['kaveh_pattern_sms'];
                    $username = $this->options['kaveh_username_sms'];
                    $password = $this->options['kaveh_password_sms'];
                    $fromnum = $this->options['kaveh_number_sms'];
                    $bodyId = $this->options['kaveh_pattern_sms'];
                    $message = $this->options['kaveh_matn_raygansms'];
                    $api = $this->options['kaveh_password_api'];
                    if($this->options['kaveh_sms_gateway'] === 'option-1'):
                      kavehsms::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-2'):
                      kavehsms::smsir($api, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-3'):
                      kavehsms::melipayamak($username, $password, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-4'):
                      kavehsms::kavehnegar($api, $mobile, $bodyId, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-5'):
                      kavehsms::raygansms($username, $password, $mobile, $message, $code);
                    elseif($this->options['kaveh_sms_gateway'] === 'option-6'):
                      kavehsms::webone($username, $password, $fromnum,$mobile, $message, $code);
                    endif;  
                    $response = array(
                      'result' => 'success',
                    );
                    wp_send_json($response);
                }else{
                    $response = array(
                      'result' => 'error',
                    );
                    wp_send_json($response);
                }
              }
              if(isset($_POST['email']) && !empty($_POST['email'])){
                $email = $_POST['email'];
                $user_by_email = get_user_by('email', $email);
                $user_by_billing_email = get_users([
                    'meta_key' => 'billing_email',
                    'meta_value' => $email,
                    'number' => 1,
                ]);
                if(!empty($user_by_email)){
                  $user = $user_by_email;
                }
                if(!empty($user_by_billing_email)){
                  $user = $user_by_billing_email;
                }
                if ($user) {
                  $user = $user[0];

                  $adt_rp_key = get_password_reset_key( $user );
                  $user_login = $user->user_login;
                  $rp_link = network_site_url("wp-login.php?action=rp&key=$adt_rp_key&login=" . rawurlencode($user_login), 'login') . '">' . network_site_url("wp-login.php?action=rp&key=$adt_rp_key&login=" . rawurlencode($user_login), 'login');
                  $message = "جهت بازیابی رمز عبور  از این لینک استفاده کنید: $rp_link";
                  wp_mail($user->user_email, 'Password Reset', $message);
                  $response = array(
                    'result' => 'success',
                  );
                  wp_send_json($response);
                }else{
                  $response = array(
                    'result' => 'error',
                  );
                  wp_send_json($response);
                }

              }
            break;
            case 'formforgotfinal':
              
              $phone = $_POST['phone'];
              $this->startSession($phone);
              $code = (int)$_POST['code'];
              $password = $_POST['pass'];
              $user_id = false;
              $numberWithoutFirstZero = ltrim( $phone, '0');
              global $wpdb;
              $query = $wpdb->prepare(
                  "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'billing_phone' AND meta_value = %s
                  UNION
                  SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'digits_phone_no' AND meta_value = %s",
                  $phone,
                  $numberWithoutFirstZero
              );
              $user_ids = $wpdb->get_col($query);
              $user_id = $user_ids[0];
              if($this->code == $code){
                  wp_set_password($password, $user_id);
                  wp_set_current_user($user_id);
                  wp_set_auth_cookie($user_id, true, false);
                  $response = array(
                      'result' => 'success',
                  );
                  wp_send_json($response);
              }else{
                  $response = array(
                      'result' => 'error',
                  );
                  wp_send_json($response);
              }
            break;
          }
          die();
      }

}