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

    class Users extends CI_Controller {

        public function __construct(){
            parent::__construct();
            $this->load->model('nano_health_model');
        }

        public function index()
        {

            if (!$this->session->userdata('token')) {

                $this->session->set_flashdata('error', 'log in first');
                $data['alert'] = '';
                $this->load->view('login', $data);

            } else {

                $hyper = "hyper";
                $super = "super";
                $admin = "admin";

                if ($this->session->userdata('category') == 0 or $this->session->userdata('category') == 1) {

                    $data['active'] = "dash";
                    $data['firstname'] = $this->session->userdata('firstname');
                    $data['lastname'] = $this->session->userdata('lastname');
                    $data['email'] = $this->session->userdata('email');
                    $this->load->view('header', $data);
                    $this->load->view('admin_dash');
                    $this->load->view('footer');

                } else if ($this->session->userdata('category') == $hyper) {

                    $data['active'] = "dash";
                    $data['token'] = $this->session->userdata('token');
                    $data['email'] = $this->session->userdata('email');
                    $data['firstname'] = $this->session->userdata('firstname');
                    $data['lastname'] = $this->session->userdata('lastname');
                    $data['member_code'] = $this->session->userdata('member_code');
                    $data['phone'] = $this->session->userdata('phone');
                    $data['adresse'] = $this->session->userdata('adresse');
                    $data['category'] = $this->session->userdata('category');
                    $data['network'] = $this->session->userdata('network');
                    $data['network_id'] =
                    $data['villes'] = $this->user_model->getVilleByUserGeo($data['network']);
                    $data['count_geo'] = $this->user_model->countUser("geolocated",$this->session->userdata('network'));
                    $data['count_sup'] = $this->user_model->countUser("super",$this->session->userdata('network'));
                    $this->load->view('header_hyp', $data);
                    $this->load->view('hyperviseur_dash');
                    $this->load->view('footer');

                } else if ($this->session->userdata('category') == $super) {

                    $data['active'] = "dash";
                    $this->load->view('header_sup', $data);
                    $this->load->view('superviseur_dash');
                    $this->load->view('footer');
                }


            }

        }

		public function login()
		{
			$user_login = [
				'user_email'    => trim($this->input->post('user_mail')),
				'user_password' => $this->input->post('user_password'),
				'user_role'     => $this->input->post('user_role')
			];

			$email    = $user_login['user_email'];
			$password = $user_login['user_password'];
			$role     = $user_login['user_role'];
    

			// CAS 1 : Agents valideurs – iLink Santé / World (role = 2)
			if ($role == 2 && filter_var($email, FILTER_VALIDATE_EMAIL)) {

				$sql = "
					SELECT nhd.*, n.name AS network, n.id AS network_id,
						cc.name AS country, cc.currency_code
					FROM nh_validating_agents nhd
					INNER JOIN networks n ON n.id = nhd.network_id
					INNER JOIN countries_currencies cc ON cc.id = n.country_id
					WHERE nhd.email = ?
				";

				$agentQuery = $this->db->query($sql, [$email]);

				if ($agentQuery->num_rows() > 0) {

					$agent = $agentQuery->first_row();

					$encrypted_password = $agent->password;
					$hash = checkhashSSHA($agent->salt, $password);

					if ($encrypted_password === $hash) {
						$this->session->set_userdata([
							'agent_id'      => $agent->id,
							'email'         => $agent->email,
							'firstname'     => $agent->firstname,
							'lastname'      => $agent->lastname,
							'phone'         => $agent->email,
							'role'          => $agent->role,
							'currency_code' => $agent->currency_code,
							'network'       => $agent->network,
							'network_id'    => $agent->network_id,
							'current_pays'  => $agent->country
						]);

						switch ($agent->role) {
							case 'DOCTOR':                 redirect('ValidatingDoctor'); break;
							case 'CONTROLLER':             redirect('ControllerDoctor'); break;
							case 'OPENING_ACCOUNT_AGENT':  redirect('OpeningAccountAgent'); break;
							default:                       redirect('ValidatingAgent');
						}
					}
				}
			}

			// CAS 2 : Login standard via user_model
			$data = $this->user_model->login_user($email, $password, $role);

			if ($data) {

				$hyper = 'hyper';
				$super = 'super';

				$this->session->set_userdata([
					'token'         => $data->token         ?? null,
					'email'         => $data->email         ?? null,
					'firstname'     => $data->firstname     ?? null,
					'lastname'      => $data->lastname      ?? null,
					'adresse'       => $data->adresse       ?? null,
					'agent_id'      => $data->agent_id      ?? null,
					'currency_code' => $data->currency_code ?? null
				]);

				// CAS ADMIN (role = 1)
				if ($role == 1) {

					$this->session->set_userdata('country', $data->country ?? null);

					// Pays
					$pays = $this->user_model->getAllCountries();
					if ($pays && $pays->first_row()) {
						$this->session->set_userdata('current_pays', $pays->first_row()->name);
					}

					// Hyperviseur
					$hyperRes = $this->user_model->getAllHyper($this->session->userdata('current_pays'));
					if ($hyperRes && $hyperRes->first_row()) {
						$this->session->set_userdata('current_hyper', $hyperRes->first_row()->code_membre);
					}

					// Ville
					$villeRes = $this->user_model->getVilleNetworkByHyper($this->session->userdata('current_hyper'));
					if ($villeRes && $villeRes->first_row()) {
						$this->session->set_userdata('current_ville', $villeRes->first_row()->ville);
					}

					$this->session->set_userdata('category', $data->category ?? null);

					redirect('Admin_dash/filter');
				}

				// CAS NON ADMIN (agents / hyper / super / geolocated)
				$this->session->set_userdata([
					'member_code'   => $data->code_membre         ?? null,
					'longitude'     => $data->longitude           ?? null,
					'latitude'      => $data->latitude            ?? null,
					'phone'         => $data->phone               ?? null,
					'category'      => $data->category            ?? null,
					'network'       => $data->network             ?? null,
					'network_id'    => $data->network_id          ?? null,
					'current_pays'  => $data->country             ?? null
				]);
				if ($data->category === $hyper) {
					redirect('Hyperviseur_dash');
				}

				if ($data->category === $super) {
					$this->session->set_userdata('code_parrain', $data->code_parrain ?? null);
					redirect('Superviseur_dash');
				}

				if ($data->category === 'geolocated') {
					$this->session->set_userdata('code_parrain', $data->code_parrain ?? null);
					$this->session->set_userdata('network_agent_id', $data->network_agent_id ?? null);
					redirect('Agent');
				}
			}
			
			$this->session->set_flashdata('error_msg', 'Error occured, try again.');

			$data['alert']   = "ok";
			$data['message'] = "L'identifiant $email ou le mot de passe sont incorrects ou vérifiez votre grade!";

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

        public function create_auth(){

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

            if($email!=null){

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

                if($this->User_model->email_check($this->input->post('user_email')))
                {
                    $id = $this->session->userdata('id');
                    $tktToken = $this->generateToken($id);
                    $current_date = date('Y-m-d H:i:s');
                    $expires = strtotime('+3 days', strtotime($current_date));
                    $end_date = date('Y-m-d H:i:s', $expires);
                    $code_sms = str_pad(mt_rand(1,999999),6,'0',STR_PAD_LEFT);

                    $auth = array(
                        'email' => $this->input->post('user_email'),
                        'contact' => $this->input->post('user_mobile'),
                        'token' => $tktToken,
                        'code_sms' => $code_sms,
                        'create_at' => $current_date,
                        'expire_at' => $end_date,
                        'id_creator' => $id
                    );

                    $userId = $this->Authentification_url_model->save_auth($auth);

                    $this->sendmail($userId,$this->input->post('email'),$this->input->post('name'),$tktToken,'register','Verify your email');
                    redirect('user/login_view', 'refresh');
                }
                else{
                    $this->session->set_flashdata('msg', 'This email is already used, please try again with different account ...');
                    redirect('users/register', 'refresh');
                }

            }
        }

        public function register(){

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

            $current_date = date('Y-m-d H:i:s');
            $token = null;
            $expiration_date = $this->Authentification_url_model->getExpireDate($token);

            if($expiration_date!=null){
                if($current_date < $expiration_date){
                    //registration logic
                }
                else{
                    $this->session->set_flashdata('error_msg', 'Error occured,Try again.');
                    //$this->load->view("login.php");
                    $data['alert'] = "ok";
                    $data['message'] = "Sorry your authentification'url has already expired";

                    //redirect('Login', $data);
                    $this->load->view('register', $data);
                }
            }
            else{
                $this->session->set_flashdata('error_msg', 'Error occured,Try again.');
                $data['alert'] = "ok";
                $data['message'] = "your authentification url is not recognized";
                $this->load->view('register', $data);
            }
        }

        public function generateToken($id){
            $static_str='IL';
            $currenttimeseconds = date("mdY_His");
            $token_id=$static_str.$id.$currenttimeseconds;

            return md5($token_id);
        }

        public function logout()
        {
            $this->session->sess_destroy();
            $data['alert'] = 'You have been disconnected';
			$this->session->set_flashdata('error','You have been disconnected' );
            redirect('Users', $data);
//            $this->load->view('login', $data);
        }

        public function forgot_password(){

            $data['message'] = 'Les instructions vous seront envoyées par email.';
            $this->load->view('admin_forgot_password',$data);
        }

        public function sendEmailInstructions(){

            if(isset($_POST))
            {
                $email = $this->input->post('email');
                $emailExist = $this->user_model->isEmailExist($email);
                if($emailExist==true){
                    $names = $this->db->query("SELECT firstname,lastname FROM admin WHERE email='".$email."'");
                    $firstname = $names->first_row()->firstname;
                    $lastname = $names->first_row()->lastname;
                    $token_query = $this->db->query("SELECT token FROM admin WHERE email='".$email."'");
                    $token = $token_query->first_row()->token;

                    $link = base_url("Admin_password/?token=".$token);
                    $this->load->library('email');

                    $this->email->from('noreply@ilink-app.com', 'iLink World');
                    $this->email->to($email);

                    $this->email->subject("Instruction pour modification de mot de passe");
                    $this->email->message($firstname.' '.$lastname.', veuillez suivre ce lien pour créer un nouveau mot de passe. '.$link);

                    $this->email->send();
                }else{
                    $data['message'] = 'Veuillez saisir votre email.';
                    $this->load->view('admin_forgot_password',$data);
                }
            }else{
                $data['message'] = 'Cet email ne correspond à aucun utilisateur.';
                $this->load->view('admin_forgot_password',$data);
            }
        }

        public function redirect_tutorial(){
            if(isset($_POST))
            {
                $profil = $this->input->post('profil');
                switch ($profil) {
                    case 1:
                        $data['profil'] = 1;
                        $this->load->view('flipbook',$data);
                        break;
                    case 2:
                        $data['profil'] = 2;
                        $this->load->view('select_tuto',$data);
                        break;
                    case 3:
                        $data['profil'] = 3;
                        $this->load->view('select_tuto',$data);
                        break;
                }
            }

        }
    }
?>
