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

class Agent_password extends CI_Controller
{

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

    public function index()
    {
        if (!$this->input->get('token')) {
            echo "Lien incorrect";
        }
        else {
            $db_token = $this->db->get_where('nh_validating_agents',['token' => $this->input->get('token')]);
            if($db_token->num_rows() > 0 ){
                $this->session->set_userdata('token', $this->input->get('token'));
                $this->load->view('admin_update_password',['isValidatingAgent' => true]);
            }else{
                echo "Ce lien a déjà expiré";
            }
        }

    }

    public function create_password()
    {
        if (!$this->session->userdata('token')) {
            echo "Ce lien a déjà expiré";
        } else {
            if(isset($_POST))
            {
                $password = $this->input->post('password');
                $hash = hashSSHA($password);
                $encrypted_password = $hash["encrypted"]; // encrypted password
                $salt = $hash["salt"]; // salt

				$this->db->where('token' , $this->session->userdata('token'));
                $res = $this->db->update('nh_validating_agents',['password' => $encrypted_password, 'salt' => $salt]);

                if($res==true){
                    $new_token = null;
                    do {
                        $new_token = bin2hex(openssl_random_pseudo_bytes(16));
						$tokenExist = $this->db->get_where('nh_validating_agents',['token' => $new_token]);
					} while ($tokenExist->num_rows() > 0);


					$this->db->where('token' , $this->session->userdata('token'));
                    $res_token = $this->db->update('nh_validating_agents',['token'=>$new_token]);

                    if($res_token==true){
                        $data['alert'] = 'password';
                        $data['message'] = 'Votre mot de passe a été configuré avec succès';
                        $this->load->view('login', $data);
                    }else{
                        echo "Une erreur s'est produite";
                    }
                }else{
                    echo "Une erreur s'est produite";
                }
            }
        }
    }
}
