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

class Security extends CI_Controller {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();
        force_ssl();
    }

  

    /**
     * Login page.
     *
     */
    public function login() {
        if ($this->session->userdata('logged_in')) {
            redirect(base_url(), 'refresh');
        }
        $this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email', 'trim|required');
        $this->form_validation->set_rules('password', 'Mot de passe', 'trim|required|callback_database_check');
        if ($this->form_validation->run() == false) {
            $this->load->view('security/login');
        }else{
            redirect(base_url(), 'refresh');
        }
    }

    /**
     * CallBack database chack Function
     * 
     */
    public function database_check($password) {
        $email = $this->input->post('email');
        $em = $this->doctrine->em;
        if ($user = $em->getRepository('Entities\User')->login($email, $password)) {
            $sess_array = [
                'id' => $user->getId(),
                'email' => $user->getEmail(),
                'admin' => $user->getAdmin(),
                'last_login' => date('Y-m-d H:i:s'),
            ];
            $this->session->set_userdata('logged_in', $sess_array);
            return true;
        } else {
            $this->form_validation->set_message('database_check', 'Email et/ou mot de passe incorrect.');
            return false;
        }
    }
    
    /**
     * Logout Function
     * 
     */
    public function logout() {
        if ($this->session->userdata('logged_in')) {
            $em = $this->doctrine->em;
            $session_user = $this->session->userdata('logged_in');
            $date = new DateTime();
            $date->setTimestamp(strtotime($session_user['last_login']));
            if($em->getRepository('Entities\User')->logout($session_user['id'], $date)) {
                $this->session->unset_userdata('logged_in');
                $this->session->sess_destroy();
            }
        }
        redirect(site_url('login'), 'refresh');
    }

}

/* End of file main.php */