<?php

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

class Certificate extends TT_user_login {

    public function __construct() {
        parent::__construct();
        $this->load->model('certificate_model');
    }

    /**
     * @Function            : view_certificate_by_student_roll
     * @Description         : Display Certificate
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 02-03-17     
     * @Status              : available      
     * */
    public function view_certificate_by_student_roll($student_roll) {
        if (!isset($this->session->person_id)) {
            redirect();
        }
        $this->load->model('certificate_model');
        $data = $this->welcome_model->generate_menu();
        $data['right_content_variation'] = 0;
        $data['certificate_data'] = $this->get_certificate_detail($student_roll);
        if (!isset($data['certificate_data']) || empty($data['certificate_data'])) {
            redirect();
        }
        $data['main_content'] = $this->load->view('user/view_certificate', $data, TRUE);
        $this->load->view('user/master', $data);
    }

    /**
     * @Function            : get_certificate_detail
     * @Description         : get detail information of a single certificate
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 02-03-17  
     *  @parameter           : $student_roll
     * @Status              : available      
     * */
    public function get_certificate_detail($student_roll) {
        $data = $this->certificate_model->certificate_info_for_public_view($student_roll);
        $data->student_name = $this->certificate_model->get_student_name_by_id($data->person_id);
        return $data;
    }

    /**
     * @Function            : print_certificate
     * @Description         : Print the course certificate in pdf
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 03-04-17  
     * @parameter           : $student_roll
     * @Status              : available      
     * */
    public function print_certificate($student_roll) {
        $this->load->model('certificate_model');
        $data['certificate_data'] = $this->get_certificate_detail($student_roll);
        if (!isset($data['certificate_data']) || empty($data['certificate_data'])) {
            redirect();
        }
        $html = $this->load->view('user/certificate_pdf.php', $data, TRUE);
        $this->load->library('tt_pdf_printer');
        // Please do not change anything without undestanding clearly
        $this->tt_pdf_printer->pdf->AddPage('L', '', '', '', '', 0, 0, 0, 0, 0, 0, '', '', '', '', '', '', '', '', '', array(150, 220));
        $this->tt_pdf_printer->pdf->WriteHTML($html);
        $this->tt_pdf_printer->pdf->Output("$student_roll.pdf", "I");
    }

    /*
     * @Function            : assign_batch_student_certificate 
     * @Description         : Assigns Certificate to batch student on ajax call
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 05-03-17
     * @Parameter           : NULL
     * @Status              : Available       
     */

    public function assign_batch_student_certificate() {
        if ($this->input->is_ajax_request()) {
            $student_roll = $this->input->post('student_roll', TRUE);
            $course_batch_id = $this->input->post('course_batch_id', TRUE);
            $this->check_certificate_existance($student_roll, $course_batch_id);
        } else {
            redirect();
        }
    }

    /*
     * @Function            : check_certificate_existance 
     * @Description         : Check certificate already exit or not
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 05-03-17
     * @Parameter           : $student_roll, $course_batch_id
     * @Status              : Available       
     */

    public function check_certificate_existance($student_roll, $course_batch_id) {
        $certificate_data = $this->certificate_model->check_certificate_existance($student_roll, $course_batch_id);
        if (!isset($certificate_data)) {
            $this->assign_student_certificate($student_roll, $course_batch_id);
        }
    }

    /*
     * @Function            : assign_student_certificate 
     * @Description         : Assign Certificate to student
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 05-03-17
     * @Parameter           : $student_roll, $course_batch_id
     * @Status              : Available       
     */

    public function assign_student_certificate($student_roll, $course_batch_id) {
        $certificate_dtl = $this->certificate_model->get_certificate_dtl_by_batch_id($course_batch_id);
        if (isset($certificate_dtl)) {
            $unset_array = ['student_certificate_id', 'person_id', 'student_roll_number'];
            foreach ($unset_array as $unset_value) {
                unset($certificate_dtl->$unset_value);
            }
            $certificate_dtl->person_id = $this->certificate_model->get_person_id_by_roll($student_roll);
            $certificate_dtl->student_roll_number = $student_roll;
            $this->certificate_model->save_certificate($certificate_dtl);
        } else {
            $data = $this->prepare_certificate_detail($student_roll, $course_batch_id);
            $this->certificate_model->save_certificate($data);
        }
    }

    /*
     * @Function            : prepare_certificate_detail 
     * @Used In             : assign_batch_student_certificate
     * @Description         : organize all certificate data
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 05-03-17
     * @Parameter           : $student_roll
     * @Status              : Available       
     */

    public function prepare_certificate_detail($student_roll, $course_batch_id) {
        $data['person_id'] = $this->certificate_model->get_person_id_by_roll($student_roll);
        $data['course_batch_id'] = $course_batch_id;
        $data['certificate_logo'] = $this->get_permanent_certificate_logo($course_batch_id);
        $data['course_by'] = $this->certificate_model->get_course_by_name($course_batch_id);
        $course_info = $this->certificate_model->get_certificate_course_info_by_batch_id($course_batch_id);
        $data['course_name'] = $course_info->course_name;
        $data['course_completion_date'] = $course_info->course_completion_date;
        $data['course_resource_person'] = $this->certificate_model->get_resource_person_name($course_info->resource_person_id);
        $data['student_roll_number'] = $student_roll;
        $data['certificate_template'] = $this->certificate_model->get_certificate_template($course_batch_id);
        return $data;
    }

    /*
     * @Function            : get_permanent_certificate_logo
     * @Description         : Copy and transfer certificate logo in permanent folder
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 05-03-17
     * @Parameter           : $course_batch_id        
     * @Status              : Available       
     */

    public function get_permanent_certificate_logo($course_batch_id) {
        $logo_file = 'content-library/certificate-logo/' . md5($course_batch_id) . '.jpg';
        if (!file_exists($logo_file)) {
            $certificate_logo = $this->certificate_model->get_current_logo($course_batch_id);

            if (!is_dir('content-library/certificate-logo/')) {
                mkdir('content-library/certificate-logo/', 0777, true);
            }

            if (!copy($certificate_logo->certificate_image, $logo_file)) {
                echo 'Error Happend While Assigning Certificate !';
                exit();
            } else {
                return $logo_file;
            }
        } else {
            return $logo_file;
        }
    }

    /*
     * @Function            : cancel_batch_student_certificate 
     * @Description         : Update certificate status to cancel
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 05-03-17
     * @Parameter           : Null
     * @Status              : Available       
     */

    public function cancel_batch_student_certificate() {
        if ($this->input->is_ajax_request()) {
            $student_roll = $this->input->post('student_roll', TRUE);
            $course_batch_id = $this->input->post('course_batch_id', TRUE);
            $this->certificate_model->cancel_batch_student_certificate($student_roll, $course_batch_id);
        } else {
            redirect();
        }
    }

    /*
     * @Function            : save_course_certificate 
     * @Description         : validates data for creating course certificate
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : NULL         
     * @Status              : Available       
     */

    public function save_course_certificate() {
        $this->form_validation->set_rules('certificate_name', 'Certificate Name', 'required|trim|max_length[50]');
        $this->form_validation->set_rules('certificate_template', 'Certificate Template', 'required');
        $this->form_validation->set_rules('certificate_logo', 'Certificate Logo', 'callback_image_check');
        $this->form_validation->set_rules('certificate_status', 'Certificate Status', 'required');
        if ($this->form_validation->run() == FALSE) {
            $this->course_create_certificate($this->session->certificate_course_url);
        } else {
            $this->certificate_model->save_certificate_model();
            $course_url = $this->session->certificate_course_url;
            $unset_items = array('uploaded_certificate_logo',
                'certificate_assign_to_type',
                'certificate_assign_to_type_id',
                'certificate_course_url');
            $this->session->unset_userdata($unset_items);
            redirect($course_url . '/demo-certificate');
        }
    }

    /*
     * @Function            : course_create_certificate 
     * @Description         : displays the create certificate view page
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : NULL         
     * @Status              : Available       
     */

    public function course_create_certificate($course_url) {
        // get the course information
        $data['course_info'] = $this->certificate_model->get_course_info_by_url($course_url);
        $certificate_info = $this->certificate_model->check_certificate(1, $data['course_info']->course_id);
        if (isset($certificate_info)) {
            redirect($course_url . '/demo-certificate');
            exit();
        }
        $this->session->set_userdata('certificate_course_url', $course_url);
        $this->session->set_userdata('certificate_assign_to_type', 1);
        $this->session->set_userdata('certificate_assign_to_type_id', $data['course_info']->course_id);
        if ($this->session->person_role == 4) {
            $data = $this->user_course_model->side_menu_info($data, 'organization', 'organization_course');
        } elseif ($this->session->person_role == 3) {
            $data = $this->user_course_model->side_menu_info($data, 'teacher', 'teacher_course');
        }

        $data['certificate_type'] = 'Course:';
        $data['main_content'] = $this->load->view('user/course/course_create_certificate', $data, TRUE);
        $this->load->view('user/master', $data);
    }

    /*
     * @Function            : image_check 
     * @Description         : call back function for validating image in save_certificate
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : NULL         
     * @Status              : Available       
     */

    public function image_check() {        
        if(isset($_FILES['certificate_logo']) && is_uploaded_file($_FILES['certificate_logo']['tmp_name'])){
            $this->remove_temporary_logo();
            $this->upload_certificate_image();
        }elseif(isset($this->session->uploaded_certificate_logo)){
            return TRUE;
        }else{
            return FALSE;
        }
    }

    /*
     * @Function            : upload_certificate_image 
     * @Description         : Uploads the certificate logo image
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 08-05-17
     * @Parameter           : NULL         
     * @Status              : Available       
     */
    public function upload_certificate_image() {
        $person_url = $this->session->person_url;
        //checks and creates image upload directory
        $upload_path = 'content-library/' . $person_url . '/my-image/' . 'certificate-logo' . '/';
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
        }
        $this->tt_files->set_file('certificate_logo')->set_upload_dir($upload_path)
                ->set_encrypt_name()
                ->set_file_size(2048000)
                ->set_allowed_type(['png', 'jpeg', 'jpg'])
                ->check_validation()->upload_file();

        if (!empty($this->tt_files->error_message())) {
            $this->form_validation->set_message('image_check', $this->tt_files->error_message());
            return FALSE;
        } else {
            $file_data = $this->tt_files->get_uploaded_file_data();
            // Create thumb image
            $image_path = $upload_path . $file_data['file_name'];
            $thumbnail_image_path = $upload_path . 'thumb_' . $file_data['file_name'];
            $this->image_model->create_thumbnail_image($thumbnail_image_path, $image_path);
            //Save the thumb image path in session
            $this->session->set_userdata('uploaded_certificate_logo', $thumbnail_image_path);
            //delete old image
            unlink($image_path);
            return TRUE;
        }
    }

    /*
     * @Function            : remove_temporary_logo
     * @Used In             : @function removePreviousLogo [admin_certificate.js] 
     * @Description         : removes previous logo when logo changed while 
     *                        creating form
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : NULL         
     * @Status              : Available       
     */

    public function remove_temporary_logo() {
        $previous_logo = $this->session->uploaded_certificate_logo;
        if (isset($previous_logo) && file_exists($previous_logo)) {
            unlink($previous_logo);
            $this->session->unset_userdata('uploaded_certificate_logo');
        }
    }

    /*
     * @Function            : view_demo_course_certificate 
     * @Description         : displays demo certificate based on certificate id
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : $course_url         
     * @Status              : Available       
     */

    public function view_demo_course_certificate($course_url) {
        $course_info = $this->certificate_model->get_course_info_by_url($course_url);
        $certificate_info = $this->certificate_model->check_certificate(1, $course_info->course_id);
        $resource_person_info = $this->certificate_model->get_resource_person_info($course_info->resource_person_id);
        //organiztion info   
        if ($resource_person_info->resource_person_type === '1') {
            $data['organization_name'] = 'Talha Training';
        } elseif ($resource_person_info->resource_person_type === '3') {
            $company_info = $this->certificate_model->get_organization_name($course_info->person_id);
            isset($company_info) ? $data['organization_name'] = $company_info : $data['organization_name'] = '';
        } elseif ($resource_person_info->resource_person_type === '2') {
            $data['organization_name'] = '';
        }
        $data['course_url'] = $course_url;
        if(isset($certificate_info)){
            $data['certificate_logo'] = $certificate_info->certificate_image;
        }
        //$data['certificate_logo'] = $certificate_info->certificate_image;
        $data['course_name'] = $course_info->course_name;
        $data['resource_person'] = $resource_person_info->person_first_name . ' ' . $resource_person_info->person_last_name;
        if ($this->session->person_role == 4) {
            $data = $this->user_course_model->side_menu_info($data, 'organization', 'organization_course');
        } elseif ($this->session->person_role == 3) {
            $data = $this->user_course_model->side_menu_info($data, 'teacher', 'teacher_course');
        }
        $data['certificate_type'] = 'Course:';
        $data['main_content'] = $this->load->view('user/course/course_demo_certificate', $data, TRUE);
        $this->load->view('user/master', $data);
    }

    /*
     * @Function            : edit_course_certificate 
     * @Description         : displays form for editing certificate
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : $course_url         
     * @Status              : Available       
     */

    public function edit_course_certificate($course_url) {
        $data['course_info'] = $this->certificate_model->get_course_info_by_url($course_url);
        $data['certificate_info'] = $this->certificate_model->check_certificate(1, $data['course_info']->course_id);
        if(isset($data['certificate_info']->certificate_image)){
        $this->session->set_userdata('uploaded_certificate_logo', $data['certificate_info']->certificate_image);}
        $this->session->set_userdata('certificate_course_url', $course_url);
        if(isset($data['certificate_info']->certificate_id)){
        $this->session->set_userdata('certificate_id', $data['certificate_info']->certificate_id);}
        $this->session->set_userdata('certificate_assign_to_type', 1);
        $this->session->set_userdata('certificate_assign_to_type_id', $data['course_info']->course_id);
        if ($this->session->person_role == 4) {
            $data = $this->user_course_model->side_menu_info($data, 'organization', 'organization_course');
        } elseif ($this->session->person_role == 3) {
            $data = $this->user_course_model->side_menu_info($data, 'teacher', 'teacher_course');
        }
        $data['certificate_type'] = 'Course:';
        $data['main_content'] = $this->load->view('user/course/course_edit_certificate', $data, TRUE);
        $this->load->view('user/master', $data);
    }

    /*
     * @Function            : update_course_certificate 
     * @Description         : Updates the course certificate
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 07-03-17
     * @Parameter           : Null         
     * @Status              : Available       
     */

    public function update_course_certificate() {
        $this->form_validation->set_rules('certificate_name', 'Certificate Name', 'required|trim|max_length[50]');
        $this->form_validation->set_rules('certificate_template', 'Certificate Template', 'required');
        $this->form_validation->set_rules('certificate_logo', 'Certificate Logo', 'callback_image_check');
        $this->form_validation->set_rules('certificate_status', 'Certificate Status', 'required');
        if ($this->form_validation->run() == FALSE) {
            $this->edit_course_certificate($this->session->certificate_course_url);
        } else {
            $this->certificate_model->update_certificate_model();
            $course_url = $this->session->certificate_course_url;
            $unset_items = array('uploaded_certificate_logo',
                'certificate_assign_to_type',
                'certificate_assign_to_type_id',
                'certificate_course_url',
                'certificate_id');
            $this->session->unset_userdata($unset_items);
            redirect($course_url . '/demo-certificate');
        }
    }

}
