<?php

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

/* * *****************Expenditure.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Expenditure
 * @description     : Manage all kind of expenditure of the system.  
 * @author          : South Bangla IT Zone Team 	
 * @url             : https://hms.sbitzone.com/      
 * @support         : rabibd.it@gmail.com	
 * @copyright       : South Bangla IT Zone Team
 * ********************************************************** */

class Expenditure extends MY_Controller
{

    public $data = array();

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

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

        check_permission(VIEW);

        if ($_GET) {
            $keyword = trim($this->input->get('keyword'));
            $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]));
            $expenditure_head_id = $this->input->get('expenditure_head_id');
            $type = $this->input->get('type');
            $payment_method = $this->input->get('payment_method');
            $created_by = $this->input->get('created_by');

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('accounting/expenditure/?search=' . $keyword . '&date=' . $date . '&expenditure_head_id=' . $expenditure_head_id . '&type=' . $type . '&payment_method=' . $payment_method . '&created_by=' . $created_by);
            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->expenditure->get_expenditure_list($config['per_page'], $offset, $keyword, $form_date, $to_date, $expenditure_head_id, $type, $payment_method, $created_by, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['expenditures'] = $this->expenditure->get_expenditure_list($config['per_page'], $offset, $keyword, $form_date, $to_date, $expenditure_head_id, $type, $payment_method, $created_by, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));

            $this->data['keyword'] = $keyword;
            $this->data['date'] = $date;
            $this->data['expenditure_head_id'] = $expenditure_head_id;
            $this->data['type'] = $type;
            $this->data['payment_method'] = $payment_method;
            $this->data['created_by'] = $created_by;
        } else {
            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $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->expenditure->get_expenditure_list($config['per_page'], $offset, null, date('Y-m-d'), date('Y-m-d'), null, null, null, null, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['expenditures'] = $this->expenditure->get_expenditure_list($config['per_page'], $offset, null, date('Y-m-d'), date('Y-m-d'), null, null, 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['expheads'] = $this->expenditure->get_list('expenditure_heads', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['employees'] = $this->expenditure->get_employee_list();

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

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

        check_permission(ADD);

        if ($_POST) {

            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('expenditure_head_id', $this->lang->line('expenditure_head'), 'trim|required');
            $this->form_validation->set_rules('name', $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('payment_method', $this->lang->line('payment') . ' ' . $this->lang->line('method'), 'trim|required');
            $this->form_validation->set_rules('amount', $this->lang->line('amount'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['custom_invoice_id'] = get_custom_invoice('expenditures', 'INV-', date('Y'), date('m'));
                $data['expenditure_head_id'] = $this->input->post('expenditure_head_id');
                $data['name'] = $this->input->post('name');
                $data['reference'] = $this->input->post('reference');
                $data['invoice_no'] = $this->input->post('invoice_no');
                $data['type'] = 'other';
                $data['payment_method'] = $this->input->post('payment_method');
                $data['bank_name'] = $this->input->post('bank_name');
                $data['cheque_no'] = $this->input->post('cheque_no');
                $data['amount'] = $this->input->post('amount');
                $data['date'] = date('Y-m-d H:i:s', strtotime($this->input->post('date')));
                $data['note'] = $this->input->post('note');
                $data['status'] = $this->input->post('status') ? $this->input->post('status') : 0;
                $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();
                }

                $insert_id = $this->expenditure->insert('expenditures', $data);
                if ($insert_id) {
                    create_log('Has been created a expenditure : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('accounting/expenditure');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('accounting/expenditure/add');
                }
            } else {
                $this->data = $_POST;
            }
        }

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

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load "Edit new expenditure" user interface
     *                    and process to store "expenditures" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function edit($id = NULL)
    {

        check_permission(EDIT);

        if ($_POST) {

            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('expenditure_head_id', $this->lang->line('expenditure_head'), 'trim|required');
            $this->form_validation->set_rules('name', $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('payment_method', $this->lang->line('payment') . ' ' . $this->lang->line('method'), 'trim|required');
            $this->form_validation->set_rules('amount', $this->lang->line('amount'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['expenditure_head_id'] = $this->input->post('expenditure_head_id');
                $data['name'] = $this->input->post('name');
                $data['reference'] = $this->input->post('reference');
                $data['invoice_no'] = $this->input->post('invoice_no');
                $data['type'] = 'other';
                $data['payment_method'] = $this->input->post('payment_method');
                $data['bank_name'] = $this->input->post('bank_name');
                $data['cheque_no'] = $this->input->post('cheque_no');
                $data['amount'] = $this->input->post('amount');
                $data['date'] = date('Y-m-d H:i:s', strtotime($this->input->post('date')));
                $data['note'] = $this->input->post('note');
                $data['status'] = $this->input->post('status') ? $this->input->post('status') : 0;
                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();

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

                $updated = $this->expenditure->update('expenditures', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    create_log('Has been updated a expenditure : ' . $data['name']);
                    success($this->lang->line('update_success'));
                    redirect('accounting/expenditure');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('accounting/expenditure/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['expenditure'] = $this->expenditure->get_single('expenditures', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['expenditure'] = $this->expenditure->get_single('expenditures', array('id' => $id));
                if (!$this->data['expenditure']) {
                    redirect('accounting/expenditure');
                }
            }
        }
        $this->data['expheads'] = $this->expenditure->get_list('expenditure_heads', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['edit'] = TRUE;
        $this->layout->title($this->lang->line('edit') . ' ' . $this->lang->line('expenditure') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('accounting/expenditure/edit', $this->data);
    }


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

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

    /*****************Function name**********************************
     * @type            : Function
     * @function name   : name
     * @description     : Unique check for "Expenditure Head Name" data/value
     *
     * @param           : null
     * @return          : boolean true/false
     * ********************************************************** */
    public function name()
    {
        if ($this->input->post('id') == '') {
            $name = $this->expenditure->duplicate_check($this->input->post('name'));
            if ($name) {
                $this->form_validation->set_message('name', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else if ($this->input->post('id') != '') {
            $name = $this->expenditure->duplicate_check($this->input->post('name'), $this->input->post('id'));
            if ($name) {
                $this->form_validation->set_message('name', $this->lang->line('already_exist'));
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            return TRUE;
        }
    }

    /*     * ***************Function _upload_attachment**********************************
     * @type            : Function
     * @function name   : _upload_attachment
     * @description     : Process to upload expenditure 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 = 'exp-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 "expenditures" 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('accounting/expenditure');
        }

        $expenditure = $this->expenditure->get_single('expenditures', array('id' => $id));

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