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

class AuthController extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('GuestModel');
		$this->load->model('AuthModel');
		$this->load->model('CountryModel');
		$this->load->model('PackageModel');
		$this->load->model('PrepackageModel');
		$this->load->model('SiteModel');
		$this->load->library('ciqrcode');
		$this->load->library('aws3');

		$this->load->model('SiteDataModel');

	}




	public function SaveImageCompress()
	{
		$data = $_POST['photo'];
		
		list($type, $data) = explode(';', $data);
		list(, $data)      = explode(',', $data);
		$data = base64_decode($data);


		$filename = time().'_'.random_int(100000, 999999).'_'.date('Y-m-d').'.jpg';

		file_put_contents('uploads/profile/'.$filename.'', $data);
		

		
	      	$source_path ='uploads/profile/' . $filename;

	      	$target_path = 'uploads/profile/';

	      	$config_manip = array(
		     'image_library' => 'gd2',
		     'source_image' => $source_path,
		     'new_image' => $target_path,
		     'maintain_ratio' => TRUE,
	             'width' => 400,
	      	);

	        $this->load->library('image_lib', $config_manip);
	      	if (!$this->image_lib->resize()) {
        		
	      	}

      		$this->image_lib->clear();

      		$path = $source_path;
		$typeEx = pathinfo($path, PATHINFO_EXTENSION);
		$getData = file_get_contents($path);
		$base64 = 'data:image/' . $typeEx . ';base64,' . base64_encode($getData);

		$key = basename($path);

		$this->aws3->sendFileLink('makeabl-hub/compfaces', $key, $path);
		
		unlink($path);

		$json['success'] = $base64;
		echo json_encode($json);
	}


	

	public function index()
	{
		

// 		$site_url = $_SERVER['HTTP_HOST'];
		$site_url = 'glclix.co';
		
		$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('sgallery', '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->SiteDataModel->insert_row($result['id'], 'Login', 'Login');


											$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('sgallery', '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', 'Oops, there was an error fetching your account details.');
							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://d38x82mkkml5o1.cloudfront.net/' . $site_row['logo'];

			
			// $this->SiteDataModel->insert_row();

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

	public function register($para1 = null, $para2 = null)
	{
		date_default_timezone_set('UTC'); 

// 		$site_url = $_SERVER['HTTP_HOST'];
        $site_url = 'glclix.co';
		
        // for temp solution 
		$site_row = $this->SiteModel->get_row_from_url($site_url);
		
        // $site_row = $this->SiteModel->get_row_from_url("glclix.co");

		$token = 'https://' . $site_url . '/' . $this->uri->uri_string;

		$actualtoken = $this->uri->segment(2);

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


		if ($reg_btn == "ok") {

			
			

			$this->form_validation->set_rules('useremail', 'Email', 'trim|valid_email|required|is_unique[guest_tb.email]');
			$this->form_validation->set_rules('userpassword', 'Password', 'trim|required|min_length[3]');
			$this->form_validation->set_rules('usercpassword', 'Password Confirmation', 'trim|required|matches[userpassword]');
			$this->form_validation->set_rules('accept', 'Terms and Condition & Privacy Policy', 'trim|required');

			$CheckEmail = $this->db->where('email', $_POST['useremail']);
			$CheckEmail = $this->db->get('guest_tb')->num_rows();
			
			if(!empty($CheckEmail))
			{
				$this->session->set_flashdata('error', "Email account has been registered. Please try another email.");
				redirect(base_url(''));
			}


			if ($this->form_validation->run() == FALSE) {
				$data = array(
					'errors' => validation_errors()
				);
				// $this->session->set_flashdata('error', $data['errors']);
				$this->session->set_flashdata('error', "Email account has been registered. Please try another email.");
				redirect(base_url('register/' . $actualtoken), 'refresh');
			} else {

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

				if (empty($actualtoken)) {
	               // printf($actualtoken);
					$token1 = md5(strtotime(date("Y-m-d H:i:s")) * 1000 + 1 + 1);

					// $config['cacheable']    = true; 
					// $config['cachedir']     = './uploads/';
					// $config['errorlog']     = './uploads/';
					// $config['imagedir']     = './uploads/prepaidQR/';
					// $config['quality']      = true;
					// $config['size']         = '1024';
					// $config['black']        = array(224,255,255);
					// $config['white']        = array(70,130,180);
					// $this->ciqrcode->initialize($config);
					
				// 	for temporary solution 
				// 	$site_url = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $site_url;
					$site_url = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . "glclix.co";

				// 	$QRTokenURL = '"' . $site_url . '/register/' . $token1 . '"';
					
					$QRTokenURL = $site_url . '/register/' . $token1;

					$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'),
						'created_date'        => time(),
						'qr_token'          => $QRTokenURL,
					);

					$guest_id =  $this->AuthModel->insert_guest_row($insert_data);
					
					$this->SiteDataModel->insert_row($guest_id, 'Register', 'Register');
					
					
					if ($site_row['default_package_id'] > 0) {

						$package_data = $this->PackageModel->get_row($site_row['default_package_id']);
						date_default_timezone_set('UTC');
						$today = date('Y-m-d H:i:s', time());
						$from_date_int = strtotime($today);
						$to_date_string = date("Y-m-d H:i:s", strtotime("" . $package_data['validity'] . " hours", $from_date_int));
						$to_date_int = strtotime($to_date_string);

						$timezone = $this->PackageModel->get_timezone($site_row['default_package_id']);
						$temp_to_date = strtotime($from_date_int) * 1000 + $package_data['validity'] * 3600 * 1000;
						$to_date = date("Y-m-d", ($temp_to_date / 1000));

						$s_from_timestamp = strtotime($from_date_int . " 07:00") - $timezone * 3600;

						$s_from_date = date('Y-m-d H:i:s', $s_from_timestamp);
						$s_timestamp = strtotime($s_from_date) + $package_data['validity'] * 3600;
						$s_to_date   = date('Y-m-d H:i:s', $s_timestamp);

						$insert_data = array(
							'package_id' => $site_row['default_package_id'],
							'from_date'  => $today . " 07:00",
							'to_date' 	 => $to_date . " 06:59",
							'from_date_int'  => $from_date_int,
							'to_date_int'  => $to_date_int,
							's_from_date' => $s_from_date,
							's_to_date'  => $s_to_date,
							'created_at' => date('Y-m-d H:i:s')
						);


						$res = $this->PrepackageModel->insert_row($insert_data);

						// config
						$config['cacheable']    = true;
						$config['cachedir']     = '../uploads/';
						$config['errorlog']     = '../uploads/';
						$config['imagedir']     = '../uploads/prepaidQR/';
						$config['quality']      = true;
						$config['size']         = '1024';
						$config['black']        = array(224, 255, 255);
						$config['white']        = array(70, 130, 180);
						$this->ciqrcode->initialize($config);

						$image_name = $token1 . '.png';
						$params['data'] = $QRTokenURL;
						$params['level'] = 'H';
						$params['size'] = 10;
						$params['savename'] = FCPATH . $config['imagedir'] . $image_name;
						$this->ciqrcode->generate($params);

						$insert_qr_data = array(
							'prepackage_id' => $res["prepackage_id"],
							'filePath' => $image_name,
							'token' => $token1,
							'created_at' => date('Y-m-d H:i:s')
						);

						$this->PrepackageModel->insert_qr_row($insert_qr_data);
					}
				} else {
				    // printf("without token");
					$update_data = array(
						'email'             => $useremail,
						'password'          => md5($userpassword),
						'site_id' 			=> $site_row['id'],
						'is_active'         => 1,
						'created_date'        => time(),
						'created_at'        => date('Y-m-d H:i:s')
					);

					$this->AuthModel->update_guest_row($update_data, array('qr_token' => $token));
				}


				$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('sgallery', 'refresh');
					} else {
						redirect('face-recognition/' . $result['id'], 'refresh');
					}
				}
			}
		}


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


	
		// $this->SiteDataModel->insert_row();
		$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_url = 'glclix.co';
		$site_row = $this->SiteModel->get_row_from_url($site_url);

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

		// $this->SiteDataModel->insert_row();

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


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

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

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

		$data['loginFace'] = 1;


		$this->SiteDataModel->insert_row($id, 'Add Face', 'Add Face');

		$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_url = 'glclix.co';
        
		$site_row = $this->SiteModel->get_row_from_url($site_url);

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


		$this->SiteDataModel->insert_row($id, 'Import Device', 'Import Device');

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


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

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

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

		$data['getGuest'] = $this->db->where('id', $id)->get('guest_tb')->row();

		$data['getExtraFace'] = $this->db->where('guest_id', $id)->get('extra_faces_tb')->result();

		$data['TotalImageUpload'] = $site_row['max_number_of_faces'];

		// $this->SiteDataModel->insert_row();

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

	public function delete_addface_register_image($id, $quest_id)
	{
		if(!empty($_GET['guest']))
		{
			$this->db->where('id', $id);
			$this->db->set('photo_url', '');
			$this->db->update('guest_tb');
		}
		else
		{
			$this->db->where('id', $id);
			$this->db->delete('extra_faces_tb');
		}

		$this->session->set_flashdata('success', 'Record successfully deleted');
		redirect(base_url('addface-image/'.$quest_id));
	}


	public function reglogin()
	{
		$guest_id = $this->input->post('guest_id', TRUE);
		$face_url = $this->input->post('face_url', TRUE);
		if(!empty($face_url))
		{
			$result = $this->AuthModel->get_guest_row(" where id = '" . $guest_id . "' and photo_url = '" . $face_url . "'");
		}
		else
		{
			$result = $this->AuthModel->get_guest_row(" where id = '" . $guest_id . "' ");	
		}
		
		$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_url = 'glclix.co';
		
		$site_row = $this->SiteModel->get_row_from_url($site_url);

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

		$this->SiteDataModel->insert_row($id, 'Capture', 'Capture');

		$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_url = 'glclix.co';
		$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']    = 'makeabl.io';
				// 	$config['smtp_port']    = '587';
				// 	$config['smtp_timeout'] = '60';
				// 	$config['smtp_user']    = 'service@makeabl.io';
				// 	$config['smtp_pass']    = 'makeabl2020!';
				// 	$config['mailtype']     = 'html';
				// 	$config['charset']      = 'utf-8';
				// 	$config['newline']      = '\r\n';
					
					
				    // $config['protocol']     = 'smtp';
        //     		$config['smtp_host']    = 'makeablmoments.com';
        //     		$config['smtp_port']    = '587';
        //     		$config['smtp_user']    = 'service@makeablmoments.com';
        //     		$config['smtp_pass']    = 'makeabl2020!';
        //     		$config['smtp_crypto']  = 'tls';
        //     		$config['mailtype']     = 'html';
        //     		$config['charset']      = 'utf-8';
        //     		$config['newline']      = '\r\n';
            		
            		
            		
        			$config['protocol']     = 'smtp';
            		$config['smtp_host']    = 'makeabl.io';
            		$config['smtp_port']    = '587';
            		$config['smtp_user']    = 'support@makeabl.io';
            		$config['smtp_pass']    = 'Teamindia11!';
            		$config['smtp_crypto']    = 'tls';
            		$config['mailtype']     = 'html';
            		$config['charset']      = 'utf-8';
            		$config['newline']      = '\r\n';
		

    
                        							
            // 		$config['protocol']     = 'smtp';
            // 		$config['smtp_host']    = 'makeabl.io';
            // 		$config['smtp_port']    = '587';
            // 		$config['smtp_user']    = 'support@makeabl.io';
            // 		$config['smtp_pass']    = 'Teamindia11!';
            // 		$config['smtp_crypto']    = 'tls';
            // 		$config['mailtype']     = 'html';
            // 		$config['charset']      = 'utf-8';
            // 		$config['newline']      = '\r\n';

					$this->email->initialize($config);
                    
                    
					$this->email->from('support@makeabl.io', 'GL Clix');
					$this->email->to($useremail);

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

					$message = 'Hello,<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>GL Clix<br/><br/>";

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

					$this->email->send();

					$this->SiteDataModel->insert_row($result["id"], 'Reset Password', 'Reset Password');

					$this->session->set_flashdata('success', 'We have accepted your request. Please check your mail.');
					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://d38x82mkkml5o1.cloudfront.net/' . $site_row['logo'];

		// $this->SiteDataModel->insert_row();

		$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_url = 'glclix.co';
		$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[4]');
			$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://d38x82mkkml5o1.cloudfront.net/' . $site_row['logo'];
		$data['id'] = $id;

		// $this->SiteDataModel->insert_row();

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

	public function logout()
	{

		$this->SiteDataModel->insert_row('', 'Logout', 'logout');

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