<?php



class Users extends Public_Controller
{



  public function __construct()
  {

    parent::__construct();

    $this->load->helper(array('date', 'language', 'cookie', 'file'));

    $this->load->model(array('users/users_model', 'pages/pages_model', 'members/members_model'));

    $this->load->library(array('safe_encrypt', 'securimage_library', 'Auth', 'Dmailer', 'mailer', 'cart'));

    $this->lang->load('portuguese', 'portuguese');

    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");



    $rf_session = $this->session->userdata('ref');

    if ($rf_session == '' && $this->input->get('ref') != "") {

      $this->session->set_userdata(array('ref' => $this->input->get('ref')));
    }
  }



  public function index()
  {



    if ($this->auth->is_user_logged_in()) {

      redirect('members/', '');
    }

    //$condition       = array('friendly_url'=>'login','status'=>'1');			 

    //$content         = $this->pages_model->get_cms_page( $condition );				 

    //$data['page_content'] = $content;	

    $data['heading_title'] = "Login";

    $data['unq_section'] = "Login";

    $this->load->view('users_register', $data);
  }



  public function forgotten_password()
  {

    if ($this->input->post('forgotme') != "") {

      $email = $this->input->post('email', TRUE);

      $this->form_validation->set_rules('email', ' Email ID', 'required|valid_email');



      if ($this->form_validation->run() == TRUE) {

        $condtion = array('field' => "customers_id,first_name,user_name", 'condition' => "user_name ='" . $email . "' AND status ='1' ");

        $res = $this->users_model->find('wps_customers', $condtion);

        if (is_array($res) && !empty($res)) {

          $first_name = $res['first_name'];

          $userId = $this->safe_encrypt->encode($res['customers_id']);



          $content = get_content('wps_auto_respond_mails', '2');

          $subject = $content->email_subject;

          $body = $content->email_content;



          $verify_url = "<a href=" . base_url() . "users/reset_password/" . $userId . ">Reset Password</a>";

          $name = $first_name;

          $body = str_replace('{mem_name}', $name, $body);

          $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);

          $body = str_replace('{site_name}', $this->config->item('site_name'), $body);

          $body = str_replace('{url}', base_url(), $body);

          $body = str_replace('{link}', $verify_url, $body);



          $mail_conf = array(

            'subject' => $subject,

            'to_email' => $res['user_name'],

            'from_email' => $this->admin_info->admin_email,

            'from_name' => $this->config->item('site_name'),

            'body_part' => $body

          );

          trace($mail_conf);

          //die;

          $this->dmailer->mail_notify($mail_conf);

          //Mail End



          $this->session->set_userdata(array('msg_type' => 'success'));

          $this->session->set_flashdata('success', $this->config->item('forgot_password_success'));

          redirect('users/forgotten_password', '');
        } else {

          $this->session->set_userdata(array('msg_type' => 'validation'));

          $this->session->set_flashdata('validation', $this->config->item('email_not_exist'));

          redirect('users/forgotten_password', '');
        }
      }
    }

    $data['heading_title'] = "Forgot Password";

    $this->load->view('users_forgot_password', $data);
  }



  public function reset_password()
  {

    $userId = $this->safe_encrypt->decode($this->uri->segment(3));

    $mres = $this->members_model->get_member_row($userId);

    $data['mres'] = $mres;

    if (is_array($mres) && !empty($mres)) {

      $this->form_validation->set_rules('new_password', 'New Password', 'trim|required|valid_password');

      $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[new_password]');



      if ($this->form_validation->run() == TRUE) {

        $password = $this->safe_encrypt->encode($this->input->post('new_password'));

        $data = array('password' => $password);

        $where = "customers_id=" . $userId . " ";

        $this->members_model->safe_update('wps_customers', $data, $where, FALSE);

        $this->session->set_userdata(array('msg_type' => 'success'));

        $this->session->set_flashdata('success', 'Your Password has been updated, please login now!');

        redirect('users/register', '');
      }

      /* End  member change password  */

      $data['heading_title'] = "Reset Password";

      $this->load->view('users_reset_password', $data);
    } else {
    }
  }



  public function direct_login()
  {

    if (!$this->auth->is_user_logged_in()) {

      //$this->form_validation->set_rules('login_username', 'Username','trim|required|valid_email');

      //$this->form_validation->set_rules('login_password', 'Password', 'trim|required|');			

      //$this->form_validation->set_rules('user', 'User', 'trim');

      //if ($this->form_validation->run() == TRUE){

      $username = $this->input->get_post('username');

      $password = $this->safe_encrypt->decode($this->input->get_post('mypass'));



      $this->auth->verify_user($username, $password);

      if ($this->auth->is_user_logged_in()) {



        $ref = $this->session->userdata('ref');

        $this->session->unset_userdata(array('ref' => 0));

        if ($ref != "") {

          redirect($ref, '');
        } else {

          redirect('members/myaccount', '');
        }
      } else {

        $this->session->set_flashdata('error', $this->config->item('login_failed'));

        redirect('login', '');
      }

      //}

      //$condition       = array('friendly_url'=>'login','status'=>'1');			 

      //$content         = $this->pages_model->get_cms_page( $condition );				 

      //$data['page_content'] = $content;	

      $data['heading_title'] = "Login";

      $this->load->view('users_login', $data);
    } else {

      redirect('members/myaccount', 'refresh');
    }
  }



  public function login()
  {

    if (!$this->auth->is_user_logged_in()) {

      $this->form_validation->set_rules('login_mobile', 'Mobile', 'trim|required|');

      $this->form_validation->set_rules('login_password', 'Password', 'trim|required|');

      if ($this->form_validation->run() == TRUE) {

        $username = $this->input->post('login_mobile');

        $password = $this->input->post('login_password');

        $rember = ($this->input->post('remember') != "") ? TRUE : FALSE;

        if ($this->input->post('remember') == "Y") {

          set_cookie('userName', $this->input->post('login_email'), time() + 60 * 60 * 24 * 30);

          set_cookie('pwd', $this->input->post('login_password'), time() + 60 * 60 * 24 * 30);
        } else {

          delete_cookie('userName');

          delete_cookie('pwd');
        }

        $usrStatus = get_db_field_value("wps_customers", "is_verified", "WHERE user_name = '" . $username . "' AND password = '" . $this->safe_encrypt->encode($password) . "'");


        if ($usrStatus == '1') {

          $this->auth->verify_mobile_user($username, $password);

          if ($this->auth->is_user_logged_in()) {

            /* Saving Login Ip Address */

            $ip_array = array(

              'member_id' => $this->session->userdata('user_id'),

              'ip_address' => $_SERVER['REMOTE_ADDR'],

            );

            $insId = $this->users_model->safe_insert('wps_ip_details', $ip_array, FALSE);

            /* End Here */

            $ref = $this->input->post('ref');

            if ($ref != "") {

              redirect($ref, '');
            } else {

              $compIdVerification = $this->input->post('compIdVerification');

              $this->session->set_userdata('compIdVerification', $compIdVerification);

              if ($compIdVerification > 0) {

                redirect($_SERVER['HTTP_REFERER'], '');
              } else {

                redirect('members/myaccount', '');
              }
            }
          } else {

            $this->session->set_userdata(array('msg_type' => 'error'));

            $this->session->set_flashdata('error', $this->config->item('login_failed'));

            redirect('login', '');
          }
        } else {

          $this->session->set_userdata(array('msg_type' => 'error'));

          $this->session->set_flashdata('error', "Your Verification is Pending, Kindly check your email for Verification Link or Contact Administartor.");

          redirect('login', '');
        }
      } else {

        echo validation_errors();
      }

      $condition = array('friendly_url' => 'login', 'status' => '1');

      $content = $this->pages_model->get_cms_page($condition);

      $data['page_content'] = $content;

      $data['heading_title'] = "Login";

      $this->load->view('users_login', $data);
    } else {

      redirect('members/myaccount', 'refresh');
    }
  }



  public function logout()
  {

    $data2 = array(

      'shipping_id' => 0,

      'coupon_id' => 0,

      'discount_amount' => 0

    );

    $this->session->unset_userdata($data2);

    $this->session->unset_userdata(array("ref" => '0'));

    //$this->cart->destroy();

    $this->auth->logout();



    $this->session->set_userdata(array('msg_type' => 'success'));

    $this->session->set_flashdata('success', $this->config->item('member_logout'));

    //redirect('users/login', '');

    redirect($_SERVER['HTTP_REFERER'], '');
  }



  public function thanks()
  {

    $data['heading_title'] = "Thanks";

    $this->load->view('users_thanks', $data);
  }



  public function register()
  {

    if (!$this->auth->is_user_logged_in()) {

      if ($this->input->get_post('action') == 'register') {

        $mobile_number = $this->input->post('mobile_number');
        //$email = $this->input->post('email');
        
       // $this->form_validation->set_rules('district_head_id', 'District Head', 'trim|required');
       //$this->form_validation->set_rules('kisan_mitra_id', 'Kisan Mitra', 'trim|required');
        //$this->form_validation->set_rules('kisan_sahayak_id', 'KM Sahyogi', 'trim|required');
        $this->form_validation->set_rules('country_id', 'Country', 'trim|required');
        $this->form_validation->set_rules('state_id', 'State', 'trim|required');
        $this->form_validation->set_rules('city_id', 'District', 'trim|required');
        $this->form_validation->set_rules('block_id', 'Block', 'trim|required');
        $this->form_validation->set_rules('panchayat_id', 'Panchayat', 'trim|required');
        $this->form_validation->set_rules('village_id', 'Village', 'trim|required');
    
        $this->form_validation->set_rules('first_name', 'Kisaan Name', 'trim|required|alpha|max_length[80]');
        $this->form_validation->set_rules('fathers_name', "Father's Name", 'trim|required|alpha|max_length[80]');
        $this->form_validation->set_rules('birth_date', "D.O.B.", 'trim|required|max_length[80]');
        $this->form_validation->set_rules('mobile_number', 'Mobile No.', 'trim|required|numeric|max_length[10]|unique[wps_customers.mobile_number ="' . $mobile_number . '"]');
        $this->form_validation->set_rules('alt_name', 'Alternate Name', 'trim|alpha|max_length[80]');
        $this->form_validation->set_rules('alt_mobile', 'Alternate Mobile No.', 'trim|max_length[10]|numeric');
        $this->form_validation->set_rules('relationship', 'Relationship', 'trim|alpha|max_length[80]');
        $this->form_validation->set_rules('land_size_owned', 'Land Size (Owned)', 'trim|required|is_valid_amount|max_length[20]');
        $this->form_validation->set_rules('land_size_owned_unit', 'Land Size Unit (Owned) ', 'trim|required');
        $this->form_validation->set_rules('land_size_leased', 'Land Size (Leased)', 'trim|required|is_valid_amount|max_length[20]');
        $this->form_validation->set_rules('land_size_leased_unit', 'Land Size Unit (Leased)', 'trim|required');
        $this->form_validation->set_rules('total_land_size', 'Total Land Size', 'trim|required|is_valid_amount|max_length[25]');
        $this->form_validation->set_rules('total_land_size_unit', 'Total Land Size Unit', 'trim|required');
        $this->form_validation->set_rules('current_annual_income', 'Current Annual Income', 'trim|required|max_length[80]');
        $this->form_validation->set_rules('major_issues', 'Major Issues/Problems/Challenges Faced by Farmer', 'trim|required|max_length[499]');
            
        $this->form_validation->set_rules('password', 'Password', 'trim|required|max_length[20]|valid_password');
        $this->form_validation->set_rules('c_password', 'Confirm passsword', 'required|matches[password]');



        if ($this->form_validation->run() == TRUE){

          $registerId = $this->users_model->create_user();
          //$first_name = $this->input->post('first_name', TRUE);
          $username = $this->input->post('mobile_number', TRUE);
          $password = $this->input->post('password', TRUE);

          $this->auth->verify_user($username, $password);
          $message = $this->config->item('register_thanks');
          $message = str_replace('<site_name>', $this->config->item('site_name'), $message);
          // $this->session->set_userdata(array('msg_type'=>'success'));
          $this->session->set_flashdata('success', $message);
          //$cart_items='';
          if ($this->cart->contents() != "" && count($this->cart->contents()) > 0) {
            redirect('cart', '');
          } else {
            redirect('members/myaccount', '');
          }
        }
      } elseif ($this->input->get_post('action') == 'login') {

        $this->form_validation->set_rules('login_email', 'Email ID', 'trim|required|valid_email');

        $this->form_validation->set_rules('login_password', 'Password', 'trim|required|');

        if ($this->form_validation->run() == TRUE) {

          $username = $this->input->post('login_email');

          $password = $this->input->post('login_password');

          $rember = ($this->input->post('remember') != "") ? TRUE : FALSE;

          if ($this->input->post('remember') == "Y") {

            set_cookie('userName', $this->input->post('login_email'), time() + 60 * 60 * 24 * 30);

            set_cookie('pwd', $this->input->post('login_password'), time() + 60 * 60 * 24 * 30);
          } else {

            delete_cookie('userName');

            delete_cookie('pwd');
          }

          $this->auth->verify_user($username, $password);

          if ($this->auth->is_user_logged_in()) {



            /* Saving Login Ip Address */

            $ip_array = array(

              'member_id' => $this->session->userdata('user_id'),

              'ip_address' => $_SERVER['REMOTE_ADDR'],

            );

            $insId = $this->users_model->safe_insert('wps_ip_details', $ip_array, FALSE);

            /* End Here */



            $ref = $this->session->userdata('ref');

            $this->session->unset_userdata(array('ref' => 0));

            if ($this->cart->total() > 0) {

              redirect('cart/delivery_info', '');
            }

            if ($ref != "") {

              redirect($ref, '');
            } else {

              redirect('members/myaccount', '');
            }
          } else {

            $this->session->set_userdata(array('msg_type' => 'validation'));

            $this->session->set_flashdata('validation', $this->config->item('login_failed'));

            redirect('register', '');
          }
        }
      }

      $data['heading_title'] = "Register";

      $data['unq_section'] = "Register";

      $data['landSizeUnitArray'] = $this->config->item('landSizeUnitArray');
  
      //$data['state'] = $this->db->query("select * from wps_states_list")->result_array();
      //$data['city'] = $this->db->query("SELECT * FROM `wps_cities_list` WHERE status='1' and temp_title IN (SELECT page_url from wps_meta_tags where is_fixed = 'L') order by id asc")->result_array();
      $data['country'] = $this->db->query("SELECT id,name FROM wps_countries_list WHERE status='1' ORDER BY name ASC")->result_array();
      $data['states'] = $this->db->query("SELECT id,name FROM wps_states_list WHERE status='1' ORDER BY name ASC")->result_array();
      $data['cities'] = $this->db->query("SELECT id,city FROM wps_cities_list WHERE status='1' ORDER BY city ASC")->result_array();
      $data['blocks'] = $this->db->query("SELECT id,name FROM `wps_blocks_list` WHERE status='1' order by name asc")->result_array();
      $data['panchayats'] = $this->db->query("SELECT id,name FROM `wps_panchayats_list` WHERE status='1' order by name asc")->result_array();
      $data['villages'] = $this->db->query("SELECT id,name FROM `wps_villages_list` WHERE status='1' order by name asc")->result_array();
  
      $this->load->view('users_register', $data);
    } else {

      redirect('members/myaccount', 'refresh');
    }
  }



  public function email_check()
  {

    $email = $this->input->post('email_address');

    if ($this->users_model->is_email_exits(array('user_name' => $email))) {

      $this->form_validation->set_message('email_check', $this->config->item('exists_user_id'));

      return FALSE;
    } else {

      return TRUE;
    }
  }



  public function valid_captcha_code($verification_code)
  {

    if ($this->securimage_library->check($verification_code) == true) {

      return TRUE;
    } else {

      $this->form_validation->set_message('valid_captcha_code', 'The Word verification code you have entered is invalid.');

      return FALSE;
    }
  }



  public function verify()
  {

    $id = $this->uri->segment(3);

    $mres = $this->db->query("SELECT user_name, password FROM wps_customers WHERE MD5(customers_id) = '" . $id . "'")->row_array();

    $this->db->query("UPDATE wps_customers SET is_verified = '1', status = '1' WHERE MD5(customers_id) = '" . $id . "'");

    $password = $this->safe_encrypt->decode($mres['password']);

    $username = $mres['user_name'];

    $this->auth->verify_user($username, $password);

    redirect(base_url() . "members/myaccount");
  }



  public function create_user()
  {

    //trace($this->input->post());

    //die;

    $mobile = $this->input->post('mobile');

    $email = $this->input->post('email');



    if ($email) {

      $usercount = count_record("wps_customers", "user_name = '" . $this->input->post('email') . "'");
    } else {

      $usercount = count_record("wps_customers", "user_name = '" . $this->input->post('mobile') . "'");
    }

    if ($usercount == 0) {

      $compIdVerification = $this->input->post('compIdVerification');

      $this->session->set_userdata('compIdVerification', $compIdVerification);

      $password = $otp = substr(str_shuffle('bcdfghjklmnprstvwxzaeiou1234567890'), 0, 6);

      $registerId = $this->users_model->create_mobile_user($mobile, $email, $password);

      $userName = ($mobile) ? $mobile : $email;

      $this->auth->verify_mobile_user($userName, $password);

      if ($mobile) {

        $message = "Thank you for Choosing NTI, Your Password is " . $password;

        sendSms($mobile, $message);

        if ($compIdVerification > 0) {

          echo 'V';
        } else {

          echo $registerId;
        }
      } else {

        /* Send  mail to user */

        $content = file_get_contents(site_url() . 'mailer/email-registered.html');

        //trace($content);

        //$content = get_content('wps_auto_respond_mails', '1');

        $subject = 'Welcome to Natural Therapy India';

        $body = $content;

        $verify_url = base_url() . "users/verify/" . md5($registerId);

        $name = " User ";

        $body = str_replace('{mem_name}', $name, $body);

        $body = str_replace('{username}', $userName, $body);

        $body = str_replace('{password}', $password, $body);

        $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);

        $body = str_replace('{site_name}', $this->config->item('site_name'), $body);

        //$body = str_replace('{url}', base_url(), $body);

        $body = str_replace('{link}', $verify_url, $body);



        $mail_conf = array(

          'subject' => $subject,

          'to_email' => $this->input->post('email'),

          'from_email' => $this->admin_info->admin_email,

          'from_name' => $this->config->item('site_name'),

          'body_part' => $body

        );

        //trace($mail_conf);

        //exit;

        $this->dmailer->mail_notify($mail_conf);

        /* End send  mail to user */

        if ($compIdVerification > 0) {

          echo 'V';
        } else {

          echo 'E';
        }
      }
    } else {

      if ($email) {

        $userName = get_db_field_value('wps_customers', 'first_name', "WHERE user_name='" . $email . "'");
      } else {

        $userName = get_db_field_value('wps_customers', 'first_name', "WHERE user_name='" . $mobile . "'");
      }

      $userName = ($userName) ? ' ' . $userName : ' User';

      echo 'R-' . $userName;
    }
  }
}



/* End of file users.php */

/* Location: ./application/modules/users/controller/users.php */