<?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', 'Auth', 'Dmailer', 'cart'));
        $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/', '');
        }
        $data['heading_title'] = "Login";
        $data['unq_section'] = "Login";
        $this->load->view('users_login', $data);
    }
    
    
    public function otp_login() {
        $data['heading_title'] = "OTP Login";
        $data['unq_section'] = "OTP Login";
        $this->load->view('users_otp_login', $data);
    }
           
    
    public function sendotp() {
        $smsres = "";
        $mobile = $this->input->post('mobile');
        $this->session->set_userdata('mobilenumber', $mobile); 
        $user = $this->users_model->check_user($mobile);
        if ($user) {
            $site_url=rawurlencode(base_url());
            $otp = substr(str_shuffle('1234567890'), 0, 6);
            $tempid = "1207164562264213561";
//        msg  for login
      $message = "Dear%20User%2C%20OTP%20to%20sign%20in%20to%20your%20account%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20VISIT%20Toyzoo%20Store%20%7B$site_url%7D";   
            
            if(sendSms($mobile,$message,$tempid))
            {
                $data = $this->users_model->saveotp($mobile, $otp);
                $this->session->set_userdata('mobnumber',$mobile);
                 echo $res = 'success';   
            }
            else
            {
                echo $res = 'error1';
            }
            
            
        } else {
            
            echo $res = 'error2';
        }
    }
    
    //          for registration resend otp
    public function reg_resendotp() {
        
        $mobile = $this->input->post('mobile');
        $this->session->set_userdata('mobilenumber', $mobile); 
        $user = $this->users_model->check_mobile($mobile);
        if ($user) {
            $otp = substr(str_shuffle('1234567890'), 0, 6);
            $site_url=rawurlencode(base_url());
            $tempid = "1207164562232826573";
             // msg for registration
            $message = "Dear%20User%2C%20OTP%20for%20Mobile%20No.%20Verification%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20visit%20Toyzoo%20Store%20%7B$site_url%7D";
            
            if(sendSms($mobile,$message,$tempid))
            {
                $data = $this->users_model->saveotp($mobile, $otp);
                 echo $res = 'success';   
            }
            else
            {
                echo $res = 'error1';
            }
               
        } else {
            
            echo $res = 'error2';
        }
    }
    
    
    public function loginotp() {
        $mobile = $this->input->post('mobile');
        $otp = $this->input->post('otp');
        if ($this->users_model->verify($mobile, $otp)) {
            $query = $this->db->query("SELECT * FROM wps_customers WHERE mobile_number='" . $mobile . "'");
            $row = $query->row_array();
            $username = $row['user_name'];
            $password = $row['password'];
            $this->auth->verify_user($username, $password);
            if ($this->auth->is_user_logged_in()) {
                $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 {
                    redirect('my-account', '');
                }
            } else {
                redirect('otp_login');
            }
        } else {
            redirect('otp_login');
        }
    }
    
    
    public function login() {
        if (!$this->auth->is_user_logged_in()) {
            $this->form_validation->set_rules('login_mobile', 'Username', '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');
                }
                $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->input->post('ref');
                    if ($ref != "") {
                        redirect($ref, '');
                    } else {
                        redirect('my-account', '');
                    }
                } else {
                    $this->session->set_userdata(array('msg_type' => 'error'));
                    $this->session->set_flashdata('error', ' Invalid username/password or un-verified Account');
                    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('my-account', 'refresh');
        }
    }
    
    
    public function login_validate() {
        $username = $this->input->post('login_mobile');
        $password = $this->input->post('login_password');
        $this->auth->verify_user($username, $password);
        if ($this->auth->is_user_logged_in()) {
            $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');
            echo $res = "success";
        } else {
            echo $res = "error";
        }
    }
    
    
    public function otplogin_validate() {
        $mobile = $this->session->userdata('mobilenumber');
        $otp = $_POST['otp'];
        if ($this->users_model->verify($mobile, $otp)) {
            $row = $this->db->query("SELECT * FROM wps_customers WHERE mobile_number='" . $mobile . "'")->row_array();
            $username = $row['user_name'];
            $password = $row['password'];
            $this->auth->verify_user($username, $password);
            if ($this->auth->is_user_logged_in()) {
                $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');
            }
            echo $res = "success";
        } else {
            echo $res = "error";
        }
    }
    

    
    public function logout() {
        $data2 = array('shipping_id' => 0, 'coupon_id' => 0, 'discount_amount' => 0);
        $this->session->unset_userdata($data2);
        $this->session->unset_userdata('reg_data');
        $this->session->unset_userdata('mobilenumber');
        $this->session->unset_userdata(array("ref" => '0'));
     
        $this->auth->logout();
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Logout Successfully.');
        redirect('login', '');
        
    }
    
    
    public function register() {
        if (!$this->auth->is_user_logged_in()) {
            if ($this->input->get_post('action') == 'register') {
        
                $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|alpha|max_length[32]');
                $this->form_validation->set_rules('email_address', 'Email ID', 'trim|required|valid_email|max_length[80]|callback_email_check');
                $this->form_validation->set_rules('mobile_number', 'Mobile No', 'trim|required|numeric|min_length[10]|max_length[15]');
                $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) {
                    
                    $data = ['f_name' => $this->input->post('first_name'), 'l_name' => "", 'username' => $this->input->post('email_address'), 'password' => $this->input->post('password'), 'mobile' => $this->input->post('mobile_number'), ];
                    $mobile = $data['mobile'];
                    $otp = substr(str_shuffle('1234567890'), 0, 6);
                    $site_url=rawurlencode(base_url());
                    $tempid = "1207164562232826573";
                    // for registration
                    $message = "Dear%20User%2C%20OTP%20for%20Mobile%20No.%20Verification%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20visit%20Toyzoo%20Store%20%7B$site_url%7D";
                    
                    $this->session->set_userdata('regg_data', $data);
                    
                    if(sendSms($mobile,$message,$tempid))
                    {
                        $this->users_model->saveotp($mobile, $otp);
                        $this->session->set_flashdata('success', $message);
                        
                        redirect('verify-otp'); 
                    }
                    else
                    {
                        $this->session->set_flashdata('success', $message);
                        redirect('verify-otp', 'refresh');
                    }
         
                }
            }
            $data['heading_title'] = "Register";
            $data['unq_section'] = "Register";
            $this->load->view('users_register', $data);
        } else {
            redirect('verify-otp', 'refresh');
        }
    }
    
    public function register_user() {
        if (!$this->auth->is_user_logged_in()) {
            if ($this->input->post('action')=='register') {
                $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|alpha|max_length[32]');
                $this->form_validation->set_rules('email_address', 'Email ID', 'trim|required|valid_email|max_length[80]|callback_email_check');
                $this->form_validation->set_rules('mobile_number', 'Mobile No', 'trim|required|numeric|min_length[10]|max_length[15]');
                $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) {
                    $data = ['f_name' => $this->input->post('first_name'), 'l_name' => "", 'username' => $this->input->post('email_address'), 'password' => $this->input->post('password'), 'mobile' => $this->input->post('mobile_number'), ];
                    $mobile = $data['mobile'];
                    $otp = substr(str_shuffle('1234567890'), 0, 6);
                    $site_url = rawurlencode(base_url());
                    $tempid = "1207164562232826573";
                    
                    $this->session->set_userdata('reg_data', $data);
                    // msg for registration
                    $message = "Dear%20User%2C%20OTP%20for%20Mobile%20No.%20Verification%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20visit%20Toyzoo%20Store%20%7B$site_url%7D";
                    
                    
                     if(sendSms($mobile,$message,$tempid))
                    {
                        $this->users_model->saveotp($mobile, $otp); 
                        $this->session->set_userdata('mobnumber', $mobile);
                        echo $res = "success";
                    }
                    else
                    {
                        echo $res = "error1";
                    }
                   
                }
                 else{
                    echo $res1 = "error2"; 
                 }
            }
            else{
                 echo $res2 = "error3";
            }    
    }
    }
    
    
    public function otp_reg_validate() {
        
        $res = $this->session->userdata('reg_data');
        $mobile = $res['mobile'];
        $otp = $this->input->post('otp');
        if ($this->users_model->verify($mobile, $otp)) {
            $registerId = $this->users_model->create_newuser($res);
            if ($registerId) {
                $query = $this->db->query("SELECT * FROM wps_customers WHERE mobile_number='" . $mobile . "'");
                $row = $query->row_array();
                $username = $row['user_name'];
                $password = $row['password'];
                $this->auth->verify_user($username, $password);
                if ($this->auth->is_user_logged_in()) {
                    $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 */
                    echo $res = "success";
                    
                } else {
                    echo $res = "error";
                }
            } else {
                echo $res = "error";
            }
        } else {
            echo $res = "error";
        }
    }
    
    public function verify_otp() {
        $this->load->view('users_verifyotp');
    }
    
    
    public function v_otp() {
        
        $ress = $this->session->userdata('regg_data');
        $mobile = $ress['mobile'];
        $otp = $this->input->post('otp');
        if ($this->users_model->verify($mobile, $otp)) {
            $registerId = $this->users_model->create_newuser($ress);
            if ($registerId) {
                $query = $this->db->query("SELECT * FROM wps_customers WHERE mobile_number='" . $mobile . "'");
                $row = $query->row_array();
                $username = $row['user_name'];
                $password = $row['password'];
                $this->auth->verify_user($username, $password);
                if ($this->auth->is_user_logged_in()) {
                    $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 {
                        redirect('my-account', '');
                    }
                } else {
                    $this->session->set_flashdata('regerror', '<div class="alert alert-danger"><strong> Wrong! OTP <button type="button" class="close" data-bs-dismiss="alert" aria-hidden="true"><i class="fa fa-remove"></i></button></div>');
                    redirect('verify-otp', "");
                }
            } else {
                $this->session->set_flashdata('regerror', '<div class="alert alert-danger"><strong> Wrong! OTP <button type="button" class="close" data-bs-dismiss="alert" aria-hidden="true"><i class="fa fa-remove"></i></button></div>');
                redirect('verify-otp', "");
            }
        } else {
            $this->session->set_flashdata('regerror', '<div class="alert alert-danger"><strong> Wrong! OTP </strong><button type="button" class="close" data-bs-dismiss="alert" aria-hidden="true"><i class="fa fa-remove"></i></button></div>');
            redirect('verify-otp', "");
        }
    }
    
 
    
    public function forgotten_password_old() {
        $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 = md5($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}', SITENAME, $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' => SITENAME, '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', ' Please check your email account to reset your password!');
                redirect('forgot-password', '');
            } else {
                $this->session->set_userdata(array('msg_type' => 'error'));
                $this->session->set_flashdata('error', ' Email id does not exist.');
                redirect('forgot-password', '');
            }
        }
        $data['heading_title'] = "Forgot Password";
        $this->load->view('users_forgot_password', $data);
    }
    
        public function forgotten_password() {
    
        $data['heading_title'] = "Forgot Password";
        $this->load->view('users_forgot_password', $data);
    }
    
    
    public function forgottenpassword() {
        
       
        $username = $this->input->post('username');
        $user = $this->users_model->check_user($username);
            if($user['mobile_number']==$username)
            {
               
            $mobile = $user['mobile_number'];
            $this->session->set_userdata('mobilenumber',$mobile);
            $otp = substr(str_shuffle('1234567890'), 0, 6);
            $site_url = rawurlencode(base_url());
            $tempid = "1207164562251262511";
            // for reset password
             $message = "Dear%20user%2C%20OTP%20to%20RESET%20your%20password%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20visit%20Toyzoo%20store%20%7B$site_url%7D";
                      
            if(sendSms($mobile,$message,$tempid))
            {
                $data = $this->users_model->saveotp($mobile, $otp);
                $this->session->set_userdata('mobnumber',$mobile);
                 echo $res = 'success';   
            }
            else
            {
                echo $res = 'error';
            }
            }
            else if($user['user_name']==$username)
            {
                  if (is_array($user) && !empty($user['user_name'])) {
                $first_name = $user['first_name'];
                $userId = md5($user['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}', SITENAME, $body);
                $body = str_replace('{url}', base_url(), $body);
                $body = str_replace('{link}', $verify_url, $body);
                $mail_conf = array('subject' => $subject, 'to_email' => $user['user_name'], 'from_email' => $this->admin_info->admin_email, 'from_name' => SITENAME, 'body_part' => $body);

                $this->dmailer->mail_notify($mail_conf);
                $this->session->set_flashdata('success', 'Please check your email account to reset your password!');
                echo $res = 'success1';
                
            }
                else
            {
                $this->session->set_flashdata('error', 'Email id does not exist.');
                echo $res = 'error1';
            }
            }
        
            
    }
    
    
    public function forget_otp_auth()
    {
        $mobile = $this->session->userdata('mobilenumber');
        $otp = $this->input->post('otp');
        if ($this->users_model->verify($mobile, $otp)) {
            echo $res = "success";
        } else {
            echo $res = "error";
        }
    }
    
    
     public function set_forget_password()
    {
        if ($this->input->post('password')) {
            $password = $this->input->post('password');
            $data = array('password' => $password);
            $where = "mobile_number=" . $this->session->userdata('mobilenumber') . " ";
            $this->members_model->safe_update('wps_customers', $data, $where, FALSE);
            echo $res = "success";
        } else {
            echo $res = "error";
        }
    }
    
    
     //          for Forget resend otp
    public function forget_resendotp() {
        
        $mobile = $this->session->userdata('mobilenumber'); 
        $user = $this->users_model->check_mobile($mobile);
        if ($user) {
            $otp = substr(str_shuffle('1234567890'), 0, 6);
            $site_url = rawurlencode(base_url());
            $tempid = "1207164562251262511";
            // for reset password
             $message = "Dear%20user%2C%20OTP%20to%20RESET%20your%20password%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20visit%20Toyzoo%20store%20%7B$site_url%7D";
                      
            if(sendSms($mobile,$message,$tempid))
            {
                $data = $this->users_model->saveotp($mobile, $otp);
                $this->session->set_userdata('mobnumber',$mobile);
                 echo $res = 'success';   
            }
            else
            {
                echo $res = 'error';
            } 
            
        } else {
            
            echo $res = 'error2';
        }
    }
    
    
    public function reset_password() {
        $userId = $this->uri->segment(3);
        $mres = get_db_single_row("wps_customers", "*", "md5(customers_id) = '" . $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->input->post('new_password');
                $data = array('password' => $password);
                $where = " md5(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('login', '');
            }
            /* End  member change password  */
            $data['heading_title'] = "Reset Password";
            $this->load->view('users_reset_password', $data);
        } else {
        }
    }
    
    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', "Email Address / Usename Already Exists!");
            return FALSE;
        } else {
            return TRUE;
        }
    }
    
    public function verify() {
        echo $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 customers_id = '" . $id . "'");
        $password = $this->safe_encrypt->decode($mres['password']);
        $username = $mres['user_name'];
        $this->auth->verify_user($username, $password);
        redirect(base_url() . "my-account");
    }
}
/* End of file users.php */
/* Location: ./application/modules/users/controller/users.php */