<?php

/**
 * Clase controladora de la inscripcion de competidores en una determinada competicion
 * Created by PhpStorm.
 * User: Pablo García Sanz
 * Date: 21/08/2017
 * Time: 17:39
 */
class CompetitorInscription extends CI_Controller
{
    const DEFAULT_SEX = 'M';
    private $language;
    private $text_competitor_inscription;

    function __construct()
    {
        include "application/src/CompetitorModelo.php";
        parent::__construct();

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

        $this->language = $this->session->userdata('language');
        $this->load->model('competitionModel');
        $this->load->model('competitorModel');
        $this->load->model('teamModel');



    }

    /**
     * Funcion que muestra la vista donde se pueden inscribir a los competidores en una determianda competcion cuyo
     * id es pasado por parametro
     * @param $id de la competicion donde se quieren inscribir a los competidores
     */
    public function competitor_inscription($id)
    {
        $sex = $this->input->post('sex');
        if($sex != null) $this -> session -> set_userdata('sex',$sex);

        if($this -> session -> has_userdata('sex')){
            $sex = $this -> session -> userdata('sex');
        }
        else{
            $sex = self::DEFAULT_SEX;
        }

        $data['competition'] = $this->competitionModel->getCompetition($id);
        if($data['competition'] == null) show_404();
        $data['weights'] = $this->competitionModel->getWeigths($id, $sex);
        $data['teams'] = $this->teamModel->getAllTeams();

        $competitors_p = array();

        foreach ($data['weights'] as $weight) {
            $competitors_p[$weight->idPeso] = CompetitorModelo::getCompetitorsByIdWeight($weight->idPeso, $data['competition']->fecha, $data['competition']->idCompeticion);
        }
        $data['competitors_p'] = $competitors_p; // competidores relaccionados con un determinado peso de una determinada competicion
        $data['dnis'] = CompetitorModelo::getPeople();
        $data['text_competitor_inscription'] = $this -> text_competitor_inscription($this->language);
        $data['text_lateral_nav'] = $this ->get_text_lateral_nav($this -> language);
        $this->load->view('Estructura/header_principal');
        $this->load->view('Competition/competitor_inscription', $data);
        $this->load->view('Estructura/footer');

    }

    /**
     * Funcion de controlador utilizada para crear un competidor si no existe y asociarle auna participacion en un peso y una inscripcion
     */
    public function enrollCompetitor()
    {

        $competition_date = $this->input->post('competition_date');
        $idCompetition = $this->input->post('idCompetition');
        $dni = $this->input->post('dni');
        if(!$this -> validateDNI($dni)) redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . SIZE_OF_DNI);
        $name = $this->input->post('name');
        $surname = $this->input->post('surname');
        $surname2 = $this->input->post('surname2');
        $countryISOA3 = $this->input->post('country');
        $community = $this->input->post('community');
        $province = $this->input->post('province');
        $teamName = $this->input->post('team');
        $email = $this->input->post('email');
        $idWeight = $this->input->post('idWeight');
        $competitor = new CompetitorModelo($dni, $name, $surname, $surname2, $countryISOA3, $community, $province, $email);
        if ($competitor->existsInscription($idCompetition)) {
            redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . EXISTS_INSCRIPTION);
        } else {
            try {
                CompetitorModelo::createCompetitor($competitor);
                CompetitorModelo::createParticipation($idWeight, $dni, $competition_date);
                CompetitorModelo::createInscription($idCompetition, $dni, $teamName);
                redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . SUCCESS_COMPETITOR_INSCRIPTION);

            } catch (Exception $e) {
                log_message('Error' . $e);
            }

        }


    }
    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 de controlador que inscribe a un competidor definitivamente en un determinado peso
     */
    public function definitive_registration()
    {
        $competition_date = $this->input->post('competition_date');
        $idCompetition = $this->input->post('idCompetition');
        $dni = $this->input->post('dni');
        $teamName = $this->input->post('teamName');
        $idWeight = $this->input->post('idWeight');

        CompetitorModelo::createParticipation($idWeight, $dni, $competition_date);
        CompetitorModelo::createInscription($idCompetition, $dni, $teamName);
        redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . SUCCESS_COMPETITOR_INSCRIPTION);
    }

    /**
     * Funcion del controlador que gestiona la actualizacion de participaciones de un competidor a otro peso diferente
     * Los parametros son pasados por post de la llamada AJAX.
     */
    public function updateParticipation()
    {
        $oldWeight = $this->input->post('oldWeight');
        $date = $this->input->post('date');
        $newWeight = $this->input->post('idWeight');
        $dni = $this->input->post('dni');
        try {
            $this->competitorModel->updateParticipation($dni, $date, $newWeight, $oldWeight);

        } catch (Exception $e) {
            log_message('Error' . $e);
        }

    }

    /**
     * Funcion que elimina la participacion de un competidor en una determinada competicion
     */
    public function deleteCompetitor()
    {
        $oldWeight = $this->input->post('oldweight');
        $idCompetition = $this->input->post('idCompetition');
        $date = $this->input->post('fecha');
        $dni = $this->input->post('dni');

        try {

            $this->competitorModel->deleteInscription($idCompetition, $dni);
            $this->competitorModel->deleteParticipation($oldWeight, $date, $dni);
            redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . SUCCESS_DELETE_COMPETITOR_PARTICIPATION);
        } catch (Exception $e) {
            log_message('Error' . $e);
            redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . ERROR_COMPETITION_EXISTS);
        }
    }

    /**
     * Funcion del controlador utilizada para inscribir a competidores
     * Parametros pasados por POST
     */
    public function inscription()
    {

        $idCompetition = $this->input->post('idCompetition');
        $competition_date = $this->input->post('competition_date');
        $idWeight = $this->input->post('idWeight');
        $dni = $this->input->post('dni');
        $team = $this->input->post('team');
        if ($this->competitionModel->existsInscription($dni, $idCompetition)) {
            redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . EXISTS_INSCRIPTION);
        }
        try {

            CompetitorModelo::createParticipation($idWeight, $dni, $competition_date);
            CompetitorModelo::createInscription($idCompetition, $dni, $team);
            redirect(base_url() . 'competitorInscription/competitor_inscription/' . $idCompetition . '?msg=' . SUCCESS_COMPETITOR_INSCRIPTION);

        } catch (Exception $e) {
            log_message('Error' . $e);
        }
    }

    private function text_competitor_inscription($idiom) {
        $this->lang->load('competitor_inscription', $idiom);
        $data['competitor_inscription_modal_exists_competitor_enter_dni'] = $this->lang->line('competitor_inscription_modal_exists_competitor_enter_dni');
        $data['competitor_inscription_modal_exists_select_team'] = $this->lang->line('competitor_inscription_modal_exists_select_team');
        $data['competitor_inscription_modal_exists_team'] = $this->lang->line('competitor_inscription_modal_exists_team');
        $data['competitor_inscription_modal_exists_enroll'] = $this->lang->line('competitor_inscription_modal_exists_enroll');

        $data['competitor_inscription_modal_not_exists_nombre'] = $this->lang->line('competitor_inscription_modal_not_exists_nombre');
        $data['competitor_inscription_modal_not_exists_surname'] = $this->lang->line('competitor_inscription_modal_not_exists_surname');
        $data['competitor_inscription_modal_not_exists_surname2'] = $this->lang->line('competitor_inscription_modal_not_exists_surname2');
        $data['competitor_inscription_modal_not_exists_country'] = $this->lang->line('competitor_inscription_modal_not_exists_country');
        $data['competitor_inscription_modal_not_exists_community'] = $this->lang->line('competitor_inscription_modal_not_exists_community');
        $data['competitor_inscription_modal_not_exists_province'] = $this->lang->line('competitor_inscription_modal_not_exists_province');
        $data['competitor_inscription_modal_not_exists_team'] = $this->lang->line('competitor_inscription_modal_not_exists_team');
        $data['competitor_inscription_modal_not_exists_email'] = $this->lang->line('competitor_inscription_modal_not_exists_email');

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

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

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

        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');

        return $data;

    }


}