<?php

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

/* * *****************Application.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Application
 * @description     : Manage application.
 * @author          : South Bangla IT Zone Team
 * @url             : http://hms.sbitzone.com
 * @support         : rabibd.it@gmail.com
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Application extends MY_Controller {

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->load->model('Application_Model', 'application', true);
    }

    /*****************Function index**********************************
     * @type            : Function
     * @function name   : index
     * @description     : Load "Application List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function index() {

        check_permission(VIEW);

        if ($_GET && $this->input->get('date')) {
            $leave_type_id = $this->input->get('leave_type_id');
            $leave_status = $this->input->get('leave_status');
            $date = $this->input->get('date');
            $exp = explode('-', $date);
            $form_date = date('Y-m-d', strtotime($exp[0]));
            $to_date = date('Y-m-d', strtotime($exp[1]));

            if ($this->session->userdata('role_id') == SUPER_ADMIN || $this->session->userdata('role_id') == ADMIN) {
                $user_id = $this->input->get('user_id');
            } else {
                $user_id = $this->session->userdata('user_id');
            }

            $approved_by = $this->input->get('approved_by');
            $keyword = trim($this->input->get('keyword'));

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('leave/application?leave_type_id=' . $leave_type_id . '&leave_status=' . $leave_status . '&date=' . $date . '&user_id=' . $user_id . '&approved_by=' . $approved_by . '&keyword=' . $keyword);
            if ($this->input->get('page')) {
                $sgm = (int) trim($this->input->get('page'));
                $offset = $config['per_page'] * ($sgm - 1);
            } else {
                $offset = 0;
            }

            $config['total_rows'] = $this->application->get_application_list($config['per_page'], $offset, $leave_type_id, $leave_status, $form_date, $to_date, $user_id, $approved_by, $keyword, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['applications'] = $this->application->get_application_list($config['per_page'], $offset, $leave_type_id, $leave_status, $form_date, $to_date, $user_id, $approved_by, $keyword, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));

            $this->data['leave_type_id'] = $leave_type_id;
            $this->data['leave_status'] = $leave_status;
            $this->data['date'] = $date;
            $this->data['user_id'] = $user_id;
            $this->data['approved_by'] = $approved_by;
            $this->data['keyword'] = $keyword;
        } else {
            $status =  $this->input->get('status') ?? null;
            if ($this->session->userdata('role_id') == SUPER_ADMIN || $this->session->userdata('role_id') == ADMIN) {
                $user_id = null;
            } else {
                $user_id = $this->session->userdata('user_id');
            }
            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            if ($status) {
                $config['base_url'] = site_url('leave/application?status=' . $status);
            } else {
                $config['base_url'] = current_url();
            }
            if ($this->input->get('page')) {
                $sgm = (int) trim($this->input->get('page'));
                $offset = $config['per_page'] * ($sgm - 1);
            } else {
                $offset = 0;
            }

            $config['total_rows'] = $this->application->get_application_list($config['per_page'], $offset, null, $status, null, null, $user_id, null, null, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['applications'] = $this->application->get_application_list($config['per_page'], $offset,  null, $status, null, null, $user_id, null, null, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
            $this->data['leave_status'] = $status;
        }

        $this->data['types'] = $this->application->get_list('leave_types', array('status' => 1));
        $this->data['employees'] = $this->application->get_employee_list();
        $this->data['approved_by'] = $this->application->get_approved_by_list();
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_leave') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('leave/index', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "Add new Application" user interface
     *                    and process to store "applications" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function add() {

        check_permission(ADD);

        if ($_POST) {
            $this->_prepare_application_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_application_data();
                $insert_id = $this->application->insert('leaves', $data);
                if ($insert_id) {
                    $user = $this->application->get_single('employees', array('user_id', $data['user_id']));
                    create_log('Has been created a leave application : ' . $insert_id);
                    success($this->lang->line('insert_success'));
                    redirect('leave/application');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('leave/application/add');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['types'] = $this->application->get_list('leave_types', array('status' => 1));
        $this->data['employees'] = $this->application->get_employee_list();
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->global_setting->brand_title);
        $this->layout->view('leave/add', $this->data);
    }

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load Update "Application" user interface
     *                    with populate "Application" value
     *                    and process to update "applications" into database
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function edit($id = null) {

        check_permission(EDIT);

        if ($_POST) {
            $this->_prepare_application_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_application_data();
                $updated = $this->application->update('leaves', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    $user = $this->application->get_single('employees', array('user_id', $data['user_id']));
                    create_log('Has been updated a leave application : ' . $updated);
                    success($this->lang->line('update_success'));
                    redirect('leave/application');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('leave/application/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['application'] = $this->application->get_single('leaves', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['application'] = $this->application->get_single('leaves', array('id' => $id));
                if (!$this->data['application']) {
                    redirect('leave/application');
                }
            }
        }
        $this->data['types'] = $this->application->get_list('leave_types', array('status' => 1));
        $this->data['employees'] = $this->application->get_employee_list();
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->global_setting->brand_title);
        $this->layout->view('leave/edit', $this->data);
    }

    /*     * ***************Function view**********************************
     * @type            : Function
     * @function name   : view
     * @description     : "Load single application information" from database                  
     *                    to the user interface   
     * @param           : null
     * @return          : null 
     * ********************************************************** */

    public function view($id) {

        check_permission(VIEW);

        $this->data['application'] = $this->application->get_single_application($id);
        $this->data['view'] = TRUE;
        $this->layout->title($this->lang->line('view') . ' ' . $this->global_setting->brand_title);
        $this->layout->view('leave/view', $this->data);
    }

    /*****************Function _prepare_application_validation**********************************
     * @type            : Function
     * @function name   : _prepare_application_validation
     * @description     : Process "Application" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_application_validation() {
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
        $this->form_validation->set_rules('leave_type_id', $this->lang->line('leave') . ' ' . $this->lang->line('type'), 'trim|required');
        $this->form_validation->set_rules('user_id', $this->lang->line('employee'), 'trim');
        $this->form_validation->set_rules('leave_from', $this->lang->line('leave') . ' ' . $this->lang->line('from'), 'trim|required');
        $this->form_validation->set_rules('leave_to', $this->lang->line('leave') . ' ' . $this->lang->line('to'), 'trim|required');
        $this->form_validation->set_rules('leave_status', $this->lang->line('leave') . ' ' . $this->lang->line('status'), 'trim');
    }

    /*****************Function _get_posted_application_data**********************************
     * @type            : Function
     * @function name   : _get_posted_application_data
     * @description     : Prepare "Application" user input data to save into database
     *
     * @param           : null
     * @return          : $data array(); value
     * ********************************************************** */
    private function _get_posted_application_data() {

        $items = array();
        $items[] = 'user_id';
        $items[] = 'leave_type_id';
        $items[] = 'reason';
        $data = elements($items, $_POST);

        $data['leave_from'] = $this->input->post('leave_from') ? date('Y-m-d', strtotime($this->input->post('leave_from'))) : date('Y-m-d');
        $data['leave_to'] = $this->input->post('leave_to') ? date('Y-m-d', strtotime($this->input->post('leave_to'))) : date('Y-m-d');
        $data['leave_status'] = $this->input->post('leave_status') ?? 'waiting';
        $data['remark'] = $this->input->post('remark') ?? null;
        $leave_from = new DateTime($data['leave_from']);
        $leave_to = new DateTime($data['leave_to']);
        $diff = $leave_from->diff($leave_to);
        $data['total_leave_day'] = $diff->d == 0 ? 1 : $diff->d + 1;

        if ($this->input->post('id')) {
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = logged_in_user_id();
        } else {
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();
        }

        if ($_FILES['attachment']['name']) {
            $data['attachment'] = $this->_upload_attachment();
        }

        return $data;
    }

    /*     * ***************Function _upload_attachment**********************************
     * @type            : Function
     * @function name   : _upload_attachment
     * @description     : Process to upload application attachment into server
     *                     and return attachment file name
     * @param           : null
     * @return          : $return_attachment string value
     * ********************************************************** */

    private function _upload_attachment() {

        $prev_attachment = $this->input->post('prev_attachment');
        $attachment = $_FILES['attachment']['name'];
        $attachment_type = $_FILES['attachment']['type'];
        $return_attachment = '';

        if ($attachment != "") {
            if (
                $attachment_type == 'image/jpeg' || $attachment_type == 'image/pjpeg' ||
                $attachment_type == 'image/jpg' || $attachment_type == 'image/png' ||
                $attachment_type == 'image/x-png' || $attachment_type == 'image/gif' ||
                $attachment_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                $attachment_type == 'application/msword' || $attachment_type == 'text/plain' ||
                $attachment_type == 'application/vnd.ms-office' || $attachment_type == 'application/pdf'
            ) {

                $destination = 'assets/uploads/attachment/';

                $file_type = explode(".", $attachment);
                $extension = strtolower($file_type[count($file_type) - 1]);
                $attachment_path = 'leave-attachment-' . time() . '-sbiz.' . $extension;

                move_uploaded_file($_FILES['attachment']['tmp_name'], $destination . $attachment_path);

                // need to unlink previous attachment
                if ($prev_attachment != "") {
                    if (file_exists($destination . $prev_attachment)) {
                        @unlink($destination . $prev_attachment);
                    }
                }

                $return_attachment = $attachment_path;
            }
        } else {
            $return_attachment = $prev_attachment;
        }

        return $return_attachment;
    }

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Application" data from database
     *
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function delete($id = null) {

        check_permission(DELETE);

        if (!is_numeric($id)) {
            error($this->lang->line('unexpected_error'));
            redirect('leave/application');
        }

        $application = $this->application->get_single('leaves', array('id' => $id));
        if (isset($application) && $id > 0) {
            $this->db->trans_start();
            create_log('Has been deleted a leave application user id : ' . $application->user_id);
            // delete attachment
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/leave-attachment/' . $application->attachment)) {
                @unlink($destination . '/leave-attachment/' . $application->attachment);
            }

            $this->application->delete('leaves', array('id' => $id));
            $this->db->trans_complete();
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
}
