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

/**
 * Clase Controlador Competicion, que gestiona la creación de competiciones de judo
 * Class Competition
 */
class Competition extends CI_Controller
{
    const PERPAGE = 4; // Numero de competiciones mostradas por página (pagination)
    const NUM_LINKS = 10; // Numero de links que se muestran ( pagination)
    private $language;

    private $competition_text;

    /**
     * Constructor de la clase Competicion. Inicializa el lenguaje en funcion de la sesion
     * Comprueba que este iniciada la sesión del usuario con rol delegado
     * Competition constructor.
     */
    function __construct()
    {
        parent::__construct();

        if (!$this->session->has_userdata('user'))
            redirect(base_url() . '?msg=' . SESSION_EXPIRED, 'refresh');

        $this->load->model('competitionModel');
        $this->load->model('competitionTypeModel');
        $this->load->model('ageGroupModel');
        $this->load->model('refereeModel');
        $this->load->model('teamModel');
        $this->load->model('timekeeperModel');
        $this->load->model('combatModel');

        $this->language = $this->session->userdata('language');
        include "application/src/Pagination.php";

        $this->competition_text = $this->get_text_competition_index($this->language);


    }

    /**
     * Funcion del controlador que muestra las competiciones que hay en la base de datos
     *
     */
    public function index()
    {
        $competitions = $this->competitionModel->getAllCompetitions();


        $data_body['competitionType'] = $this->competitionTypeModel->getCompetitionTypes();
        $data_body['ageGroup'] = $this->ageGroupModel->getAgeGroupTypes();
        $data_body['competitions'] = $this->competitionModel->getCompetitionsBy(self::PERPAGE, $this->uri->segment(3));
        $data_body['competition_text'] = $this->competition_text;

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

        $this->load->view('Estructura/header_principal');
        $this->load->view('Competition/competitions', $data_body);
        $this->load->view('Estructura/footer');
    }

    /**
     * Funcion del controlador que sirve para crear competciones de judo. Todos los campos se pasan en el
     * post del formulario
     */
    public function create()
    {

        $numeroTatamis = $this->input->post('numeroDeTatamis');  // Para crear N instancias de Tatami y asociarlos al id de la competicion
        $nombre = $this->input->post('nombre');
        $fecha = $this->input->post('fecha');
        $paisISOA3 = $this->input->post('paisISOA3');
        $autonomia = $this->input->post('autonomia');
        $provincia = $this->input->post('provincia');
        $pabellon = $this->input->post('pabellon');

        $idTipoCompeticion = $this->input->post('tipoCompeticion');
        $grupoEdad = $this->input->post('grupoEdad');
        if($numeroTatamis == null|| $nombre == null || $fecha == null|| $grupoEdad == null || $autonomia == null || $idTipoCompeticion == null) {
            redirect(base_url() . 'competition?msg=' . ERROR_CREATE_COMPETITION);
        }
        $emailDelegado = $this->session->userdata('user');
        try {
            if ($this->competitionModel->existsCompetition($fecha, $grupoEdad)) {
                redirect(base_url() . 'competition?msg=' . ERROR_COMPETITION_EXISTS);
            } else {
                $this->competitionModel->createCompetition($nombre, $fecha, $paisISOA3, $autonomia, $provincia, $pabellon, $emailDelegado,
                    $grupoEdad, $idTipoCompeticion, $numeroTatamis);
                redirect(base_url() . 'competition?msg=' . SUCCESS_CREATE_COMPETITION);
            }

        } catch (Exception $e) {
            log_message($e->getMessage());
            redirect(base_url() . 'competition?msg=' . ERROR_CREATE_COMPETITION);
        }


    }

    /**
     * Funcion del controlador que sirve para eliminar una determinada competicion cuyo id es pasado por
     * parametro
     * @param $id de la competcion que se quiere eliminar
     */
    public function delete($id)
    {
        try {
            $this->competitionModel->deleteCompetition($id);
            redirect(base_url() . 'competition?msg=' . SUCCESS_DELETE_COMPETITION);
        } catch (Exception $e) {
            log_message($e->getMessage());
            redirect(base_url() . 'competition?msg=' . ERROR_DELETE_COMPETITION);
        }
    }

    /**
     * Funcion que muestra los pesos que tiene la competción cuyo id
     * es pasado por parametro a la funcion
     * @param $id de la competicion de la cual se quiere mostrar los combates
     */
    public function viewcompetition($id)
    {

        $competition = $this->competitionModel->getCompetition($id);
        if($competition == null) show_404();
        $mats = $this->competitionModel->getMatsByCompetitionId($id);
        $data['text_lateral_nav'] = $this -> get_text_lateral_nav($this -> session -> userdata('language'));
        $data['competition'] = $competition;
        $data['mats'] = $mats;
        $data['f_weights'] = $this->competitionModel->getWeigths($id, 'F');
        $data['m_weights'] = $this->competitionModel->getWeigths($id, 'M');

        $data['combat_text'] = $this -> get_combat_text($this -> language);
        $this->load->view('Estructura/header_principal');
        $this->load->view('Combats/competition_weights', $data);
        $this->load->view('Estructura/footer');
    }

    /**
     * Funcion que muestra los combates de una determinada competicion y en un determinado peso de la misma
     * El peso se pasa por medio de la url como un parametro capturado por medio de la funcion get
     * @param $id de la competicion que se quiere ver los combates
     */
    public function viewcombats($id){
        $competition = $this->competitionModel->getCompetition($id);
        if($competition == null) show_404();
        $idWeight = $this -> input -> get ('idWeight');
        $data['competitors_position'] = $this -> competitionModel -> getCompetitorsWithPosition($competition -> idCompeticion,$idWeight);
        $data['competitors'] = $this -> combatModel -> getCompetitorsByCompetitionAndIdWeight($competition -> fecha ,$idWeight);
        $mats = $this->competitionModel->getMatsByCompetitionId($id);
        $data['text_lateral_nav'] = $this -> get_text_lateral_nav($this -> session -> userdata('language'));
        $data['competition'] = $competition;
        $data['mats'] = $mats;
        $data['f_weights'] = $this->competitionModel->getWeigths($id, 'F');
        $data['m_weights'] = $this->competitionModel->getWeigths($id, 'M');
        $data['combats'] = $this -> combatModel -> getCombats($competition -> idCompeticion,$competition -> fecha,$idWeight);

        $data['combats_text'] = $this -> get_combat_text($this -> language);
        $this->load->view('Estructura/header_principal');
        $this->load->view('Combats/combats_weight_selected', $data);
        $this->load->view('Estructura/footer');

    }

    /**
     * Funcion del controlador que muestra la pagina donde se realizaran las inscripciones de arbitros y de cronometradores
     * @param $id de la competicion de la cual se quiere mostrar los arbitros que se quieren inscribir, asi mismo de los
     * cronometradores.
     */
    public function referee_inscription($id)
    {
        $competition = $this->competitionModel->getCompetition($id);
        if($competition == null) show_404();
        $data['referees'] = $this->competitionModel->getRefereesNotRolleIn($id);

        $data['competition'] = $competition;
        $data['teams'] = $this->teamModel->getAllTeams();
        $data['referees_rolle_in'] = $this->competitionModel->getRefereesRolleIn($id);
        $data['idCompetition'] = $id;
        $data['mats'] = $this->competitionModel->getMatsByCompetitionId($id);
        $data['referee_inscription_text'] = $this->get_text_referee_inscription($this->language);
        $data['text_lateral_nav'] = $this->get_text_lateral_nav($this->language);

        $mat_referees = array(); // Arbitros asignados a los tatamis de la competicion con id @param $id
        foreach ($data['mats'] as $mat) {
            $mat_referees[$mat->idTatami] = $this->competitionModel->getReferees($mat->idTatami);
        }
        $data['referees_not_associate'] = $this->competitionModel->getRefereesNotAssociateToMat($id);
        $data['mat_referees'] = $mat_referees;

        $data['timekeepers'] = $this ->timekeeperModel->getTimekeepersByIDCompetition($id);
        $this->load->view('Estructura/header_principal');
        $this->load->view('Competition/referees_inscriptions', $data);
        $this->load->view('Estructura/footer');
    }

    /**
     * Funcion que gestiona la inscripcion de arbitros en una competicion
     * @param $id de la competicion
     */
    public function addRefereeToCompetition($id)
    {

        $teams = $this->input->post('idTeams');

        foreach ($teams as $team) {

            $dni = json_decode($team) -> dni;
            $teamName = json_decode($team) -> team;
            try {
                $this->competitionModel->addRefereeToCompetition($id, $dni, $teamName);


            } catch (Exception $e) {
                log_message($e);
                redirect(base_url() . 'competition/referee_inscription/' . $id . '?msg=' . ERROR_ADD_REFEREE_TO_COMPETITION);
            }
        }
        redirect(base_url() . 'competition/referee_inscription/' . $id . '?msg=' . SUCCESS_ADD_REFEREE_TO_COMPETITION);


    }

    /**
     * Desinscribir a un arbitro de una competición
     * @param $idCompeticion de la cual se quiere desinscribir al árbitro de la competicion
     */
    public function deleteRefereeInscription($idCompeticion)
    {
        $dni_referee = $this->input->post('dni');
        try {
            $this->competitionModel->deleteRefereeInscription($idCompeticion, $dni_referee);
            redirect(base_url() . 'competition/referee_inscription/' . $idCompeticion . '?msg=' . SUCCESS_DELETE_REFEREE_INSCRIPTION);
        } catch (Exception $e) {
            log_message($e);
            redirect(base_url() . 'competition/referee_inscription/' . $idCompeticion . '?msg=' . ERROR_DELETE_REFEREE_INSCRIPTION);
        }

    }

    /**
     * Funncion que añade un determinado arbitro inscrito en una competicion a un tatami
     * Todos los parametros son capturados por el post del formulario
     */
    public function addRefereeToMat()
    {

        $idMat = $this->input->post('idMat');
        $dni = $this->input->post('dni');
        $idCompetition = $this->input->post('idCompetition');
        $this->competitionModel->addRefereeToMat($idMat, $dni, $idCompetition);


    }
    /**
    * Funcion del controlador que añade un cronometrador a un tatami de una competicion cuyo id es pasado por parametro
    * @param $idCompetition id de la competcion de la cual se quiere asignar el cronometrador
    */
    public function asignTimekeeperToMat($idCompetition) {
          
            $idMat = $this -> input -> post('mat');
            $email_timekeeper = $this -> input -> post('timekeeper');

          try {
            $email_timekeeper = $email_timekeeper == 'delete' ? null : $email_timekeeper;
            $this -> timekeeperModel -> addTimekeeperToMat($idMat,$email_timekeeper);
          }
          catch (Exception $e) {

          }
        $email_timekeeper == "delete" ?
            redirect(base_url() . 'competition/referee_inscription/' . $idCompetition . '?msg=' . SUCCESS_DELETE_TIMEKEEPER_TO_MAT,'refresh') :
            redirect(base_url() . 'competition/referee_inscription/' . $idCompetition . '?msg=' . SUCCESS_ADD_TIMEKEEPER_TO_MAT,'refresh');

          

    }


    private function get_text_competition_index($idiom)
    {
        $this->lang->load('competition_lang', $idiom);
        $data['competition_create_name'] = $this->lang->line('competition_create_name');
        $data['competition_create_date'] = $this->lang->line('competition_create_date');
        $data['competition_create_country'] = $this->lang->line('competition_create_country');
        $data['competition_create_community'] = $this->lang->line('competition_create_community');
        $data['competition_create_province'] = $this->lang->line('competition_create_province');
        $data['competition_create_sport_center'] = $this->lang->line('competition_create_sport_center');
        $data['competition_create_number_of_mats'] = $this->lang->line('competition_create_number_of_mats');
        $data['competition_create_category'] = $this->lang->line('competition_create_category');
        $data['competition_create_age_group'] = $this->lang->line('competition_create_age_group');

        $data['competition_card_mats'] = $this->lang->line('competition_card_mats');
        $data['competition_card_referee_inscription'] = $this->lang->line('competition_card_referee_inscription');
        $data['competition_card_competitor_inscription'] = $this->lang->line('competition_card_competitor_inscription');
        $data['competition_add_btn_tooltip'] = $this->lang->line('competition_add_btn_tooltip');
        $data['competition_create_btn'] = $this->lang->line('competition_create_btn');
        $data['competition_delete_btn'] = $this->lang->line('competition_delete_btn');
        $data['competition_update_btn'] = $this->lang->line('competition_update_btn');

        $data['competition_tooltip_mats'] = $this->lang->line('competition_tooltip_mats');
        $data['competition_tooltip_competitor_inscription'] = $this->lang->line('competition_tooltip_competitor_inscription');
        $data['competition_tooltip_referee_inscription'] = $this->lang->line('competition_tooltip_referee_inscription');

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

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

        return $data;

    }

    private function get_text_referee_inscription($idiom)
    {
        $this->lang->load('competition_lang', $idiom);
        $data['competition_referee_inscription_step1'] = $this->lang->line('competition_referee_inscription_step1');
        $data['competition_referee_inscription_step2'] = $this->lang->line('competition_referee_inscription_step2');
        $data['competition_referee_inscription_name'] = $this->lang->line('competition_referee_inscription_name');
        $data['competition_referee_inscription_surname'] = $this->lang->line('competition_referee_inscription_surname');
        $data['competition_referee_inscription_category'] = $this->lang->line('competition_referee_inscription_category');
        $data['competition_referee_inscription_team'] = $this->lang->line('competition_referee_inscription_team');
        $data['competition_referee_inscription_select'] = $this->lang->line('competition_referee_inscription_select');
        $data['competition_referee_inscription_enroll'] = $this->lang->line('competition_referee_inscription_enroll');
        $data['competition_referee_inscription_mat'] = $this->lang->line('competition_referee_inscription_mat');
        $data['competition_referee_inscription_referees_enroll'] = $this->lang->line('competition_referee_inscription_referees_enroll');
        $data['competition_referee_inscription_no_more_referees'] = $this->lang->line('competition_referee_inscription_no_more_referees');
        $data['competition_referee_inscription_confirm_delete'] = $this->lang->line('competition_referee_inscription_confirm_delete');

        $data['competition_referee_inscription_select_timekeeper'] = $this->lang->line('competition_referee_inscription_select_timekeeper');
        $data['competition_select_choose'] = $this->lang->line('competition_select_choose');
        $data['competition_select_delete_timekeeper'] = $this->lang->line('competition_select_delete_timekeeper');

        return $data;

    }

    private function get_text_lateral_nav($language)
    {
        $this->lang->load('nav_lateral_competition_lang', $language);

        $data['nav_lateral_competition_name'] = $this->lang->line('nav_lateral_competition_name');
        $data['nav_lateral_competition_type_of_competition'] = $this->lang->line('nav_lateral_competition_type_of_competition');
        $data['nav_lateral_competition_age_group'] = $this->lang->line('nav_lateral_competition_age_group');
        $data['nav_lateral_competition_date'] = $this->lang->line('nav_lateral_competition_date');
        $data['nav_lateral_competition_community'] = $this->lang->line('nav_lateral_competition_community');
        $data['nav_lateral_competition_province'] = $this->lang->line('nav_lateral_competition_province');

        $data['nav_lateral_competition_referee_inscription'] = $this->lang->line('nav_lateral_competition_referee_inscription');
        $data['nav_lateral_competition_competitor_inscription'] = $this->lang->line('nav_lateral_competition_competitor_inscription');
        $data['nav_lateral_competition_combats'] = $this->lang->line('nav_lateral_competition_combats');

        $data['nav_lateral_competition_choose_sex'] = $this->lang->line('nav_lateral_competition_choose_sex');
        $data['nav_lateral_competition_female'] = $this->lang->line('nav_lateral_competition_female');
        $data['nav_lateral_competition_male'] = $this->lang->line('nav_lateral_competition_male');
        $data['nav_lateral_number_of_mats'] = $this->lang->line('nav_lateral_number_of_mats');

        $data['nav_lateral_type_of_pairing'] = $this->lang->line('nav_lateral_type_of_pairing');
        $data['nav_lateral_select_algorithm'] = $this->lang->line('nav_lateral_select_algorithm');
        $data['nav_lateral_league'] = $this->lang->line('nav_lateral_league');
        $data['nav_lateral_random'] = $this->lang->line('nav_lateral_random');
        $data['nav_lateral_btn_generate'] = $this->lang->line('nav_lateral_btn_generate');
        $data['nav_lateral_tooltip_generate'] = $this->lang->line('nav_lateral_tooltip_generate');



        return $data;

    }

    private function get_combat_text($language) {
        $this->lang->load('combat_lang', $language);
        $data['combat_competition_name'] = $this->lang->line('combat_competition_name');
        $data['combat_date'] = $this->lang->line('combat_date');
        $data['combat_community'] = $this->lang->line('combat_community');
        $data['combat_province'] = $this->lang->line('combat_province');
        $data['combat_sport_center'] = $this->lang->line('combat_sport_center');
        $data['combat_view_combats'] = $this->lang->line('combat_view_combats');
        $data['combat_list_male_combats'] = $this->lang->line('combat_list_male_combats');
        $data['combat_list_female_combats'] = $this->lang->line('combat_list_female_combats');

        $data['combat_list_combats_without_score'] = $this->lang->line('combat_list_combats_without_score');
        $data['combat_list_with_score'] = $this->lang->line('combat_list_with_score');
        $data['combat_results'] = $this->lang->line('combat_results');
        $data['combat_name'] = $this->lang->line('combat_name');
        $data['combat_surname'] = $this->lang->line('combat_surname');
        $data['combat_surname2'] = $this->lang->line('combat_surname2');
        $data['combat_team_name'] = $this->lang->line('combat_team_name');
        $data['combat_create'] = $this->lang->line('combat_create');
        $data['combat_winner'] = $this->lang->line('combat_winner');
        $data['combat_2'] = $this->lang->line('combat_2');
        $data['combat_3'] = $this->lang->line('combat_3');
        $data['combat_5'] = $this->lang->line('combat_5');
        $data['combat_7'] = $this->lang->line('combat_7');

        // new modal

        $data['combat_modal_header'] = $this->lang->line('combat_modal_header');
        $data['combat_modal_requiered_fields'] = $this->lang->line('combat_modal_requiered_fields');
        $data['combat_modal_competitor_white'] = $this->lang->line('combat_modal_competitor_white');
        $data['combat_modal_competitor_blue'] = $this->lang->line('combat_modal_competitor_blue');
        $data['combat_modal_select_white'] = $this->lang->line('combat_modal_select_white');
        $data['combat_modal_select_blue'] = $this->lang->line('combat_modal_select_blue');
        $data['combat_modal_mat'] = $this->lang->line('combat_modal_mat');
        $data['combat_modal_select_mat'] = $this->lang->line('combat_modal_select_mat');
        $data['combat_modal_phase'] = $this->lang->line('combat_modal_phase');
        $data['combat_modal_btn_create'] = $this->lang->line('combat_modal_btn_create');

        $data['combat_modal_btn_add_score'] = $this->lang->line('combat_modal_btn_add_score');
        $data['combat_modal_bnt_update_score'] = $this->lang->line('combat_modal_bnt_update_score');
        $data['combat_modal_change_mat'] = $this->lang->line('combat_modal_change_mat');
        $data['combat_toast_msg_delete_combat'] = $this->lang->line('combat_toast_msg_delete_combat');
        $data['combat_toast_msg_create_combat'] = $this->lang->line('combat_toast_msg_create_combat');

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

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

        return $data;
    }

}
