<?php

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

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

class Complaint extends MY_Controller {

    public $data = array();

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

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

        check_permission(VIEW);

        $search = $this->input->get('search');
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        if ($search) {
            $config['base_url'] = site_url('frontoffice/complaint/?search=') . $search;
        } 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->complaint->get_complaint_list($config['per_page'], $offset, $search, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['complaints'] = $this->complaint->get_complaint_list($config['per_page'], $offset, $search, $count = FALSE);

        $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        $this->data['search'] = $search;

        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('complaint') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('complaint/index', $this->data);
    }

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

        check_permission(ADD);
        if ($_POST) {
            $this->_prepare_complaint_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_complaint_data();
                $insert_id = $this->complaint->insert('complaints', $data);
                if ($insert_id) {
                    create_log('Has been created a Complaint : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('frontoffice/complaint');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('frontoffice/complaint/add');
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['complaint_types'] = $this->complaint->get_list('complaint_types', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['sources'] = $this->complaint->get_list('sources', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['add'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('complaint') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('complaint/add', $this->data);
    }

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

        check_permission(EDIT);
        if ($_POST) {
            $this->_prepare_complaint_validation();
            if ($this->form_validation->run() === TRUE) {
                $data = $this->_get_posted_complaint_data();
                $updated = $this->complaint->update('complaints', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a Complaint : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('frontoffice/complaint');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('frontoffice/complaint/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['complaint'] = $this->complaint->get_single('complaints', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['complaint'] = $this->complaint->get_single('complaints', array('id' => $id));
                if (!$this->data['complaint']) {
                    redirect('frontoffice/complaint');
                }
            }
        }
        $this->data['complaint_types'] = $this->complaint->get_list('complaint_types', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['sources'] = $this->complaint->get_list('sources', array('status' => 1), '', '', '', 'sort_by', 'ASC');

        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('complaint') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('complaint/edit', $this->data);
    }


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

    public function get_single_complaint() {
        $id = $this->input->post('id');
        $this->data['complaint'] = $this->complaint->get_single_complaint($id);
        echo $this->load->view('complaint/view', $this->data);
    }

    /*****************Function _prepare_complaint_validation**********************************
     * @type            : Function
     * @function name   : _prepare_complaint_validation
     * @description     : Process "Complaint" user input data validation
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    private function _prepare_complaint_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('complaint_type_id', $this->lang->line('complaint') . ' ' . $this->lang->line('type'), 'trim|required');
        $this->form_validation->set_rules('source_id', $this->lang->line('source'), 'trim|required');
        $this->form_validation->set_rules('name', $this->lang->line('name'), 'trim|required');
        $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required');
        $this->form_validation->set_rules('complaint_date', $this->lang->line('date'), 'trim|required');
    }

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

        $items = array();
        $items[] = 'complaint_type_id';
        $items[] = 'source_id';
        $items[] = 'name';
        $items[] = 'phone';
        $items[] = 'email';
        $items[] = 'assigned';
        $items[] = 'description';
        $items[] = 'action_note';
        $items[] = 'note';
        $data = elements($items, $_POST);

        $data['complaint_date'] = $this->input->post('complaint_date') ? date('Y-m-d', strtotime($this->input->post('complaint_date'))) : date('Y-m-d');
        $data['action_date'] = $this->input->post('action_date') ? date('Y-m-d', strtotime($this->input->post('action_date'))) : date('Y-m-d');

        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 complaint 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 == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                $attachment_type == 'application/msword' || $attachment_type == 'text/plain' ||
                $attachment_type == 'application/vnd.ms-office' || $attachment_type == 'application/pdf' ||
                $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'
            ) {

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

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

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

                // need to unlink previous photo
                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 "Complaint" 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('frontoffice/complaint');
        }

        $complaint = $this->complaint->get_single('complaints', array('id' => $id));

        if ($this->complaint->delete('complaints', array('id' => $id))) {
            // delete attachment
            $destination = 'assets/uploads/';
            if (file_exists($destination . '/attachment/' . $complaint->attachment)) {
                @unlink($destination . '/attachment/' . $complaint->attachment);
            }
            create_log('Has been deleted a Complaint : ' . $complaint->name);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect('frontoffice/complaint');
    }
}
