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

/**
 * Class Timekeeper controlador de un cronometrador
 */
class Timekeeper extends CI_Controller {
    private $language;

    /**
     * Timekeeper constructor.
     * Comprueba se ha iniciado session como rol de delegado o cronometrador
     */
    function __construct()
    {
        parent::__construct();

        if (!$this->session->has_userdata('user') &&!$this->session->has_userdata('timekeeper')  )
            redirect(base_url() . '?msg=' . SESSION_EXPIRED, 'refresh');
        $this -> load -> model ('timekeeperModel');
        $this -> load -> model ('combatModel');
        $this -> language = $this -> session -> userdata('language');
        include "application/src/Pagination.php";

    }

    /**
     * Funcion controladora que muestra los cronometradores que hay registrados en la aplicación
     */
    public function index() {
        $data['timekeeper'] = $this->timekeeperModel-> getTimekeepers();
        $data['timekeeper_text'] = $this -> get_text_view_timekeeper($this -> language);
        $this -> load -> view ('Estructura/header_principal');
        $this -> load -> view ('Timekeepers/timekeepers',$data);
        $this -> load -> view ('Estructura/footer');

    }

    /**
     * Funcion controladora de la creacion de cronometradores
     * Parametros pasados por medio de POST
     */
    public function create() {

        $email= $this -> input -> post('email');
        $dni = $this -> input -> post('dni');
        if(!$this ->validateDNI($dni))redirect(base_url() . 'timekeeper?msg=' . SIZE_OF_DNI, 'refresh');

        $name = $this -> input -> post('name');
        $surname = $this -> input -> post('surname');
        $surname2 = $this -> input -> post('surname2');

        $password = password_hash($this -> input -> post('password'),PASSWORD_BCRYPT); // Encryptamos la contraseña en el lado del servidor


        $this -> timekeeperModel -> existsTimekeeper($dni,$email) ?
            redirect(base_url() . 'timekeeper?msg=' . ERROR_CREATE_TIMEKEEPER, 'refresh') :
            $this -> createTimekeeper($email,
                $dni,
                $name,
                $surname,
                $surname2,
                $password);



    }

    /**
     * @param $email Servira de username para acceder como cronometrador en la aplicacion
     * @param $dni dni del cronometrados
     * @param $name Nombre
     * @param $surname Primer apellido
     * @param $surname2 Segundo apellido
     * @param $password Contraseña con la que podrá acceder el cronometrador a la aplicacion ( hasheada)
     */
    public function createTimekeeper($email,$dni,$name,$surname, $surname2,$password) {
        $this -> timekeeperModel -> createTimekeeper($email, $dni, $name, $surname, $surname2, $password);
        redirect(base_url() . 'timekeeper?msg=' . SUCCESS_CREATE_TIMEKEEPER, 'refresh');
    }
    public function changePassword() {
       $email =  $this -> input -> post('email');
       $password = password_hash($this -> input -> post('password'),PASSWORD_BCRYPT);

           $this -> timekeeperModel -> changePassword($email,$password) ? redirect(base_url().'timekeeper?msg='.SUCCESFULL_CHANGE_PASSWORD) : redirect(base_url().'timekeeper?msg='.ERROR_OLD_PASSWORD);


    }public function init() {
    $email = $this -> session -> userdata('timekeeper');
    $mats = $this ->timekeeperModel -> getMats($email);
    $data['mats']= $mats;
    $data['timekeeper_text'] = $this -> get_text_timekeeper_combat($this -> session -> userdata('language'));
    $this -> load -> view ('Estructura/header_timekeeper');
    $this -> load -> view ('Timekeepers/timekeeper_mats',$data);
    $this -> load -> view ('Estructura/footer');
}
    /**
     * Funcion controladora de mostrar los combates que tiene asignado un determinado cronometrador
     * @param $idMat tatami del cronometrador asignado
     */
    public function mat($idMat) {

        $data['timekeeper_text'] = $this -> get_text_timekeeper_combat($this ->language);
        $data['combats'] = $this -> combatModel -> getCombatsByIDMat($idMat);
        $this -> load -> view ('Estructura/header_timekeeper');
        $this -> load -> view ('Timekeepers/combats',$data);
        $this -> load -> view ('Estructura/footer');
    }

    private function get_text_timekeeper_combat($language) {
        $this->lang->load('timekeeper_lang', $language);
        $data['timekeeper_init_competition_date'] = $this->lang->line('timekeeper_init_competition_date');
        $data['timekeeper_init_competition_show'] = $this->lang->line('timekeeper_init_competition_show');
        $data['timekeeper_init_competition_mat'] = $this->lang->line('timekeeper_init_competition_mat');
        $data['timekeeper_init_competition_name'] = $this->lang->line('timekeeper_init_competition_name');
        $data['timekeeper_init_competition_btn'] = $this->lang->line('timekeeper_init_competition_btn');
        $data['timekeeper_list_combats_without_score'] = $this->lang->line('timekeeper_list_combats_without_score');
        $data['timekeeper_list_with_score'] = $this->lang->line('timekeeper_list_with_score');
        $data['timekeeper_phase'] = $this->lang->line('timekeeper_phase');
        $data['timekeeper_btn_score'] = $this->lang->line('timekeeper_btn_score');


        return $data;


    }

    private function get_text_view_timekeeper($idiom)
    {
        $this->lang->load('timekeeper_lang', $idiom);
        $data['timekeeper_create'] = $this->lang->line('timekeeper_create');
        $data['timekeeper_text'] = $this->lang->line('timekeeper_text');
         $data['timekeeper_name'] = $this->lang->line('timekeeper_name');
        $data['timekeeper_surname'] = $this->lang->line('timekeeper_surname');
        $data['timekeeper_surname2'] = $this->lang->line('timekeeper_surname2');
        $data['timekeeper_dni'] = $this->lang->line('timekeeper_dni');
        $data['timekeeper_email'] = $this->lang->line('timekeeper_email');

        $data['timekeeper_change_password'] = $this->lang->line('timekeeper_change_password');



        $data['timekeeper_form_text'] = $this->lang->line('timekeeper_form_text');
        $data['timekeeper_form_create_password'] = $this->lang->line('timekeeper_form_create_password');
        $data['timekeeper_form_create_timekeeper'] = $this->lang->line('timekeeper_form_create_timekeeper');
        $data['timekeeper_form_password'] = $this->lang->line('timekeeper_form_password');

        $data['timekeeper_change_password_text'] = $this->lang->line('timekeeper_change_password_text');
        $data['timekeeper_change_password_new'] = $this->lang->line('timekeeper_change_password_new');
        $data['timekeeper_change_password_btn'] = $this->lang->line('timekeeper_change_password_btn');


        return $data;
    }

    private function validateDNI($dni) {
        $letter = substr($dni, -1);
        $numbers = substr($dni,0,-1);


        return substr(("TRWAGMYFPDXBNJZSQVHLCKE"),$numbers % 23,1) == $letter ||substr(("trwagmyfpdxbnjzsqvhlcke"),$numbers % 23,1) == $letter;
    }
}

?>