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

class User extends CI_Controller {

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

    public function create(){
        $this->load->library('form_validation');

		$this->form_validation->set_rules('nom', 'Nom', 'required');
		$this->form_validation->set_rules('prenom', 'Prénom', 'required');
		$this->form_validation->set_rules('email', 'Adresse mail', 'valid_email');
		$this->form_validation->set_rules('password', 'current password', 'min_length[5]|required');
		$this->form_validation->set_rules('cpassword', 'confirm password', 'required|matches[password]');
		
        if ($this->form_validation->run() == FALSE){
			$this->load->view('layout/header');
		    $this->load->view('create_user');
		    $this->load->view('layout/footer');
		}else{
			
            $user=array(
                "usernom" => $this->input->post("nom"),
                "userprenom" => $this->input->post("prenom"),
                "usermail" => $this->input->post("email"),
                "userpassword" => password_hash(($this->input->post("password")), PASSWORD_DEFAULT),
            );

            $this->model_music->create_user($user);
            redirect("user/auth");
            }
	}

    public function auth()
	{
		$this->load->library('form_validation');

		$this->form_validation->set_rules('email', 'Adresse mail', 'valid_email');
		$this->form_validation->set_rules('password', 'current password', 'min_length[5]|required');
				
        if ($this->form_validation->run() == FALSE){
			$this->load->view('layout/header');
		    $this->load->view('connexion_user');
		    $this->load->view('layout/footer');
		}else{
            $email = $this->input->post('email');
            $MDP = $this->input->post('password');

            $dataUtilisateur = $this->model_music->get_user_by_email($email);

            if(password_verify($MDP, $dataUtilisateur->userpassword)){
                $dataUser = array(
                    "userId" => $dataUtilisateur->userId,
                    "userprenom" => $dataUtilisateur->userprenom,
                    "usermail" => $dataUtilisateur->usermail,
                    "userpassword" => $dataUtilisateur->userpassword,
                    "logged_in" => TRUE
                );
                $this->session->set_userdata($dataUser);
                redirect("albums");
            }else{
                redirect("user/create");
            }

        }
	}

    public function logout(){
        $this->session->sess_destroy();
    redirect("albums");
    }
}