<?php

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

class Tasks extends CI_Controller {

    public $user_data = array();

    public function __construct() {
        parent::__construct();
        $this->user_data = $this->ion_auth->check_user_privilege(array('Firma', 'Admin'));
        $this->load->model(array('company_model', 'company_projects_model', 'projects_tasks_model', 'company_professions_model'));
        $this->breadcrumbs->push('Start', '/');
        $this->company_id = $this->ion_auth->user()->row()->id;
        $this->company = $this->ion_auth->logged_in() ? $this->ion_auth->user()->row()->company : false;
        $this->base_url = base_url() . '/tasks/' . $this->router->fetch_method();
    }
    
    public function pre($tab){
        echo '<pre>';
        print_r($tab);
        echo '</pre>';
    }
    
    public function daneJS($tabDanych){
        // pobierz max i min z całego  zakresu
        $minLimit = array();
        $maxLimit = array();
        // na czas unixowy
        if($tabDanych){
            foreach($tabDanych as $dane0){
                $tabLimits[] = strtotime($dane0['dataStart']);
                $tabLimits[] = strtotime($dane0['dataStop']);
            }

            $minLimitNum = min($tabLimits);

            $minLimitDate = date("Y-m-d", $minLimitNum);
            $minLimit = explode( "-", $minLimitDate );

            $maxLimitNum = max($tabLimits);
            $maxLimitDate =  date("Y-m-d", $maxLimitNum);
            $maxLimit = explode( "-", $maxLimitDate);

            $str= '';
            $dataTaski = '';
            $textjs = '';

            //$this->pre($minLimitNum);

            foreach($tabDanych as $dane){   
                $dataTaski .= '"'.$dane['taskNazwa'].'",';
                $taskJS = $dane['taskNazwa'];
                $dataStartNum = strtotime($dane['dataStart']);
                $dataStopNum = strtotime($dane['dataStop']);
                $rozwal_start = explode("-", $dane['dataStart']);
                $rozwal_stop = explode("-", $dane['dataStop']);

                $str = 'label: "'.$taskJS.'",data: [{x:new Date('.$rozwal_start[0].', '.$rozwal_start[1].', '.$rozwal_start[2].'),y:"'.$taskJS.'"},{x:new Date('.$rozwal_stop[0].', '.$rozwal_stop[1].', '.$rozwal_stop[2].'),y:"'.$taskJS.'"}],';



                $textjs .= '{'.$str.'
                    backgroundColor: "#73c6a8",
                    borderColor: "#73c6a8",
                    pointBorderWidth: 5,
                    borderWidth: 10,
                    fill: false},';

            }
        
        }
        else{
            $dataTaski = '';  
            $textjs = '';
            $minLimit[0] = 0; $minLimit[1] = 0; $minLimit[2] = 0; 
            $maxLimit[0] = 0; $maxLimit[1] = 0; $maxLimit[2] = 0; 
        }
        
        $calosc = '<script>
                    var ctx = document.getElementById("myChart");
                    var myChart = new Chart(ctx, {
                        type: "line",
                        data: {
                            labels: ["Start",'.$dataTaski.',"Koniec"],
                            datasets: [
                                '.$textjs.'
                                      ]
                        },
                        options: {
                            legend: {
                                display: false,
                            },        
                            scales: {
                                xAxes: [{
                                    type: "time",
                                    time: {
                                        displayFormats: {
                                            millisecond: "YYYY-MM-DD",
                                            second: "YYYY-MM-DD",
                                            minute: "YYYY-MM-DD",
                                            hour: "YYYY-MM-DD",
                                            day: "DD-MM",
                                            week: "DD-MM",
                                            month: "YYYY-MM",
                                            year: "YYYY"  
                                        },
                                        minUnit: "day",
                                        min: new Date('.$minLimit[0].','.$minLimit[1].','.$minLimit[2].'),
                                        max: new Date('.$maxLimit[0].','.$maxLimit[1].','.$maxLimit[2].')
                                    }
                                }],
                                yAxes: [{
                                    type: "category",
                                    ticks: {
                                        max: 25,
                                        min: 0,
                                        stepSize: 1
                                    }
                                }]            
                            }
                        }
                    });
                    </script>';
        
       return $calosc; 

    }

    public function index($project_id = null) {
        if (!is_numeric($project_id))
            redirect('/');
        $company_id = $this->company_projects_model->get_companyid_byproject($project_id);
        if (!($this->user_data['is_admin'] or ( $company_id == $this->company_id) and $this->user_data['is_firma'])) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }
        $this->breadcrumbs->push('Firma', '/firma/index/' . $company_id);
        $this->breadcrumbs->push('Staże', '/projects/index/' . $company_id);
        $this->breadcrumbs->push('Zadania', '/tasks/index/' . $project_id);

        $this->load->config('pagination', true);
        $config = $this->config->config['pagination'];
        $config['base_url'] = $this->base_url . '/' . $project_id;
        $config['total_rows'] = $this->projects_tasks_model->get_list($project_id, null, null, true);
        $page = $this->uri->segment(4, 1);
        $config['uri_segment'] = 4;
        $data['stanowiska'] = $this->projects_tasks_model->get_list($project_id, $config['per_page'], $page, false);
        $data['company'] = $this->company_model->get_name($company_id);
        $data['project'] = $this->company_projects_model->get_name($project_id);
        $data['company_id'] = $company_id;
        $data['project_id'] = $project_id;
        $data['page'] = $page;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();

        foreach($data['stanowiska'] as $kl => $dx){
            if(strlen($dx['task_name'])>10){
                $taskNazwa = substr($dx['task_name'], 0, 10);
                $taskNazwa.="...";
            }
            else{
                $taskNazwa = $dx['task_name'];
            }
            $datyx[$kl]['taskNazwa'] = $taskNazwa; 
            $datyx[$kl]['dataStart'] = $dx['date_start'];     
            $datyx[$kl]['dataStop'] = $dx['date_stop'];
        }
        
        
        if( !isset($datyx) ){
            $datyx = array();
        }
        $data['daneWykres'] = $this->daneJS($datyx);
        
        
        
        $this->load->view('Base_header');
        $this->load->view('tasks/index', $data);
        $this->load->view('Base_footer');
    }
    
    public function delete_profession($task_id,$profession_id) {
        if (!is_numeric($task_id)) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }
        $company_id = $this->projects_tasks_model->get_companyid_bytask($task_id);
        if (!is_numeric($company_id)) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }
        if (!($this->user_data['is_admin'] or ( $company_id == $this->company_id) and $this->user_data['is_firma'])) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }        
        if(is_numeric($profession_id)){
            $del = $this->projects_tasks_model->delete_task_profession($task_id,$profession_id);
            if($del)
            $this->session->set_flashdata('message', 'Stanowisko zostało usunięte');
            redirect('/tasks/edit_task/'.$task_id.'#professions');            
        }
    }
    

    public function add_profession($task_id) {
        if (!is_numeric($task_id)) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }
        $company_id = $this->projects_tasks_model->get_companyid_bytask($task_id);
        if (!is_numeric($company_id)) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }
        if (!($this->user_data['is_admin'] or ( $company_id == $this->company_id) and $this->user_data['is_firma'])) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }

        if (!empty($this->input->post())) {
            $this->form_validation->set_rules('number_of_students', 'Ilość studentów', 'trim|required');
            $this->form_validation->set_rules('profession_id', 'Stanowisko', 'trim|required|numeric', 'Wybierz tanowisko');
            if ($this->form_validation->run() == FALSE) {
                $this->session->set_flashdata('error', 'Popraw formularz.<br/>' . validation_errors());
                redirect('/tasks/edit_task/' . $task_id.'#professions');
            } else {
                $add = $this->projects_tasks_model->insert_task_profession($task_id, $this->input->post());
                if ($add) {
                    $this->session->set_flashdata('message', 'Stanowikso zostało dodane');
                }
                redirect('/tasks/edit_task/' . $task_id.'#professions');
            }
        }
    }

    public function add_task_project($company_id = null, $project_id = null) {
        $this->add_task($company_id, null, $project_id);
    }

    public function edit_task($task_id, $project_id = null) {
        if (!is_numeric($task_id))
            redirect('/');
        $company_id = $this->projects_tasks_model->get_companyid_bytask($task_id);
        if (!is_numeric($company_id))
            redirect('/');
        $this->add_task($company_id, $task_id,$project_id);
    }    
    

    public function add_task($company_id = null, $task_id = null, $select_project_id = null) {
        if (!is_numeric($company_id))
            redirect('/');
        if (!($this->user_data['is_admin'] or ( $company_id == $this->company_id) and $this->user_data['is_firma'])) {
            $this->session->set_flashdata('error', 'Nie masz uprawnień');
            redirect('/');
        }
        if (!$this->company_model->check_isset($company_id))
            redirect('/');

        if (!empty($this->input->post())) {
            $this->form_validation->set_rules('task_name', 'Nazwa zadania', 'trim|required');
            $this->form_validation->set_rules('description', 'Opis', 'trim|required|min_length[3]|max_length[1000]');
            $this->form_validation->set_rules('duration', 'Czas trwania', 'trim|numeric');
            if ($this->form_validation->run() == FALSE) {
                $this->session->set_flashdata('error', 'Popraw formularz.<br/>' . validation_errors());
            } else {
                if (is_numeric($task_id)) {
                    $update = $this->projects_tasks_model->update($task_id, $this->input->post());
                    if ($update)
                        $this->session->set_flashdata('message', 'Zadanie zostało zmienione');
                    else
                        $this->session->set_flashdata('error', 'Zadanie nie zostało zmienione');
                    redirect('tasks/edit_task/' . $task_id);
                }else {
                    $task_id = $this->projects_tasks_model->insert($company_id, $this->input->post());
                    if ($task_id)
                        $this->session->set_flashdata('message', 'Zadanie zostało dodane');
                    else
                        $this->session->set_flashdata('error', 'Zadanie nie zostało dodane');
                    redirect('tasks/index/' . $this->input->post('project_id'));
                }
            }
        }

            $this->breadcrumbs->push('Firma', '/firma/index/' . $company_id);
            $this->breadcrumbs->push('Staże', '/projects/index/' . $company_id);
            $this->breadcrumbs->push('Zadania', '/tasks/index/' . $select_project_id);
        
        
        if (is_numeric($task_id)) {
            $this->breadcrumbs->push('Edytuj zadanie', '/tasks/edit_task_project/');
            $task_data = $this->projects_tasks_model->get_task($task_id);
            $task_professions_data = $this->projects_tasks_model->get_task_professions($task_id);
        } else{
            $this->breadcrumbs->push('Dodaj zadanie', '/tasks/add_task_project/');
            $task_data = array();
            $task_professions_data = array();
        }

        $data = $this->form_add_task($company_id, $task_data, $select_project_id);
        $data['id'] = is_numeric($task_id) ? $task_id : null;
        $pom_data = $this->form_add_profession($company_id,$task_id);
        $data = array_merge($data, $pom_data);        
        $data['task_professions'] = $task_professions_data;
        $this->load->view('Base_header');
        $this->load->view('tasks/form_add_task', $data);
        $this->load->view('Base_footer');
    }

    private function form_add_profession($company_id,$task_id) {
        $form_data['profession_id'] = array(
            'name' => 'profession_id',
            'class' => 'form-control',
        );
        
        $data['number_of_students'] = '';
        
        $form_data['profession_array'] = $this->company_professions_model->get_list_forform($company_id,$task_id);
        $form_data['profession_select'] = set_value('profession_id');

        $form_data['number_of_students'] = array(
            'name' => 'number_of_students',
            'type' => 'text',
            'value' => set_value('number_of_students') != "" ? set_value('number_of_students') : $data['number_of_students'],
            'class' => 'form-control',
            'placeholder' => 'Ilość studentów'
        );
        return $form_data;
    }

    private function form_add_task($company_id, $data = array(), $select_project_id = null) {
        $form_data['project_id'] = array(
            'name' => 'project_id',
            'class' => 'form-control',
        );
        

        
        $form_data['project_array'] = $this->company_projects_model->get_list_forform($company_id);
        if (isset($data['project_id'])){
            $select_project_id = $data['project_id'];
        }
        else{
            $data['task_name'] = '';
            $data['description'] = '';
            $data['date_start'] = '';
            $data['date_stop'] = '';
            $data['duration'] = '';
        }
            
        $form_data['project_select'] = set_value('project_id') != "" ? set_value('project_id') : $select_project_id;

        $form_data['task_name'] = array(
            'name' => 'task_name',
            'type' => 'text',
            'value' => set_value('task_name') != "" ? set_value('task_name') : $data['task_name'],
            'class' => 'form-control',
            'placeholder' => 'Nazwa zadania'
        );

        $form_data['description'] = array(
            'name' => 'description',
            'type' => 'text',
            'value' => set_value('description') != "" ? set_value('description') : $data['description'],
            'class' => 'form-control',
            'placeholder' => 'Opis'
        );

        $form_data['date_start'] = array(
            'name' => 'date_start',
            'type' => 'text',
            'value' => set_value('date_start') != "" ? set_value('date_start') : $data['date_start'],
            'class' => 'form-control datepicker',
            'placeholder' => 'Data rozpoczęcia'
        );
        $form_data['date_stop'] = array(
            'name' => 'date_stop',
            'type' => 'text',
            'value' => set_value('date_stop') != "" ? set_value('date_stop') : $data['date_stop'],
            'class' => 'form-control datepicker',
            'placeholder' => 'Data zakończenia'
        );

        $form_data['duration'] = array(
            'name' => 'duration',
            'type' => 'text',
            'value' => set_value('duration') != "" ? set_value('duration') : $data['duration'],
            'class' => 'form-control',
            'placeholder' => 'Czas trwania'
        );
        return $form_data;
    }
    
    

    
    #######################################################################################
    #                                         AJAX
    #######################################################################################
    
    public function AjaxPobierzZadanie($taskId){
        $dane = $this->projects_tasks_model->get_task($taskId);
        if($dane){
            $zwroc = $dane;
        }
        else{
            $zwroc['error'] = 1;
        }
        echo json_encode($zwroc);
        
    }
    

}
