<?php
/*
Plugin Name: wp soluk login
Version: 1.5
Plugin URI: 
Description:
Author: Hassan Dehghanian (Edit Hamid V1.0)
Author URI: 
Network: False
*/

  if (is_multisite() && get_current_blog_id() === 1) {
    return;
  }
  require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
    
  define('MY_PLUGIN_PATH', plugin_dir_path(__FILE__));
  define('MY_PLUGIN_URL', plugin_dir_url(__FILE__));
  

  
  /*
  
  if (!file_exists(__DIR__ . '/sessions')) {
    mkdir(__DIR__ . '/sessions', 0755, true);
  }
  ini_set('session.save_path', __DIR__ . '/sessions');
  */
  
////////////////////////////////////////// session_path set
  $upload_dir = wp_upload_dir();
  $session_path = $upload_dir['basedir'] . '/login-sessions';
  
    if (!is_dir($session_path)) {
      wp_mkdir_p($session_path);
    }

    if ( is_dir($session_path) && is_writable($session_path) ) {
        ini_set('session.save_path', $session_path);
    } else {
        error_log('Custom session path failed.'. $session_path .'  >>Using default path host.');
    }
  session_start();
  
  
  require_once MY_PLUGIN_PATH . '/functions/public_fun.php';
  require_once MY_PLUGIN_PATH . '/functions/register_fun.php';
  require_once MY_PLUGIN_PATH . '/functions/captcha_fun.php';
  

  add_action('wp_enqueue_scripts', 'login_scripts');
    function login_scripts()
    {

      wp_enqueue_script(
          'soluk-scripts',
          MY_PLUGIN_URL . 'js/soluk-login.js',
          ['jquery'],
          filemtime( MY_PLUGIN_PATH . 'js/soluk-login.js' )
        );
      
 
      wp_enqueue_script(
          'soluk-validate-scripts',
          MY_PLUGIN_URL . 'js/jquery.validate.min.js',
          ['jquery'],
          filemtime( MY_PLUGIN_PATH . 'js/jquery.validate.min.js' )
        );
    }

    //if (!strpos($_SERVER['REQUEST_URI'], 'form_submit.php') && !strpos($_SERVER['REQUEST_URI'], 'admin-ajax.php'))
     // set_captcha_session();
    //^^^
    if ( !wp_doing_ajax() && !is_admin() ) 
      set_captcha_session();
    




////////////////////////////////////////////////////////////////////add login html page by shortcode
  add_shortcode('soluk_login', 'soluk_login_func');
  function soluk_login_func($atts)
  {

    do_action('wp_head');
    $admin = false;
    $user = wp_get_current_user();
    if (in_array('administrator', (array) $user->roles))
      $admin = true;

    if (!is_admin())
      include MY_PLUGIN_PATH . '/pages/login.php';
  }



//////////////////////////////////////////////////////////////////////////////////////////sending code login otp ajax
  add_action("wp_ajax_otp_send_func", "otp_send");
  add_action("wp_ajax_nopriv_otp_send_func", "otp_send");

  function otp_send()
  {

    if (check_login_register_time('login')) {
      session_start();
      $mobile = convertPersianNumbersToEnglish( sanitize_text_field( wp_unslash( $_POST['mobile'] ) ) );
      $captcha = convertPersianNumbersToEnglish(  $_POST['captcha']  );
      $user = get_user_by( 'email', $mobile );
      
      //global $wpdb;
      
      // دریافت شماره موبایل از جدول یوزرمتا
      //  $table = $wpdb->usermeta;
      //  $meta_key = $wpdb->prefix . 'mobile';
      //  $sql = $wpdb->prepare(
      //    "SELECT * FROM {$table} WHERE meta_key = %s AND meta_value = %s", $meta_key, $mobile );
      

      // دریافت شماره مبایل از جدول یوزر
      //$table = $wpdb->users;
      //$mobile_field = 'user_email';
      //$caps = $wpdb->prefix .'capabilities'  
      //$sql = $wpdb->prepare(
      //    "SELECT * FROM {$table} WHERE {$mobile_field} = %s", $mobile );
      // $row = $wpdb->get_results($sql);
      // $row = $wpdb->get_row($sql);
     
      
      
      if ( !empty($user) ) {

        //$url = $_SERVER['SERVER_NAME'];
        //$user_id = $row[0]->user_id; //with usermeta
        //$user_id = $row->ID; // with users
        //$user = get_user_by('id', $user_id);
        
        $userid = $user->ID;
        $user_roles = $user->roles;
        /*
        $users_id_this_site = get_users(array(
          'fields' => 'ID'
        ));
        */
        if (isset($_SESSION['x']) && $_SESSION['x'] == $captcha) {
          //if ($userid > 0) 
          //if (in_array($userid, $users_id_this_site)) 
          if ( !empty($userid) && is_user_member_of_blog( $userid ) && count($user_roles) > 0 ) 
          {

           /* if (!check_user_have_role($user)) 
            {
              set_captcha_session();
              $captcha = get_captcha(true);
              echo 'pending|' . $captcha;
              die();
              exit();
            }
            */
            $otp_code = rand(5696, 9696); // ساخت کد پیامکی
            
            $otp_array = array();
            $otp_array[0] = $otp_code;
            $otp_array[1] = 4; //محدودیت تعداد ورود otp  اشتباه
            $otp_array[2] = $userid ; // ID کاربر 
            $otp_array[3] = $mobile ;   //شماره تلفن کاربر
            
            $data_json = json_encode($otp_array);

            //update_user_meta($userid,'otp_random',$data_json);
            $_SESSION['soluk_otp'] = $data_json;
            
            $input_data = $otp_code;
            $patt = get_theme_mod('pattern_code_login');
            $mobile = substr($mobile, 1);
            $res = send_sms($mobile, $patt, $input_data);

            if (strlen($res) > 3)
              echo 'code_sent';
            else {
              set_captcha_session();
              $captcha = get_captcha(true);
              echo $res . '|' . $captcha;
            }
          } else {

            set_captcha_session();
            $captcha = get_captcha(true);
            echo 'not_access|' . $captcha;
          }
        } else {
          set_captcha_session();
          $captcha = get_captcha(true);
          echo 'captcha_error|' . $captcha;
        }
      } else {
        set_captcha_session();
        $captcha = get_captcha(true);
        echo 'not_found|' . $captcha;
      }
    } else {
        echo 'زمان ورود به پایان رسیده';
      }

    wp_die();
  }




///////////////////////////////////////////////////////////////////////////////////login otp ajax check otp validation
  add_action("wp_ajax_otp_validation_func", "otp_validation");
  add_action("wp_ajax_nopriv_otp_validation_func", "otp_validation");

  function otp_validation()
  {
    session_start();
    $mobile = convertPersianNumbersToEnglish(sanitize_text_field(wp_unslash($_POST['mobile'])));
    $otp_input = convertPersianNumbersToEnglish(sanitize_text_field(wp_unslash($_POST['otp'])));
    
    $otp = $_SESSION['soluk_otp'];
    $new_otp_array = $otp_array = json_decode($otp);
    
    
    global $wpdb;
    
    // دریافت شماره موبایل از جدول یوزرمتا
    //$table = $wpdb->usermeta;  // جدول داینامیک
    //$meta_key = $wpdb->prefix . 'mobile';   // meta_key داینامیک
   /* $sql = $wpdb->prepare(
      "SELECT * FROM {$table} WHERE meta_key = %s AND meta_value = %s",
      $meta_key,
      $mobile
    );*/
    
    // دریافت شماره مبایل از جدول یوزر
     // $table = $wpdb->users;
      //$mobile_field = 'user_email';
      //$sql = $wpdb->prepare(
      //  "SELECT * FROM {$table} WHERE {$mobile_field} = %s",
      //  $mobile
      //);
      //$row = $wpdb->get_results($sql);

    
    if ( !empty($new_otp_array) ) 
    {
      //$url = $_SERVER['SERVER_NAME'];
      //$user_id = $row[0]->user_id;//with usermeta
      //$user_id = $row[0]->ID; // with users
      $user_id = $new_otp_array[2]; // with users
      $user = get_user_by('id', $user_id);
      $userid = $user->ID;
      //$user_roles = $user->roles;
      
      /*
      $users_id_this_site = get_users(array(
          'fields' => 'ID'
        ));
      */
      
      //if ($userid > 0) {
      //if (in_array($userid, $users_id_this_site)) 
        if( !empty($user) ) {
            
           /* 
          if (!check_user_have_role($user)) {
            echo 'pending';
            die();
            exit();
          }
          */
          
          //$otp = $_SESSION['soluk_otp'];
          //$new_otp_array = $otp_array = json_decode($otp);
          $new_otp_array[1] = $new_otp_array[1] - 1 ;
          $data_json = json_encode($new_otp_array);
          //update_user_meta($userid,'otp_random',$data_json);
          $_SESSION['soluk_otp'] = $data_json;
          
          
          if ($new_otp_array[1] >= 0) {
            if ($otp_array[0] == $otp_input) {
              clean_user_cache($userid);
              wp_clear_auth_cookie();

              wp_set_current_user($userid);
              wp_set_auth_cookie($userid, true, false);
              do_action('wp_login', $user->user_login);

              echo 'success';
            } else
                echo 'error'. $new_otp_array[1];
          } else
              echo 'redirect';
        }else{
             echo 'not_register';
        }
        
    } else {
      //set_captcha_session();
      //$captcha = get_captcha(true);
      echo 'not_register';
      //echo 'not_found|' . $captcha;
    }

    wp_die();
  }




?>