<?php 
defined('BASEPATH') or EXIT ('Ação não permitida');

class Home extends CI_Controller {
    
    public function __construct() {
        parent::__construct();

        $this->load->model('Author_model', 'author');
        $this->load->model('Email_model', 'email_model');
        $this->load->helper('string');

        // Get the user id through session
        $user_id = $this->session->user_id;

        // Valid session?
        if (!$this->ion_auth->in_group('author', $user_id)) {
            redirect('restricted/auth');
        }
    }

    public function index(){
        // Get the user id through session
        $user_id = $this->session->user_id;
        $data = array(
            'title'                         => 'Painel do autor',
            'styles'                =>  array(
                'css/custom.css',
            ),
            'scripts'               =>  array(
                'js/edit-chapter-status.js',
                'js/chapter_details.js',
                'js/delete-confirm.js'
            ),
            'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
            'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
            'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
            'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
            'all_chapters'                  => $this->author->count_chapters('chapters'),
            'chapters_waiting_review'       => $this->author->count_chapters('chapters', array('status' => 'waiting_review', 'author_id' => $user_id)),
            'chapters_in_review'            => $this->author->count_chapters('chapters', array('status' => 'in_review', 'author_id' => $user_id)),
            'chapters_approved'             => $this->author->count_chapters('chapters', array('status' => 'approved', 'author_id' => $user_id)),
            'chapters_recused'              => $this->author->count_chapters('chapters', array('status' => 'recused', 'author_id' => $user_id)),
            'chapters'                      => $this->core_model->get_all('chapters', array('author_id' => $user_id)),
        );
        $this->load->view('restricted/layout/header', $data);
        $this->load->view('restricted/author/index');
        $this->load->view('restricted/layout/footer');
    }

    public function get_book(){
        header('Content-Type: application/x-json; charset=utf-8');
        $book_id = $this->input->post('book_id');
        $response = $this->core_model->get_by_id('books', array('id' => $book_id));
        $response = $response->submission_rule;
        echo json_encode($response);
    }

    public function core($id = NULL){
        // Get the user id through session
        $user_id = $this->session->user_id;

        // Get users from group "admin" to send email for each one of them
        $admins  = $this->ion_auth->users('admin')->result();

        if(!$id){
            // If not exist add new chapter
            $id = (int) $id;

            // var_dump($admins); die();
            // This validation isn't working because of the multistep form. It's here to future modification
            $this->form_validation->set_rules('title', 'Título', 'trim|max_length[100]');
            $this->form_validation->set_rules('abstract', 'Resumo', 'trim');
            $this->form_validation->set_rules('document', 'Documento', 'trim');

            if($this->form_validation->run()){

                $co_authors = array(
                    'co_author_name'    => $this->input->post('co_author_name'),
                    'co_author_email'   => $this->input->post('co_author_email'),
                    'co_author_phone'   => $this->input->post('co_author_phone'),
                    'co_author_company' => $this->input->post('co_author_company'),
                );

                $data = array(
                    'unique_code'   => strtoupper(random_string('alnum', 8)),
                    'book_id'       => $this->input->post('book_id'),
                    'title'         => $this->input->post('title'),
                    'abstract'      => $this->input->post('abstract'),
                    'keywords'      => implode(',', $this->input->post('keywords')),
                    'status'        => 'waiting_review',
                    'author_id'     => $user_id,
                    'created_at'    => date('Y-m-d H:i:s'),
                    'modified_at'   => '',
                );

                // Start uplaod files
                $_FILES['document'];

                $uploadPath = './uploads/authors/' . $user_id;
                if(!is_dir($uploadPath)){
                    mkdir($uploadPath, 0751, TRUE);
                }
                $config = array(
                    'upload_path'       =>  $uploadPath,
                    'allowed_types'     =>  'jpg|jpeg|png|doc|docx|pdf|txt|xls|xlsx|csv',
                );
                $this->load->library('upload', $config);
                    
                if (!$this->upload->do_upload('document')) {
                    // Use this var to debug possible upload erros
                    $errors = $this->upload->display_errors();

                    $this->session->set_flashdata('error_message', 'Não foi possível enviar os arquivos. Verifique a extensão do arquivo e tente novamente.');
                    redirect('restricted/author/home/core');

                } else {
                    $file = $this->upload->data();
                    $file_name = $file['file_name'];
                    // Add file name to the key document in array data to insert in database
                    $data += ["document" => $file_name];

                    // Save data in database
                    if($this->author->send_chapter('chapters', $data) == TRUE){
                        $last_insert = $this->db->insert_id();
    
                        // Save co author in table co_authors
                        foreach($co_authors['co_author_name'] as $key=> $co_author){
                            $data_coauthor = array(
                                'co_author_name'        => $co_author,
                                'co_author_email'       => $co_authors['co_author_email'][$key],
                                'co_author_phone'       => $co_authors['co_author_phone'][$key],
                                'co_author_company'     => $co_authors['co_author_company'][$key],
                                'chapters_id'           => $last_insert,
                            );
                            if(!$this->db->insert('co_authors', $data_coauthor)){
                                unlink($uploadPath.'/'.$file_name);
                                $this->session->set_flashdata('error_message', 'Não foi possível enviar o capítulo. Tente novamente.');
                                redirect('restricted/author/home');
                            }
                        }

                        // Send email to adms
                        $email_params = array(
                            'chapter_title'        => $data['title'],
                            'chapter_code'         => $data['unique_code'],
                        );
                        foreach($admins as $admin){
                            $this->email_model->send_email('new_chapter_admin', $admin->id, $email_params);
                        }

                        $this->session->set_flashdata('upload_successful', 'Capítulo enviado com sucesso!');
                        redirect('restricted/author/home/');
                    } else {
                        unlink($uploadPath.'/'.$file_name);
                        $this->session->set_flashdata('error_message', 'Não foi possível enviar o capítulo. Tente novamente.');
                        redirect('restricted/author/home');
                    }



                }
                // End upload files
                
            } else {
                //Validation error
                $data = array(
                    'title' => "Enviar capítulo",
                    'groups' => $this->ion_auth->groups()->result(),
                    'styles' => array(
                        'css/step-by-step.css',
                        'css/tag-input.css',
                        'css/custom.css',
                    ),
                    'scripts' => array(
                        'js/step-by-step.js',
                        'js/tag-input.js',
                        'js/co-authors.js',
                        'js/show-abstract-form.js',
                        'js/check-form.js',
                        'js/initialize-ckeditor.js',
                        'js/block-enter.js'
                    ),
                    'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
                    'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
                    'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
                    'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
                    'books'                         => $this->core_model->get_all('books'),
                );
                $this->load->view('restricted/layout/header', $data);
                $this->load->view('restricted/author/core');
                $this->load->view('restricted/layout/footer');
            }

        // If exist edit chapter
        } else {
            // Check if the chapter exists
            if(!$chapter = $this->core_model->get_by_id('chapters', array('id' => $id))){
                $this->session->set_flashdata('error_message', 'Capítulo não encontrado.');
                redirect('restricted/author/home');            
            } else {

                // This validation isn't working because of the multistep form. It's here to future modification
                $this->form_validation->set_rules('title', 'Título', 'trim|max_length[100]');
                $this->form_validation->set_rules('abstract', 'Resumo', 'trim');
                $this->form_validation->set_rules('document', 'Documento', 'trim');
                
                if ($this->form_validation->run()) {
                    $co_authors = array(
                        'co_author_name'    => $this->input->post('co_author_name'),
                        'co_author_email'   => $this->input->post('co_author_email'),
                        'co_author_phone'   => $this->input->post('co_author_phone'),
                        'co_author_company' => $this->input->post('co_author_company'),
                    );

                    $data = array(
                        'book_id'       => $this->input->post('book_id'),
                        'title'         => $this->input->post('title'),
                        'abstract'      => $this->input->post('abstract'),
                        'status'        => 'waiting_review',
                        'author_id'     => $user_id,
                        'modified_at'   => date('Y-m-d H:i:s'),
                    );

                    if($this->input->post('keywords') != '' OR $this->input->post('keywords') != NULL){
                        $keywords = implode(',', $this->input->post('keywords'));
                    } else {
                        unset($keywords);
                    }

                    // Start uplaod files
                    $_FILES['document'];

                    $uploadPath = './uploads/authors/' . $user_id;
                    if(!is_dir($uploadPath)){
                        mkdir($uploadPath, 0751, TRUE);
                    }
                    $config = array(
                        'upload_path'       =>  $uploadPath,
                        'allowed_types'     =>  'jpg|jpeg|png|doc|docx|pdf|txt|xls|xlsx|csv',
                    );
                    $this->load->library('upload', $config);

                    if (!$this->upload->do_upload('document')) {
                        // Use this var to debug possible upload erros
                        $errors = $this->upload->display_errors();

                        $this->session->set_flashdata('error_message', 'Não foi possível enviar os arquivos. Verifique a extensão do arquivo e tente novamente.');
                        redirect('restricted/author/home/');

                    } else {
                        $file = $this->upload->data();
                        $file_name = $file['file_name'];
                        // Add file name to the key document in array data to insert in database
                        $data += ["document" => $file_name];

                        // Save data in database
                        if($this->author->update_chapter('chapters', $data, $keywords, array('id' => $chapter->id)) == TRUE){

                            // Save co author in table co_authors
                            foreach($co_authors['co_author_name'] as $key=> $co_author){
                                $data_coauthor = array(
                                    'co_author_name'        => $co_author,
                                    'co_author_email'       => $co_authors['co_author_email'][$key],
                                    'co_author_phone'       => $co_authors['co_author_phone'][$key],
                                    'co_author_company'     => $co_authors['co_author_company'][$key],
                                    'chapters_id'           => $id,
                                );
                                if(!$this->db->insert('co_authors', $data_coauthor)){
                                    unlink($uploadPath.'/'.$file_name);
                                    $this->session->set_flashdata('error_message', 'Não foi possível enviar o capítulo. Tente novamente.');
                                    redirect('restricted/author/home');
                                }
                            }

                            // Send email to adms and editor/revisors assigned to the current chapter   
                            $email_params = array(
                                'chapter_title'        => $chapter->title,
                                'chapter_code'         => $chapter->unique_code,
                            );
                            foreach($admins as $admin){
                                $this->email_model->send_email('resubmit_chapter_admin', $admin->id, $email_params);
                            }
                            if($chapter->author_id != '' OR $chapter->author_id != NULL){
                                $this->email_model->send_email('resubmit_chapter_author', $chapter->author_id, $email_params);
                            }
                            if($chapter->editor_id != '' OR $chapter->editor_id != NULL){
                                $this->email_model->send_email('resubmit_chapter_editor', $chapter->editor_id, $email_params);
                            }
                            if($chapter->reviewer_id != '' OR $chapter->reviewer_id != NULL){
                                $this->email_model->send_email('resubmit_chapter_reviewer', $chapter->reviewer_id, $email_params);
                            }

        
                            $this->session->set_flashdata('upload_successful', 'Capítulo editado com sucesso!');
                            redirect('restricted/author/home/');
                        } else {
                            unlink($uploadPath.'/'.$file_name);
                            $this->session->set_flashdata('error_message', 'Não foi possível enviar o capítulo. Tente novamente.');
                            redirect('restricted/author/home');
                        }

                    }
                    // End upload files

                } else {
                    
                    //Validation error
                    $data = array(
                        'title'         =>  "Editar capítulo",
                        'styles'        =>  array(
                            'css/step-by-step.css',
                            'css/tag-input.css',
                            'css/custom.css',
                        ),
                        'scripts'       =>  array(
                            'js/step-by-step.js',
                            'js/tag-input.js',
                            'js/co-authors.js',
                            'js/show-abstract-form.js',
                            'js/delete-confirm.js',
                            'js/initialize-ckeditor.js',
                            'js/block-enter.js',
                            'js/check-form.js',
                        ),
                        'chapter'                       => $chapter,
                        'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
                        'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
                        'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
                        'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
                        'co_authors'                    => $this->core_model->get_all('co_authors', array('chapters_id' => $id)),
                        'books'                         => $this->core_model->get_all('books'),
                    );
                    $this->load->view('restricted/layout/header', $data);
                    $this->load->view('restricted/author/core');
                    $this->load->view('restricted/layout/footer');
                }
            }
        }
    }

    public function delete_chapter($id = NULL){
        // Get the user id through session
        $user_id = $this->session->user_id;
        
        $data = $this->core_model->get_by_id('chapters', array('id' => $id, 'author_id' => $user_id));
        $document = json_decode($data->document);
        
        // IF exist any document uploaded, delete it
        if(isset($document)){
            foreach($document as $d){
                if(is_dir('./uploads/authors/'.$user_id)){
                    $file = ('./uploads/authors/'.$user_id.'/'. $d);
                    unlink($file);
                }
            }
            $this->core_model->delete('chapters', array('id' => $id, 'author_id' => $user_id));

            // IF NOT, Delete just the row in database
        } else {
            $this->core_model->delete('chapters', array('id' => $id, 'author_id' => $user_id));
        }

        redirect('restricted/author/home');
    }
    
    public function delete_co_author($id = NULL){
        if(isset($id)){
            $this->db->delete('co_authors', array('id' => $id));
        } else {
            $this->session->set_flashdata('error_message', 'Ops! Algo deu errado. Tente novamente!');
        }
    }
}
