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

class Admin_password extends CI_Controller
{

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

    }

    public function index()
    {

        if (!$this->input->get('token')) {
            echo "Lien incorrect";
        }
        else {

            $db_token = $this->user_model->getToken($this->input->get('token'));
            if($db_token==true){
                $this->session->set_userdata('token', $this->input->get('token'));
                $this->load->view('admin_update_password');
            }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 = $this->hashSSHA($password);
                $encrypted_password = $hash["encrypted"]; // encrypted password
                $salt = $hash["salt"]; // salt

                $res = $this->user_model->createPasswordAdmin($encrypted_password,$salt,$this->session->userdata('token'));

                if($res==true){
                    $new_token = null;
                    do {
                        $new_token = bin2hex(openssl_random_pseudo_bytes(16));
                        $tokenExist = $this->user_model->getToken($new_token);
                    } while ($tokenExist==true);


                    $res_token = $this->user_model->updateToken($new_token,$this->session->userdata('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";
                }
            }
        }
    }

    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

}
