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

/**
 * Clase controladora Referee encargada de la gestion de arbitros
 * Class Referee
 */
class Referee extends CI_Controller
{
    private $language;
    const PERPAGE = 10;
    const NUM_LINKS = 10;

    /**
     * Constructor de la clase controladora Referee. verifica que el usuario con rol de delegado ha iniciado session antes de
     * crear unaa instancia.
     * Referee constructor.
     */
    function __construct()
    {
        parent::__construct();
        if (!$this->session->has_userdata('user'))
            redirect(base_url() . '?msg=' . SESSION_EXPIRED, 'refresh');
        include 'application/src/Pagination.php';
        $this->language = $this->session->userdata('language');
        $this -> load -> library('pagination');
        $this->load->model('refereeModel');
        $this->load->model('categoriaArbitralModel');


    }

    /**
     * Funcion que muestra los arbitros registrados en la aplicación
     */
    public function index()
    {

        $referess = $this->refereeModel->getAllReferees();

        $pagination = new Pagination( base_url().'referee/index', sizeof($referess), self::PERPAGE, self::NUM_LINKS);
        $pagination->init_pagination();

        $referess_categories = $this->categoriaArbitralModel->getRefereeCategories();
        $text['referees'] = $this -> refereeModel -> getRefereesBy(self::PERPAGE,$this -> uri -> segment(3));
        $text['referees_categories'] = $referess_categories;
        $text['text_referee'] = $this->get_text_view_referee($this->language);
        $text['num_referees'] = sizeof($referess);
        $this->load->view('Estructura/header_principal');
        $this->load->view('Referees/referees', $text);
        $this->load->view('Estructura/footer');
    }

    /**
     * Funcion que sirve para buscar arbitros en funcion de una determinada categoria arbitral
     * Los parametros son pasados por medio de POST
     */
    public function search()
    {


        $referess_categories = $this->categoriaArbitralModel->getRefereeCategories();
        $categorie = $this->input->get('selectRefereeCategory');
        $text['referees'] = $this->refereeModel->getReferees($categorie,self::PERPAGE,$this -> uri -> segment(3));

        $pagination = new Pagination( base_url().'referee/search', $this -> refereeModel -> countRefereesBy($categorie), self::PERPAGE, self::NUM_LINKS);
        $pagination->init_pagination();

        $text['referees_categories'] = $referess_categories;
        $text['text_referee'] = $this->get_text_view_referee($this->language);
        $text['num_referees'] = $this -> refereeModel -> countRefereesBy($categorie);

        $this->load->view('Estructura/header_principal');
        $this->load->view('Referees/referees', $text);
        $this->load->view('Estructura/footer');

    }

    /**
     * Funcion para crear arbitros, parametros pasados por POST
     */
    public function addReferee()
    {

        $dni = $this->input->post('dni');
        if(!$this ->validateDNI($dni))redirect(base_url() . 'referee?msg=' . SIZE_OF_DNI, 'refresh');
        if ($this->refereeModel->existsDNI($dni)) {
            if ($this->refereeModel->hasRefereeCategory($dni)) {
                redirect(base_url() . 'referee?msg=' . ERROR_DNI_EXISTS, 'refresh');
            } else {
                $this->session->set_userdata('dni_add_referee_category', $dni);
                redirect(base_url() . 'referee?msg=' . LOAD_MODAL_CREATE_REFEREE_CATEGORY);
            }
        }


        $nombre = $this->input->post('nombre');
        $apellido1 = $this->input->post('primer_apellido');
        $apellido2 = $this->input->post('segundo_apellido');
        $idCategoriaArbitral = $this->input->post('idCategoriaArbitral');
        $paisISOA3 = $this->input->post('paisISOA3');
        $autonomia = $this->input->post('autonomia');
        $provincia = $this->input->post('provincia');
        $email = $this->input->post('email');


        $this->refereeModel->createReferee($dni, $nombre, $apellido1, $apellido2, $idCategoriaArbitral, $paisISOA3, $autonomia,
            $provincia, $email) ? redirect(base_url() . 'referee?msg=' . SUCCESS_CREATE_REFEREE, 'refresh') :
            redirect(base_url() . 'referee?msg=' . ERROR_CREATE_REFEREE, 'refresh');

    }
    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;
    }

    /**
     * Funcion controladora de la asignacion de una categoria a un arbitro
     */
    public function addRefereeCategory()
    {
        $idRefereeCategory = $this->input->post('idRefereeCategory');
        $dni = $this->input->post('dni');

        $this->refereeModel->addRefereeCategory($idRefereeCategory, $dni);
        redirect(base_url() . 'referee?msg=' . SUCCESS_ADD_REFEREE_CATEGORY, 'refresh');
    }

    /**
     * Funcion controladora de la eliminación de un arbitro, es decir, su categoria arbitral
     */
    public function deleteReferee()
    {
        $dni = $this->input->post('dni');
        $this->load->model('refereeModel');
        $this->refereeModel->deleteReferee($dni) ? redirect(base_url() . 'referee?msg=' . SUCCESS_DELETE_REFEREE, 'refresh') :
            redirect(base_url() . 'team?msg=' . ERROR_DELETE_REFEREE, 'refresh');
    }

    /**
     * Funcion controladora de los datos de un arbitro.
     * Sirve para actualizar tambien su categoria arbitral
     */
    public function updateReferee()
    {
        $dni = $this->input->post('dni');
        $nombre = $this->input->post('nombre');
        $apellido1 = $this->input->post('apellido1');
        $apellido2 = $this->input->post('apellido2');
        $idCategoriaArbitral = $this->input->post('idCategoriaArbitral');
        $paisISOA3 = $this->input->post('paisISOA3');
        $autonomia = $this->input->post('autonomia');
        $provincia = $this->input->post('provincia');
        $email = $this->input->post('email');

    
        $this->load->model('refereeModel');
        $this->refereeModel->updateReferee($dni, $nombre, $apellido1, $apellido2, $idCategoriaArbitral, $paisISOA3, $autonomia,
            $provincia, $email) ? redirect(base_url() . 'referee?msg=' . SUCCESS_UPDATE_REFEREE, 'refresh') :
            redirect(base_url() . 'referee?msg=' . ERROR_UPDATE_REFEREE, 'refresh');

    }




    private function get_text_view_referee($idiom)
    {
        $this->lang->load('referee_lang', $idiom);
        $data['referee_dni'] = $this->lang->line('referee_dni');
        $data['referee_name'] = $this->lang->line('referee_name');
        $data['referee_create_referee'] = $this->lang->line('referee_create_referee');
        $data['referee_surname'] = $this->lang->line('referee_surname');
        $data['referee_second_surname'] = $this->lang->line('referee_second_surname');
        $data['referee_category'] = $this->lang->line('referee_category');
        $data['referee_country'] = $this->lang->line('referee_country');
        $data['referee_autonomous_community'] = $this->lang->line('referee_autonomous_community');
        $data['referee_province'] = $this->lang->line('referee_province');
        $data['referee_email'] = $this->lang->line('referee_email');
        $data['referee_btn_create'] = $this->lang->line('referee_btn_create');
        $data['referee_btn_delete'] = $this->lang->line('referee_btn_delete');
        $data['referee_btn_update'] = $this->lang->line('referee_btn_update');
        $data['referee_update_referee'] = $this->lang->line('referee_update_referee');
        $data['referee_not_exists_referees'] = $this->lang->line('referee_not_exists_referees');
        $data['referee_exists_dni'] = $this->lang->line('referee_exists_dni');
        $data['referee_exists_text'] = $this->lang->line('referee_exists_text');
        $data['referee_add_category'] = $this->lang->line('referee_add_category');

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

        $data['referee_num_referees_info'] = $this->lang->line('referee_num_referees_info');
        $data['referee_total_referees'] = $this->lang->line('referee_total_referees');
        $data['referee_input_all'] = $this->lang->line('referee_input_all');
        return $data;
    }


}
