<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class AuthController extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->model('AuthModel');
		$this->load->model('CountryModel');
		$this->load->model('SiteModel');
		$this->load->library('ciqrcode');
		$this->load->library('aws3');
	    $this->load->library("pagination");
	}

	public function index()
	{
		$site_url = $_SERVER['HTTP_HOST'];
		$site_url = str_replace("www.","",$_SERVER['HTTP_HOST']);
		$site_row = $this->SiteModel->get_row_from_url($site_url);

	    if(isset($this->session->userdata['makeabl2020'])){
			if($site_row['is_single_gallery'] == 1)
	        	redirect('sgallery', 'refresh');
			else
				redirect('mgallery', 'refresh');
	    }else{
    		$login_btn = $this->input->post('login_btn', TRUE);
    		if($login_btn == "ok"){
				$this->form_validation->set_rules('useremail', 'Email', 'trim|required');
				$this->form_validation->set_rules('userpassword', 'Password', 'trim|required');

				if ($this->form_validation->run() == FALSE) {
					$data = array(
						'errors' => validation_errors()
					);
					$this->session->set_flashdata('error', $data['errors']);
					redirect(base_url('login'),'refresh');
				} else {
					try {
						$useremail = $this->input->post('useremail', TRUE);
						$userpassword = $this->input->post('userpassword', TRUE);
			
						$result = $this->AuthModel->get_guest_row(" where email = '".$useremail."' and password = '".md5($userpassword)."'");
			
						if(count($result) > 0){
							if($result['isDeleted'] == 0){
								if($result['is_active'] == 1){	
									if($result['photo_url'] == "" && $result["qr_url"] == ""){
										redirect('face-recognition/'.$result['id'], 'refresh');
									}else{
										if($result["package_status"] == 0){
											$update_data = array(
												'last_login' => date('Y-m-d H:i:s')
											);
						
											$this->AuthModel->update_guest_row($update_data, array('id' => $result['id']));            	
											$this->session->set_userdata('makeabl2020', $result);
											if($site_row['is_single_gallery'] == 1)
												redirect('sgallery', 'refresh');
											else
												redirect('mgallery', 'refresh');
										}else{
											$this->session->set_flashdata('error', 'Your refund request is being processed. You can login after process again.');
											redirect(base_url('login'));
											exit();
										}
									}
								}else{
									$this->session->set_flashdata('error', 'You need to activate your account first. Please check your Email.');
									redirect(base_url('login'));
									exit();
								}
							}else{
								$this->session->set_flashdata('error', 'You have already deleted your account.');
								redirect(base_url('login'));
								exit();
							}
						}else{
							$this->session->set_flashdata('error', 'Sorry, we can not match your account.');
							redirect(base_url('login'));
							exit();
						}
					}catch(Exception $e) {
						$this->session->set_flashdata('error', $e->getMessage());
						redirect(base_url('login'));
						exit();
					}
				}
    		}
    
    		$data['title'] = 'Login | MAKEABL';
			$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
    
    		$this->load->view('auth/header', $data);
    		$this->load->view('auth/login', $data);	
    		$this->load->view('auth/footer', $data);
	    }
	}

   
    public function qr()
    {
        $this->load->view('auth/header');	
		$this->load->view('auth/qr');
		$this->load->view('auth/footer');
    }
    
    public function contentimage()
    {
        $site_url = str_replace("www.","",$_SERVER['HTTP_HOST']);
        $result = $this->AuthModel->get_bucketlist($site_url);
        if($result['location']!="")
        {
            $prefix = "Country/".str_replace(" ","_",$result['country'])."/".str_replace(" ","_",$result["site"])."/locations/".str_replace(" ","_",$result["location"])."/kiosk_image/";
        }
        else {
            $prefix = "Country/".str_replace(" ","_",$result['country'])."/".str_replace(" ","_",$result["site"])."/kiosk_image/";
        }
        $result  = $this->aws3->listobject($prefix);
        $config = array();
        $config["base_url"] = base_url()."contentimage";
        $config["total_rows"] = count($result);
        $config["per_page"] = 18;
        $config["uri_segment"] = 2;
        $this->pagination->initialize($config);
        $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
        $data["links"] = $this->pagination->create_links();
        $num = $page/18+1;
        if(count($result)>18*$num-1){
            $data["obj"] = array_slice($result,18*($num-1),18);
        }
        else{
            $data["obj"] = array_slice($result,18*($num-1),18);
        }
        $data["length"] = ceil(count($result)/18);
        $this->load->view('auth/header');	
		$this->load->view('auth/contentimage',$data);
		$this->load->view('auth/footer');
    }
    
    public function detailimage()
    {
        $data["url"] = $this->input->post("guestid", TRUE);
        $data["back"] = $this->input->post("backguestid", TRUE);
        $data["next"] = $this->input->post("nextguestid", TRUE);
        $data["qrurl"] = str_replace(".jpg","_qr.jpg",$this->input->post("guestid", TRUE));
        $this->load->view('auth/header');	
		$this->load->view('auth/detailimage',$data);
		$this->load->view('auth/footer');
    }
    
    public function contentimagePage()
    {
        $num = $this->input->post("num", TRUE);
        $site_url = str_replace("www.","",$_SERVER['HTTP_HOST']);
        $result = $this->AuthModel->get_bucketlist($site_url);
        $prefix = "Country/".str_replace(" ","_",$result['country'])."/".str_replace(" ","_",$result["site"])."/kiosk_image/";
        $result  = $this->aws3->listobject($prefix);
        if(count($result)>18*$num-1){
            $data["obj"] = array_slice($reult,18*($num-1),18*$num-1);
        }
        else{
            $data["page"] = "last";
            $data["obj"] = array_slice($reult,18*($num-1),count($result)-1);
        }
        
        $data["page"] = $num;
        $data["length"] = ceil(count($result)/18);
        $this->load->view('auth/header');	
		$this->load->view('auth/contentimage',$data);
		$this->load->view('auth/footer');
    }

    public function qrlogin()
    {
        $site_url = str_replace("www.","",$_SERVER['HTTP_HOST']);
		$site_row = $this->SiteModel->get_row_from_url($site_url);
        if(isset($this->session->userdata['makeabl2020'])){
			if($site_row['is_single_gallery'] == 1)
	        	redirect('sgallery', 'refresh');
			else
				redirect('mgallery', 'refresh');
	    }else{
    		$id = $this->input->post('guestid', TRUE);
			try {
				$result = $this->AuthModel->qr_guest_row(" where id = '".(int)$id."'");
				if(count($result) > 0){
					if($result['isDeleted'] == 0){
						if($result['is_active'] == 1){	
							if($result['photo_url'] == "" && $result["qr_url"] == ""){
								redirect('face-recognition/'.$result['id'], 'refresh');
							}else{
							    if($result["package_status"] == 0){
									$update_data = array(
										'last_login' => date('Y-m-d H:i:s')
									);
									
									$this->AuthModel->update_guest_row($update_data, array('id' => $result['id']));            	
									$this->session->set_userdata('makeabl2020', $result);
									if($site_row['is_single_gallery'] == 1)
										redirect('sgallery', 'refresh');
									else
										redirect('mgallery', 'refresh');
								}else{
									$this->session->set_flashdata('error', 'Your refund request is being processed. You can login after process again.');
									redirect(base_url('login'));
									exit();
								}
							}
						}else{
							$this->session->set_flashdata('error', 'You need to activate your account first. Please check your Email.');
							redirect(base_url('login'));
							exit();
						}
					}else{
						$this->session->set_flashdata('error', 'You have already deleted your account.');
						redirect(base_url('login'));
						exit();
					}
				}else{
					$this->session->set_flashdata('error', 'Sorry, we can not match your account.');
					redirect(base_url('login'));
					exit();
				}
			} catch (\Throwable $th) {
				//throw $th;
			}
    		
	    }
    
        
    }

	public function register()
	{
		$site_url = $_SERVER['HTTP_HOST'];
		$site_row = $this->SiteModel->get_row_from_url($site_url);

		$reg_btn = $this->input->post('reg_btn', TRUE);
		if($reg_btn == "ok"){
            $this->form_validation->set_rules('useremail', 'Email', 'trim|valid_email|is_unique[guest_tb.email]|required');
            $this->form_validation->set_rules('userpassword', 'Password', 'trim|required|min_length[8]');
            $this->form_validation->set_rules('usercpassword', 'Password Confirmation', 'trim|required|matches[userpassword]');

            if ($this->form_validation->run() == FALSE) {
                $data = array(
                    'errors' => validation_errors()
                );
                $this->session->set_flashdata('error', $data['errors']);
                redirect(base_url('register'),'refresh');
            }else{
				$useremail = $this->input->post('useremail', TRUE);
				$userpassword = $this->input->post('userpassword', TRUE);
				
				
				$insert_data = array(
					'email'             => $useremail,
					'password'          => md5($userpassword),
					'site_id' 			=> $site_row['id'],
					'is_active'         => 1,
					'created_at'        => date('Y-m-d H:i:s')
				);
				
				$this->AuthModel->insert_guest_row($insert_data);
	
				$result = $this->AuthModel->get_guest_row(" where email = '".$useremail."'");
				
				if($result){
					$gid = $result['id'];
					
					$config['cacheable']    = true; 
					$config['cachedir']     = './uploads/'; 
					$config['errorlog']     = './uploads/'; 
					$config['imagedir']     = './uploads/qrcode/'; 
					$config['quality']      = true; 
					$config['size']         = '1024'; 
					$config['black']        = array(224,255,255); 
					$config['white']        = array(70,130,180);
					$this->ciqrcode->initialize($config);
				
					$image_name = $gid.'_'.date('YmdHis').'.png';
				
					$params['data'] = $gid;
					$params['level'] = 'H';
					$params['size'] = 10;
					$params['savename'] = FCPATH.$config['imagedir'].$image_name;
					$this->ciqrcode->generate($params);
					
					$update_data = array(
						'qr_url' => base_url().'uploads/qrcode/'.$image_name
					);
					
					$this->AuthModel->update_guest_row($update_data, array('id' => $gid));
					
					if($site_row['isFace'] == 1){
					    $this->session->set_userdata('makeabl2020', $result);
    					if($site_row['is_single_gallery'] == 1)
            	        	redirect('sgallery', 'refresh');
            			else
            				redirect('mgallery', 'refresh');
					}else{
					    redirect('face-recognition/'.$result['id'], 'refresh');
					}
				}
			}
		}

		$data['title'] = 'Register | MAKEABL';
		$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];

		$this->load->view('auth/header', $data);	
		$this->load->view('auth/register', $data);
		$this->load->view('auth/footer', $data);
	}

	public function face_recognition()
	{
		$id = $this->uri->segment(2);
		if($id == "")
			redirect('login', 'refresh');

		$site_url = $_SERVER['HTTP_HOST'];
		$site_row = $this->SiteModel->get_row_from_url($site_url);

		$data['title'] = 'Face Recognition | MAKEABL';
		$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
		$data['id'] = $id;

		$this->load->view('auth/header', $data);	
		$this->load->view('auth/face-recognition', $data);
		$this->load->view('auth/footer', $data);
	}

	public function register_image()
	{
		$id = $this->uri->segment(2);
		if($id == "")
			redirect('login', 'refresh');

		$site_url = $_SERVER['HTTP_HOST'];
		$site_row = $this->SiteModel->get_row_from_url($site_url);

		$data['title'] = 'Register Image | MAKEABL';
		$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
		$data['id'] = $id;

		$this->load->view('auth/header', $data);
		$this->load->view('auth/register-image', $data);
		$this->load->view('auth/footer', $data);
	}
	
	public function reglogin(){
        $guest_id = $this->input->post('guest_id', TRUE);
        $face_url = $this->input->post('face_url', TRUE);
        $result = $this->AuthModel->get_guest_row(" where id = '".$guest_id."' and photo_url = '".$face_url."'");
        $this->session->set_userdata('makeabl2020', $result);
        echo "success";
	}

	public function webcam()
	{
		$id = $this->uri->segment(2);
		if($id == "")
			redirect('login', 'refresh');
		
		$site_url = $_SERVER['HTTP_HOST'];
		$site_row = $this->SiteModel->get_row_from_url($site_url);

		$data['title'] = 'Register Image | MAKEABL';
		$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
		$data['id'] = $id;

		$this->load->view('auth/header', $data);	
		$this->load->view('auth/webcam', $data);
		$this->load->view('auth/footer', $data);
	}

	public function recoverpw()
	{
		$site_url = $_SERVER['HTTP_HOST'];
		$site_row = $this->SiteModel->get_row_from_url($site_url);

		$reset_btn = $this->input->post('reset_btn', TRUE);
		if($reset_btn == "ok"){
			$useremail = $this->input->post('useremail', TRUE);
			$result = $this->AuthModel->get_guest_row(" where email = '".$useremail."'");
			if(count($result) > 0){
				try {
					$this->load->library('email');
						
					$config['protocol']     = 'smtp';
					$config['smtp_host']    = 'makeablmoments.com';
					$config['smtp_port']    = '587';
					$config['smtp_timeout'] = '60';
					$config['smtp_user']    = 'service@makeablmoments.com';
					$config['smtp_pass']    = 'makeabl2020!';
					$config['mailtype']     = 'html';
					$config['charset']      = 'utf-8';
					$config['newline']      = '\r\n';

					$this->email->initialize($config);

					$this->email->from('service@makeablmoments.com', 'Makeabl Team');
					$this->email->to($useremail);

					$this->email->subject('Reset Password');

					$message = 'Hi, Sir<br><br>';
					$message .= 'We have received a request to reset the password for your account. If you did not request to reset your password, please ignore this email.<a href="'.base_url('reset/'.$result["id"].'').'">Reset password now</a>.';
					$message .= "<br><br>Makeabl Team<br/><br/>";

					$this->email->message($message);

					$this->email->send();

					$this->session->set_flashdata('success', 'We accepted your request successfully! Please check your email.');
					redirect(base_url('recoverpw'));
					exit();
				}
				catch(Exception $e) {
					$this->session->set_flashdata('error', $e->getMessage());
					redirect(base_url('recoverpw'));
					exit();
				}
			}else{
				$this->session->set_flashdata('error', 'Sorry, we can not match your email.');
				redirect(base_url('recoverpw'));
				exit();
			}
		}

		$data['title'] = 'Forgot Password | MAKEABL';
		$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];

		$this->load->view('auth/header', $data);
		$this->load->view('auth/recoverpw', $data);
		$this->load->view('auth/footer', $data);
	}

	public function reset()
	{
		$id = $this->uri->segment(2);
		if($id == "")
			redirect('recoverpw', 'refresh');

		$site_url = $_SERVER['HTTP_HOST'];
		$site_row = $this->SiteModel->get_row_from_url($site_url);

		$reset_btn = $this->input->post('reset_btn', TRUE);
		if($reset_btn == "ok"){
            $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]');
            $this->form_validation->set_rules('cpassword', 'Password Confirmation', 'trim|required|matches[password]');

            if ($this->form_validation->run() == FALSE) {
                $data = array(
                    'errors' => validation_errors()
                );
                $this->session->set_flashdata('error', $data['errors']);
                redirect(base_url('register'),'refresh');
            }else{
				try {
					$password = $this->input->post('password', TRUE);
					$data_id = $this->input->post('data_id', TRUE);	
					
					$update_data = array(
						'password' => md5($password)
					);

					$this->AuthModel->update_guest_row($update_data, array('id'=>$data_id));

					$this->session->set_flashdata('success', 'Your password has been updated successfully.');
					redirect(base_url('reset/'.$id));
					exit();
				}catch(Exception $e) {
					$this->session->set_flashdata('error', $e->getMessage());
					redirect(base_url('reset/'.$id));
					exit();
				}
			}
		}
		
		$data['title'] = 'Reset Password | MAKEABL';
		$data['site_logo'] = 'http://d1z6a3vjnfowyr.cloudfront.net/'.$site_row['logo'];
		$data['id'] = $id;

		$this->load->view('auth/header', $data);
		$this->load->view('auth/reset', $data);
		$this->load->view('auth/footer', $data);
	}

	public function logout()
	{
		$this->session->unset_userdata('makeabl2020');
		redirect('login', 'refresh');
	}
}