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

/**
 * Class Welcome controlador del login de usuarios
 */
class Welcome extends CI_Controller
{
    private $language;

    function __construct()
    {
        parent::__construct();


        $this -> load -> model ('timekeeperModel');
        $this->load->model('delegadoModel');


    }


    /**
     * Funcion controladora que muestra la vista de inicio de session para ambos roles
     * tanto como cronometrador como delegado.
     */
    public function index()
    {
        

            if(!$this -> session -> has_userdata('language')) $this->session->set_userdata('language', DEFAULT_LANGUAGE);
            $language = $this->session->userdata('language');
            $data = $this->get_text_view_login($language);

            $this->load->view('Estructura/header_styles');
            $this->load->view('Registro/login', $data);
            $this->load->view('Estructura/footer');




    }


    /**
     * Funcion controladora del inicio de sesion .
     * Rol delegado
     * Rol cronometrador
     */
    public function login() {
        header('Last-Modified:' . gmdate('D,d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate,max-age=0');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');

        if($this -> session -> has_userdata('user')) {
            $data['text_inicio'] = $this -> get_text_inicio($this -> session -> userdata('language'));
            $this->load->view('Estructura/header_principal');
            $this->load->view('Principal/inicio',$data);
            $this->load->view('Estructura/footer');
        }
        else if($this -> session -> has_userdata('timekeeper')) {
            $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');
        }

        else if($this->delegadoModel->existsEmail($this->input->post('email'))) {
            $this->delegadoModel->validatePassword($this->input->post('email'), $this->input->post('password')) ?
                $this->go_to_inicio_page($this->input->post('email')) : redirect(base_url() . '?msg=' . ERROR_ENTER_EMAIL_OR_PASSWORD, 'refresh');
        }
        else if ($this -> timekeeperModel -> existsEmail($this->input->post('email'))) {
            $this -> timekeeperModel -> validatePassword($this->input->post('email'),$this->input->post('password')) ? $this -> go_to_index_timekeeper($this->input->post('email')): redirect(base_url() . '?msg=' . ERROR_ENTER_EMAIL_OR_PASSWORD, 'refresh');;
        }
        else {
            redirect(base_url() . '?msg=' . ERROR_ENTER_EMAIL_OR_PASSWORD, 'refresh');
        }
    }
    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 go_to_index_timekeeper($user) {
        $this -> session -> set_userdata('timekeeper',$user);
        $mats = $this ->timekeeperModel -> getMats($user);
        $data['timekeeper_text'] = $this -> get_text_timekeeper_combat($this -> session -> userdata('language'));
        $data['mats']= $mats;
        $this -> load -> view ('Estructura/header_timekeeper');
        $this -> load -> view ('Timekeepers/timekeeper_mats',$data);
        $this -> load -> view ('Estructura/footer');
    }

    /**
     * Funcion controladora de olvidar contraseña del usuario con rol de delegado
     */
    public function forget_password()
    {
        $language = $this->session->userdata('language');
        $data = $this->get_text_reset_password($language);
        $this->load->view('Estructura/header_styles');
        $this->load->view('Registro/forget_password', $data);
        $this->load->view('Estructura/footer');
    }

    /**
     * Funcion que envia un email al delegado para que pueda recuperar la contraseña
     * Funciona mediante el servicio smtp que ofrece gmail
     */
    public function send_email()
    {
        $language = $this->session->userdata('language');
        $text = $this->get_text_recovery_email($language);
        $email_to = $this->input->post('email');
        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.gmail.com',
            'smtp_port' => 465,
            'smtp_user' => 'judocupapp@gmail.com',
            'smtp_pass' => 'ushirogoshi',
            'mailtype' => 'html',
            'charset' => 'utf-8',
            'newline' => "\r\n"
        );
        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $this->email->initialize($config);


        $this->load->model('delegadoModel');
        if ($this->delegadoModel->existsEmail($email_to)) {
            $token = password_hash(time(), PASSWORD_BCRYPT);
            $url_recovery_password = base_url() . 'registro/recoveryPassword/' . '?token=' . $token . '&email=' . $email_to;
            $this->delegadoModel->setToken($email_to, $token);
            $this->email->from('judocupapp@gmail.com', 'Administrator');
            $this->email->to($email_to);
            $this->email->subject($text['email_recovery_subject']);
            $nombre_delegado = $this->delegadoModel->getDelegado($email_to)->nombre;
            $email_message = "
                        <html>
                          
                            <body>
                                    <p>" . $text['email_recovery_initial_greeting'] . $nombre_delegado . "</p>
                                    <br>
                                    <p>" . $text['email_recovery_body_message'] . $email_to . " </p>
                                    <p>" . $text['email_recovery_body_message2'] . "</p>
                                    <a 
                                            style='background-color: #3f51b5;
                                            color:white;
                                            padding: 14px 25px;
                                            text-align: center;
                                            text-decoration: none;
                                            border-radius: 15px;
                                            display: inline-block;
                                    '
                                    href=" . $url_recovery_password . ">
                                        " . $text['email_recovery_btn'] . "
                                    </a>
                                    <br>
                                    <p> " . $text['email_recovery_farewell_greeting'] . "</p>
                            </body>
                        </html>
            ";
            try {

                $this->email->message($email_message);

                $this->email->send();
            }
            catch (Exception $e) {
                redirect(base_url() . '?msg=' . RECOVERY_PASSWORD_SENT, 'refresh');
            }


             redirect(base_url() . '?msg=' . RECOVERY_PASSWORD_SENT, 'refresh');
        } else {
            // Simulamos que se envia el mensaje para evitar asi que desconocidos sepan si existe ese email o no.
            redirect(base_url() . '?msg=' . RECOVERY_PASSWORD_SENT, 'refresh');
        }

    }

    /**
     * @param $idiom idioma p.e 'english' or 'spanish'
     * @return Un array asociativo con el texto en funcion del idioma de la pagina
     */
    private function get_text_view_login($idiom)
    {
        $this->lang->load('login_lang', $idiom);
        $data['msg_email'] = $this->lang->line('error_enter_email');
        $data['msg_password'] = $this->lang->line('msg_enter_password');
        $data['msg_forget_password'] = $this->lang->line('msg_forget_password');
        $data['msg_create_account'] = $this->lang->line('msg_create_account');
        $data['modal_error_email'] = $this->lang->line('modal_error_email');
        $data['modal_error_email_content'] = $this->lang->line('modal_error_email_content');
        $data['login'] = $this->lang->line('msg_login');
        return $data;
    }


    private function get_text_reset_password($idiom)
    {
        $this->lang->load('forget_password', $idiom);
        $data['enter_email'] = $this->lang->line('enter_email');
        $data['btn_send_reset_email'] = $this->lang->line('btn_send_reset_email');
        $data['enter_email'] = $this->lang->line('enter_email');
        $data['forget_password_title'] = $this->lang->line('forget_password_title');
        $data['forget_password_msg1'] = $this->lang->line('forget_password_msg1');

        return $data;
    }

    private function get_text_recovery_email($idiom)
    {
        $this->lang->load('email', $idiom);
        $data['email_recovery_subject'] = $this->lang->line('email_recovery_subject');
        $data['email_recovery_initial_greeting'] = $this->lang->line('email_recovery_initial_greeting');
        $data['email_recovery_body_message'] = $this->lang->line('email_recovery_body_message');
        $data['email_recovery_body_message2'] = $this->lang->line('email_recovery_body_message2');
        $data['email_recovery_farewell_greeting'] = $this->lang->line('email_recovery_farewell_greeting');
        $data['email_recovery_btn'] = $this->lang->line('email_recovery_btn');
        return $data;
    }

    private function get_text_inicio($idiom) {
        $this->lang->load('inicio', $idiom);
        $data['inicio_carousel_competitions'] = $this->lang->line('inicio_carousel_competitions');
        $data['inicio_carousel_competitions_create'] = $this->lang->line('inicio_carousel_competitions_create');
        $data['inicio_carousel_competitions_enroll_competitor'] = $this->lang->line('inicio_carousel_competitions_enroll_competitor');
        $data['inicio_carousel_competitions_enroll_referee'] = $this->lang->line('inicio_carousel_competitions_enroll_referee');
        $data['inicio_carousel_competitions_view_results'] = $this->lang->line('inicio_carousel_competitions_view_results');

        $data['inicio_carousel_teams'] = $this->lang->line('inicio_carousel_teams');
        $data['inicio_carousel_teams_create'] = $this->lang->line('inicio_carousel_teams_create');
        $data['inicio_carousel_teams_edit'] = $this->lang->line('inicio_carousel_teams_edit');

        $data['inicio_carousel_referee'] = $this->lang->line('inicio_carousel_referee');
        $data['inicio_carousel_referee_create'] = $this->lang->line('inicio_carousel_referee_create');
        $data['inicio_carousel_referee_update'] = $this->lang->line('inicio_carousel_referee_update');

        $data['inicio_carousel_competitors'] = $this->lang->line('inicio_carousel_competitors');
        $data['inicio_carousel_referee_classify'] = $this->lang->line('inicio_carousel_referee_classify');
        $data['inicio_carousel_referee_results'] = $this->lang->line('inicio_carousel_referee_results');

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


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

        return $data;
    }

    private function go_to_inicio_page($email)
    {

        $this->session->set_userdata('user', $email);
//        redirect(base_url() . 'competition');
        $data['text_inicio'] = $this -> get_text_inicio($this -> session -> userdata('language'));
        $this->load->view('Estructura/header_principal');
        $this->load->view('Principal/inicio',$data);
        $this->load->view('Estructura/footer');

    }



}

