<?php
use gateways\SMSIRGateway;
use gateways\IPPANELGateway;
use gateways\MELLIPAYAMAKGateway;
use gateways\KAVEHNEGARGateway;
use gateways\Raygansms;
use gateways\WebOne;
use gateways\rahpayam;
use gateways\panelchi;

class kavehajaxLogin
{

  public $options;
  public $code;

  public function __construct()
  {
    if (is_user_logged_in()) {
      return;
    }

    $this->options = kaveh_get_options();

    // Register all AJAX actions
    add_action('wp_ajax_kaveh_smslogin', [$this, 'kaveh_smslogin']);
    add_action('wp_ajax_nopriv_kaveh_smslogin', [$this, 'kaveh_smslogin']);

    add_action('wp_ajax_kaveh_backupsms', [$this, 'kaveh_backupsms']);
    add_action('wp_ajax_nopriv_kaveh_backupsms', [$this, 'kaveh_backupsms']);

    add_action('wp_ajax_kaveh_formfinal', [$this, 'kaveh_formfinal']);
    add_action('wp_ajax_nopriv_kaveh_formfinal', [$this, 'kaveh_formfinal']);

    add_action('wp_ajax_kaveh_passlogin', [$this, 'kaveh_passlogin']);
    add_action('wp_ajax_nopriv_kaveh_passlogin', [$this, 'kaveh_passlogin']);

    add_action('wp_ajax_kaveh_passformfinal', [$this, 'kaveh_passformfinal']);
    add_action('wp_ajax_nopriv_kaveh_passformfinal', [$this, 'kaveh_passformfinal']);

    add_action('wp_ajax_kaveh_forgotform', [$this, 'kaveh_forgotform']);
    add_action('wp_ajax_nopriv_kaveh_forgotform', [$this, 'kaveh_forgotform']);

    add_action('wp_ajax_kaveh_formforgotfinal', [$this, 'kaveh_formforgotfinal']);
    add_action('wp_ajax_nopriv_kaveh_formforgotfinal', [$this, 'kaveh_formforgotfinal']);
  }

  public function kaveh_backupsms()
  {
    $this->handleAjaxRequest('backupsms');
  }

  public function kaveh_smslogin()
  {
    $this->handleAjaxRequest('smslogin');
  }

  public function kaveh_formfinal()
  {
    $this->handleAjaxRequest('formfinal');
  }

  public function kaveh_passlogin()
  {
    $this->handleAjaxRequest('passlogin');
  }

  public function kaveh_passformfinal()
  {
    $this->handleAjaxRequest('passformfinal');
  }

  public function kaveh_forgotform()
  {
    $this->handleAjaxRequest('forgotform');
  }

  public function kaveh_formforgotfinal()
  {
    $this->handleAjaxRequest('formforgotfinal');
  }




  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 handleAjaxRequest($request)
  {

    switch ($request) {
      case 'backupsms':
        $phone = $_POST['phone'];
        $this->startSession($phone);
        $mobile = $phone;
        $code = $this->code;
        $bodyId = $this->options['kaveh_pattern_sms2'];
        $username = $this->options['kaveh_username_sms2'];
        $password = $this->options['kaveh_password_sms2'];
        $fromnum = $this->options['kaveh_number_sms2'];
        $bodyId = $this->options['kaveh_pattern_sms2'];
        $message = $this->options['kaveh_matn_raygansms2'];
        $api = $this->options['kaveh_password_api2'];
        if ($this->options['kaveh_sms_gateway2'] === 'option-1'):
          IPPANELGateway::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
        elseif ($this->options['kaveh_sms_gateway2'] === 'option-2'):
          SMSIRGateway::smsir($api, $mobile, $bodyId, $code);
        elseif ($this->options['kaveh_sms_gateway2'] === 'option-3'):
          MELLIPAYAMAKGateway::melipayamak($username, $password, $mobile, $bodyId, $code);
        elseif ($this->options['kaveh_sms_gateway2'] === 'option-4'):
          KAVEHNEGARGateway::kavehnegar($api, $mobile, $bodyId, $code);
        elseif ($this->options['kaveh_sms_gateway2'] === 'option-5'):
          Raygansms::raygansms($username, $password, $mobile, $message, $code);
        elseif ($this->options['kaveh_sms_gateway2'] === 'option-6'):
          rahpayam::rahpayam($api, $mobile, (int) $bodyId, $code);
        elseif ($this->options['kaveh_sms_gateway2'] === 'option-7'):
          panelchi::panelchi($api, $mobile, $fromnum, $bodyId, $code);
        endif;
        $response = array(
          'result' => 'success',
        );
        wp_send_json($response);

        break;

      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'):
            IPPANELGateway::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-2'):
            SMSIRGateway::smsir($api, $mobile, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-3'):
            MELLIPAYAMAKGateway::melipayamak($username, $password, $mobile, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-4'):
            KAVEHNEGARGateway::kavehnegar($api, $mobile, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-5'):
            Raygansms::raygansms($username, $password, $mobile, $message, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-6'):
            rahpayam::rahpayam($api, $mobile, (int) $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-7'):
            panelchi::panelchi($api, $mobile, $fromnum, $bodyId, $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'):
            IPPANELGateway::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-2'):
            SMSIRGateway::smsir($api, $mobile, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-3'):
            MELLIPAYAMAKGateway::melipayamak($username, $password, $mobile, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-4'):
            KAVEHNEGARGateway::kavehnegar($api, $mobile, $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-5'):
            Raygansms::raygansms($username, $password, $mobile, $message, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-6'):
            rahpayam::rahpayam($api, $mobile, (int) $bodyId, $code);
          elseif ($this->options['kaveh_sms_gateway'] === 'option-7'):
            panelchi::panelchi($api, $mobile, $fromnum, $bodyId, $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'):
              IPPANELGateway::ippanel($username, $password, $mobile, $fromnum, $bodyId, $code);
            elseif ($this->options['kaveh_sms_gateway'] === 'option-2'):
              SMSIRGateway::smsir($api, $mobile, $bodyId, $code);
            elseif ($this->options['kaveh_sms_gateway'] === 'option-3'):
              MELLIPAYAMAKGateway::melipayamak($username, $password, $mobile, $bodyId, $code);
            elseif ($this->options['kaveh_sms_gateway'] === 'option-4'):
              KAVEHNEGARGateway::kavehnegar($api, $mobile, $bodyId, $code);
            elseif ($this->options['kaveh_sms_gateway'] === 'option-5'):
              Raygansms::raygansms($username, $password, $mobile, $message, $code);
            elseif ($this->options['kaveh_sms_gateway'] === 'option-6'):
              rahpayam::rahpayam($api, $mobile, (int) $bodyId, $code);
            elseif ($this->options['kaveh_sms_gateway'] === 'option-7'):
              panelchi::panelchi($api, $mobile, $fromnum, $bodyId, $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 = esc_html__("Use this link to reset your password: $rp_link", 'kavehTheme');
            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();
  }

}