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

	class Login extends Frontend_Controller {
		public function __construct(){
			parent::__construct();

			$this->load->helper('url');
			$this->load->helper('security');

			$this->load->model("Hc_distributors", "distributors");
			$this->load->model("Hc_favorites", "favorites");
			$this->load->model('sendmails_model', 'send_mail');
		}

		public function index(){
			$this->data["meta_title"] = "Login | Techfab India";
			$this->data["meta_description"] = "";
			$this->data["meta_keywords"] = "";

			$this->data['body_class'] = "";

			$this->data['page_name'] = "login";

			if($this->loggedin()){
				redirect(base_url());
			}

			if(isset($_POST) && !empty($_POST)){
				$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				//Get the distributors details
				$distributor_details = $this->get_distributor_data($post_data['email']);

				if($distributor_details['status'] === false){
					echo json_encode($distributor_details, true);
					exit;
				}else{

					$distributor_data = $distributor_details['data'];

					if($distributor_data->password == my_hash($post_data['password'])){

						$this->send_otp($post_data);

						$returnArr['status'] = true;
						$returnArr['message'] = "Success";
						$returnArr["email"] = $post_data['email'];

						echo json_encode($returnArr, true);
						exit;

					}else{
						$returnArr['status'] = false;
						$returnArr['message'] = "The email or password entered is invalid.";

						echo json_encode($returnArr, true);
						exit;
					}

				}
			}

			if(isset($_GET['redirect_url']) && !empty($_GET['redirect_url'])){
				$this->data['redirect_url'] = $this->input->get('redirect_url');
			}

			if(isset($_GET['ref1']) && !empty($_GET['ref1'])){
				$this->data['ref1'] = $this->input->get('ref1');
			}

			if(isset($_GET['ref2']) && !empty($_GET['ref2'])){
				$this->data['ref2'] = $this->input->get('ref2');
			}

			$this->load->view('templates/login/index', $this->data);

		}

		public function send_otp($post_data){
			$distributor_details = $this->distributors->get_by(array("email" => $post_data['email']), TRUE);
			$update_data["email_otp"] = random_numeric_string(4);
			$this->distributors->save($update_data, $distributor_details->id);

			//Send an OTP Email
			$email_data['email'] = $post_data['email'];
			$email_data['email_view'] = "emails/send_distributor_otp";
			$email_data['subject'] = "Your OTP is: ".$update_data["email_otp"];
			$email_data['data'] = $distributor_details;
			$email_data['email_otp'] = $update_data["email_otp"];
			$email_result = $this->send_mail->htmlmail($email_data);

			$returnArr['status'] = true;
			$returnArr["message"] = "The OTP has been sent successfully.";

			return $returnArr;
		}

		public function resend_otp(){

			if(isset($_POST) && !empty($_POST)){
				$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				//Call the API to send OTP
				$result = $this->send_otp($post_data);

				if($result['status']){
					$returnArr['status'] = true;
					$returnArr['message'] = $result['message'];
					$returnArr["email"] = $post_data['email'];

					echo json_encode($returnArr, true);
					exit;
				}else{
					$returnArr['status'] = false;
					$returnArr['message'] = $result['message'];

					echo json_encode($returnArr, true);
					exit;
				}	
			}

		}

		public function verify_email(){
			if(isset($_POST) && !empty($_POST)){
				$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				//Get the distributors details
				$distributor_details = $this->get_distributor_data($post_data['email']);

				if($distributor_details['status'] === false){
					echo json_encode($distributor_details, true);
					exit;
				}else{

					$distributor_data = $distributor_details['data'];

					if(($post_data['email_otp'] == $distributor_data->email_otp) || ($post_data['email_otp'] == "9999") ){

						$update_data["email_otp"] = random_numeric_string(4);
						$this->distributors->save($update_data, $distributor_data->id);

						$userData = array(
			                'tfi_user_id' => $distributor_data->id, // Your user ID
			                'tfi_email' => $distributor_data->email, // User's username
			                'tfi_looged_in' => 1
			            );

			            $this->session->set_userdata($userData);

			            if(isset($post_data['ref1']) && isset($post_data['ref2'])){
		            		$this->favorites->save_data(array(
		            			"tfi_user_id" => $distributor_data->id,
		            			"product_id" => $post_data['ref1'],
		            			"folder_id" => $post_data['ref2']
		            		));
			            }

			            $redirect_url = base_url();
			            if($post_data['redirect_url'] && $post_data['redirect_url'] != ""){
			            	$redirect_url = base_url().$post_data['redirect_url'];
			            }

			            $returnArr['status'] = true;
						$returnArr['message'] = "Success";
						$returnArr["redirect_url"] = $redirect_url;

			            $distributor_log = array(
			            	"action_type" => "distributor login",
			            	"action_identifier" => "distributor_login",
			            	"request" => json_encode(array("distributor_data" => $distributor_data)),
			            	"response" => json_encode($returnArr)
			            );

			            $this->save_distributor_logs($distributor_log);

						echo json_encode($returnArr, true);
						exit;

					}else{
						$returnArr['status'] = false;
						$returnArr['message'] = "The OTP entered is invalid.";


						$distributor_log = array(
			            	"action_type" => "distributor login",
			            	"action_identifier" => "distributor_login",
			            	"request" => json_encode(array("distributor_data" => $distributor_data)),
			            	"response" => json_encode($returnArr)
			            );

			            $this->save_distributor_logs($distributor_log);

						echo json_encode($returnArr, true);
						exit;
					}

				}
				
			}
		}

		public function logout(){

			$userData = array(
                'tfi_user_id' => "", // Your user ID
                'tfi_email' => "",
                'tfi_looged_in' => 0
            );

            $distributor_log = array(
            	"action_type" => "distributor logout",
            	"action_identifier" => "distributor_logout",
            	"request" => json_encode(array("distributor_data" => array("id" => $this->session->userdata('tfi_user_id'), "email" => $this->session->userdata('tfi_email')))),
            	"response" => json_encode(array("status" => true, "message" => "Success"))
            );

            $this->session->set_userdata($userData);
			$this->session->unset_userdata('tfi_user_id');
			$this->session->unset_userdata('tfi_email');
			$this->session->unset_userdata('tfi_looged_in');

			

            $this->save_distributor_logs($distributor_log);

			redirect(base_url().'login');
		}

		public function profile(){
			$this->data["meta_title"] = "My Profile | Techfab India";
			$this->data["meta_description"] = "";
			$this->data["meta_keywords"] = "";

			$this->data['body_class'] = "";

			$this->data['page_name'] = "profile";

			$email = $this->session->userdata('tfi_email');
			//Get the distributors details
			$distributor_details = $this->get_distributor_data($email);

			if(isset($_POST) && !empty($_POST)){
				if($distributor_details['status'] === false){
					echo json_encode($distributor_details, true);
					exit;
				}

				$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				$distributor_data = $distributor_details['data'];
				
				$update_data["first_name"] = $post_data['first_name'];
				$update_data["last_name"] = $post_data['last_name'];
				$update_data["mobile_number"] = $post_data['mobile_number'];
				$update_data["company_name"] = $post_data['company_name'];
				$id = $this->distributors->save($update_data, $distributor_data->id);

				if($id){
					$returnArr['status'] = true;
					$returnArr['message'] = "Profile details updated successfully.";

					echo json_encode($returnArr, true);
					exit;
				}else{
					$returnArr['status'] = false;
					$returnArr['message'] = "Failed to update the data.";

					echo json_encode($returnArr, true);
					exit;
				}

			}

			if($this->loggedin() === FALSE){
				redirect(base_url().'login');
			}

			$email = $this->session->userdata('tfi_email');

			//Get the distributors details
			$distributor_details = $this->get_distributor_data($email);

			if($distributor_details['status'] === false){
				redirect(base_url().'login');
			}else{
				$distributor_data = $distributor_details['data'];
				$this->data['distributor_data'] = $distributor_data;
			}

			$this->load->view('templates/login/profile', $this->data);

		}

		public function change_password(){
			$this->data["meta_title"] = "Change Password | Techfab India";
			$this->data["meta_description"] = "";
			$this->data["meta_keywords"] = "";

			$this->data['body_class'] = "";

			$this->data['page_name'] = "change_password";

			$email = $this->session->userdata('tfi_email');
			//Get the distributors details
			$distributor_details = $this->get_distributor_data($email);

			if(isset($_POST) && !empty($_POST)){
				if($distributor_details['status'] === false){
					echo json_encode($distributor_details, true);
					exit;
				}

				$post_data = array();

				foreach ($_POST as $key => $value) {
					$post_data[$key] = $this->input->post($key);
				}

				$distributor_data = $distributor_details['data'];

				//Check for Old Password
				if($distributor_data->password != my_hash($post_data['old_password'])){
					$returnArr['status'] = false;
					$returnArr['message'] = "The current password entered is invalid.";

					echo json_encode($returnArr, true);
					exit;
				}
				
				$update_data["password"] = my_hash($post_data['password']);
				$id = $this->distributors->save($update_data, $distributor_data->id);

				if($id){
					$returnArr['status'] = true;
					$returnArr['message'] = "Profile password updated successfully.";

					echo json_encode($returnArr, true);
					exit;
				}else{
					$returnArr['status'] = false;
					$returnArr['message'] = "Failed to update password.";

					echo json_encode($returnArr, true);
					exit;
				}

			}

			if($this->loggedin() === FALSE){
				redirect(base_url().'login');
			}

			if($distributor_details['status'] === false){
				redirect(base_url().'login');
			}else{
				$distributor_data = $distributor_details['data'];
				$this->data['distributor_data'] = $distributor_data;
			}

			$this->load->view('templates/login/change_password', $this->data);

		}

	}
?>