<?php

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

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

class Ipd extends MY_Controller
{

    public $data = array();
    public $patient_data = array();
    public $advance_data = array();
    public $details_data = array();
    public $paymentdata = array();

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

    public function set_barcode($code)
    {
        // Load library
        $this->load->library('zend');
        // Load in folder Zend
        $this->zend->load('Zend/Barcode');
        // Generate barcode
        Zend_Barcode::render('code128', 'image', array('text' => $code, 'drawText' => false), array());
    }

    public function index()
    {

        check_permission(VIEW);

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

    /*****************Function admitted**********************************
     * @type            : Function
     * @function name   : admitted
     * @description     : Load "IPD Admitted Patient List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function admitted()
    {

        check_permission(VIEW);

        $search = trim($this->input->get('search'));
        $config = array();
        $config = get_pagination(ADMIN_PER_PAGE);
        $config['base_url'] = site_url('ipd/admitted/?search=' . $search);
        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->ipd->get_admitted_list($config['per_page'], $offset, $search, $count = TRUE);
        $this->pagination->initialize($config);
        $this->data['patients'] = $this->ipd->get_admitted_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('admitted') . ' ' . $this->lang->line('patient') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('ipd/admitted', $this->data);
    }

    /*****************Function new**********************************
     * @type            : Function
     * @function name   : new
     * @description     : Load "Add New IPD Patient" user interface
     *                    and process to store "ipd_patients" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function new()
    {

        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('name', $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('gender', $this->lang->line('gender'), 'trim|required');
            $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required|callback_phone');
            $this->form_validation->set_rules('bed_group_id', $this->lang->line('admitted') . ' ' . $this->lang->line('ward'), 'trim|required');
            $this->form_validation->set_rules('bed_id', $this->lang->line('bed') . ' ' . $this->lang->line('number'), 'trim|required');

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

                $patient['name'] = $this->input->post('name');
                $patient['gender'] = $this->input->post('gender');
                $patient['phone'] = $this->input->post('phone');
                $patient['guardian_name'] = $this->input->post('guardian_name');
                $patient['address'] = $this->input->post('address');

                // Age Calculation
                $age = abs((int) $this->input->post('age'));
                $month = abs((int) $this->input->post('month'));
                $day = abs((int) $this->input->post('day'));

                $str = date('Y-m-d');
                if ($age > 0) {
                    $str = $str . ' -' . $age . ' years';
                }
                if ($month > 0) {
                    $str = $str . ' -' . $month . ' months';
                }
                if ($day > 0) {
                    $str = $str . ' -' . ($day + 1) . ' days';
                }
                $dob = date("Y-m-d", strtotime($str));
                $patient['dob'] = date('Y-m-d', strtotime($dob));
                $patient['age'] = floor((time() - strtotime($patient['dob'])) / 31556926);
                // End Age Calculation

                // create patient_unique_id
                $patient['patient_unique_id'] = $this->ipd->get_custom_id('patients', '1');
                // create user
                $patient['user_id'] = $this->ipd->create_user();
                // create patient
                $this->ipd->insert('patients', $patient);

                // IPD Data
                $data['ipd_no'] = $this->ipd->get_custom_id('ipd_patients', 'IPD');
                $data['registration_no'] = $this->ipd->get_custom_id('ipd_patients', 'R-');
                $data['patient_id'] = $patient['user_id'];
                $data['doctor_id'] = $this->input->post('doctor_id');
                $data['reference_id'] = $this->input->post('reference_id');
                $data['admission_date'] = date('Y-m-d H:i', strtotime($this->input->post('admission_date')));
                $data['bed_group_id'] = $this->input->post('bed_group_id');
                $data['bed_id'] = $this->input->post('bed_id');
                $data['contract_person'] = $this->input->post('contract_person');
                $data['contract_amount'] = $this->input->post('contract_amount');
                $data['contract_day'] = $this->input->post('contract_day') > 0 ? $this->input->post('contract_day') : null;
                $data['medicine'] = $this->input->post('medicine');
                $data['oxygen'] = $this->input->post('oxygen');
                // Optional Data
                $data['disease'] = $this->input->post('disease');
                $data['pulse'] = $this->input->post('pulse');
                $data['bp'] = $this->input->post('bp');
                //$data['resp'] = $this->input->post('resp');
                $data['temp'] = $this->input->post('temp');
                //$data['heart'] = $this->input->post('heart');
                //$data['lungs'] = $this->input->post('lungs');
                $data['height'] = $this->input->post('height');
                $data['weight'] = $this->input->post('weight');
                $data['case'] = $this->input->post('case');
                $data['casualty'] = $this->input->post('casualty');
                $data['symptoms'] = $this->input->post('symptoms');
                $data['operation_note'] = $this->input->post('operation_note');
                $data['patient_history'] = $this->input->post('patient_history');
                $data['remark'] = $this->input->post('remark');
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = logged_in_user_id();

                $insert_id = $this->ipd->insert('ipd_patients', $data);

                if ($insert_id) {
                    $this->ipd->insert('ipd_beds', array(
                        'ipd_id' => $insert_id,
                        'patient_id' => $data['patient_id'],
                        'bed_group_id' => $data['bed_group_id'],
                        'bed_id' => $data['bed_id'],
                        'from_date' => $data['admission_date'],
                        'status' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => logged_in_user_id()
                    ));
                    $this->ipd->update('beds', array('is_active' => 1), array('id' => $data['bed_id']));

                    // Send SMS
                    if (has_permission(ADD, 'ipd', 'ipd_admission_sms')) {
                        send_sms('ipd_admission', $insert_id);
                    }

                    create_log('Has been created a IPD Patient : ' . $patient['name']);
                    success($this->lang->line('insert_success'));
                    redirect('ipd/admitted');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('ipd/new');
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['doctors'] = $this->ipd->get_doctor_list();
        $this->data['references'] = $this->ipd->get_employee_list();
        $this->data['contracts'] = $this->ipd->get_contract_person_list();
        $this->data['bed_groups'] = $this->ipd->get_bed_group_list();
        $this->data['beds'] = $this->ipd->get_list('beds', array('status' => 1, 'is_active' => 0), '', '', '', 'id', 'ASC');

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

    /*****************Function existing**********************************
     * @type            : Function
     * @function name   : existing
     * @description     : Load "Add New IPD Patient" user interface
     *                    and process to store "ipd_patients" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function existing()
    {

        check_permission(VIEW);

        if ($_GET && !empty($this->input->get('search'))) {
            $search = $this->input->get('search');
            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            if ($search) {
                $config['base_url'] = site_url('ipd/existing/?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->ipd->get_patient_list($config['per_page'], $offset, $search, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->ipd->get_patient_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('existing') . ' ' . $this->lang->line('patient') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('ipd/existing', $this->data);
    }

    /*****************Function admission**********************************
     * @type            : Function
     * @function name   : admission
     * @description     : Load "Add Existing IPD Patient" user interface
     *                    and process to store "ipd_patients" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function admission($patient_id)
    {

        check_permission(ADD);

        $this->data['patient'] = $this->ipd->get_single('patients', array('user_id' => $patient_id));

        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('bed_group_id', $this->lang->line('admitted') . ' ' . $this->lang->line('ward'), 'trim|required');
            $this->form_validation->set_rules('bed_id', $this->lang->line('bed') . ' ' . $this->lang->line('number'), 'trim|required');

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


                // Patient Update Data
                $patient_data['name'] = $this->input->post('name');
                $patient_data['gender'] = $this->input->post('gender');
                $patient_data['phone'] = $this->input->post('phone');
                $patient_data['marital_status'] = $this->input->post('marital_status');
                $patient_data['guardian_name'] = $this->input->post('guardian_name');
                $patient_data['address'] = $this->input->post('address');

                $this->ipd->update('patients', $patient_data, array('user_id' => $patient_id));
                create_log('Has been updated a patient from IPD Admission : ' . $this->data['patient']->name . ' => ' . $patient_data['name']);


                // IPD Data
                $data['ipd_no'] = $this->ipd->get_custom_id('ipd_patients', 'IPD');
                $data['registration_no'] = $this->ipd->get_custom_id('ipd_patients', 'R-');
                $data['patient_id'] = $patient_id;
                $data['doctor_id'] = $this->input->post('doctor_id');
                $data['reference_id'] = $this->input->post('reference_id');
                $data['admission_date'] = date('Y-m-d H:i', strtotime($this->input->post('admission_date')));
                $data['bed_group_id'] = $this->input->post('bed_group_id');
                $data['bed_id'] = $this->input->post('bed_id');
                $data['contract_person'] = $this->input->post('contract_person');
                $data['contract_amount'] = $this->input->post('contract_amount');
                $data['contract_day'] = $this->input->post('contract_day') > 0 ? $this->input->post('contract_day') : null;
                $data['medicine'] = $this->input->post('medicine');
                $data['oxygen'] = $this->input->post('oxygen');

                // Optional Data
                $data['disease'] = $this->input->post('disease');
                $data['pulse'] = $this->input->post('pulse');
                $data['bp'] = $this->input->post('bp');
                //$data['resp'] = $this->input->post('resp');
                $data['temp'] = $this->input->post('temp');
                //$data['heart'] = $this->input->post('heart');
                //$data['lungs'] = $this->input->post('lungs');
                $data['height'] = $this->input->post('height');
                $data['weight'] = $this->input->post('weight');
                $data['case'] = $this->input->post('case');
                $data['casualty'] = $this->input->post('casualty');
                $data['symptoms'] = $this->input->post('symptoms');
                $data['operation_note'] = $this->input->post('operation_note');
                $data['patient_history'] = $this->input->post('patient_history');
                $data['remark'] = $this->input->post('remark');
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = logged_in_user_id();

                $insert_id = $this->ipd->insert('ipd_patients', $data);
                if ($insert_id) {
                    $this->ipd->insert('ipd_beds', array(
                        'ipd_id' => $insert_id,
                        'patient_id' => $data['patient_id'],
                        'bed_group_id' => $data['bed_group_id'],
                        'bed_id' => $data['bed_id'],
                        'from_date' => $data['admission_date'],
                        'status' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => logged_in_user_id()
                    ));
                    $this->ipd->update('beds', array('is_active' => 1), array('id' => $data['bed_id']));

                    // Send SMS
                    if (has_permission(ADD, 'ipd', 'ipd_admission_sms')) {
                        send_sms('ipd_admission', $insert_id);
                    }

                    create_log('Has been created a IPD Patient : ' . $this->data['patient']->name);
                    success($this->lang->line('insert_success'));
                    redirect('ipd/admitted');
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect('ipd/admission/' . $patient_id);
                }
            } else {
                $this->data = $_POST;
            }
        }

        $this->data['doctors'] = $this->ipd->get_doctor_list();
        $this->data['references'] = $this->ipd->get_employee_list();
        $this->data['contracts'] = $this->ipd->get_contract_person_list();
        $this->data['bed_groups'] = $this->ipd->get_bed_group_list();
        $this->data['beds'] = $this->ipd->get_list('beds', array('status' => 1, 'is_active' => 0), '', '', '', 'id', 'ASC');

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

    /*****************Function edit**********************************
     * @type            : Function
     * @function name   : edit
     * @description     : Load "Edit IPD Admitted Patient" user interface
     *                    and process to store "ipd_patients" 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('doctor_id', $this->lang->line('doctor'), 'trim');
            $this->form_validation->set_rules('admission_date', $this->lang->line('admission') . ' ' . $this->lang->line('date'), 'trim|required');
            $this->form_validation->set_rules('bed_group_id', $this->lang->line('bed') . ' ' . $this->lang->line('group'), 'trim|required');
            $this->form_validation->set_rules('bed_id', $this->lang->line('bed') . ' ' . $this->lang->line('name'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['doctor_id'] = $this->input->post('doctor_id');
                $data['reference_id'] = $this->input->post('reference_id');
                $data['contract_person'] = $this->input->post('contract_person');
                $data['contract_amount'] = $this->input->post('contract_amount');
                $data['contract_day'] = $this->input->post('contract_day') > 0 ? $this->input->post('contract_day') : null;
                $data['medicine'] = $this->input->post('medicine');
                $data['oxygen'] = $this->input->post('oxygen');

                $ipd_patient = $this->ipd->get_single('ipd_patients', array('id' => $this->input->post('id')));
                $ipd_bed = $this->ipd->get_single('ipd_beds', array('ipd_id' => $this->input->post('id')));
                if (isset($ipd_patient->bed_id) && $ipd_patient->bed_id ==  $this->input->post('bed_id')) {
                    $data['admission_date'] = date('Y-m-d H:i', strtotime($this->input->post('admission_date')));
                    $data['bed_group_id'] = $this->input->post('bed_group_id');
                    $data['bed_id'] = $this->input->post('bed_id');
                } else {
                    if ($ipd_patient->bed_empty == 0) {
                        $this->ipd->update('beds', array('is_active' => 0), array('id' => $ipd_patient->bed_id));
                        $data['admission_date'] = date('Y-m-d H:i', strtotime($this->input->post('admission_date')));
                        $data['bed_group_id'] = $this->input->post('bed_group_id');
                        $data['bed_id'] = $this->input->post('bed_id');
                        $this->ipd->update('beds', array('is_active' => 1), array('id' => $data['bed_id']));
                    }
                }

                if (isset($ipd_bed) && !empty($ipd_bed)) {
                    if ($ipd_patient->bed_empty == 0) {
                        $ipd_data['bed_group_id'] = $this->input->post('bed_group_id');
                        $ipd_data['bed_id'] = $this->input->post('bed_id');
                        $ipd_data['from_date'] = $data['admission_date'];
                        $this->ipd->update('ipd_beds', $ipd_data, array('id' => $ipd_bed->id));
                    }
                } else {
                    $ipd_data['ipd_id'] = $this->input->post('id');
                    $ipd_data['patient_id'] = $this->input->post('patient_id');
                    $ipd_data['bed_group_id'] = $this->input->post('bed_group_id');
                    $ipd_data['bed_id'] = $this->input->post('bed_id');
                    $ipd_data['from_date'] = $data['admission_date'];
                    $ipd_data['status'] = 1;
                    $ipd_data['created_at'] = date('Y-m-d H:i:s');
                    $ipd_data['created_by'] = logged_in_user_id();
                    $this->ipd->insert('ipd_beds', $ipd_data);
                }

                // Optional Data
                $data['disease'] = $this->input->post('disease');
                $data['pulse'] = $this->input->post('pulse');
                $data['bp'] = $this->input->post('bp');
                $data['temp'] = $this->input->post('temp');
                $data['height'] = $this->input->post('height');
                $data['weight'] = $this->input->post('weight');
                $data['case'] = $this->input->post('case');
                $data['casualty'] = $this->input->post('casualty');
                $data['symptoms'] = $this->input->post('symptoms');
                $data['operation_note'] = $this->input->post('operation_note');
                $data['patient_history'] = $this->input->post('patient_history');
                $data['remark'] = $this->input->post('remark');
                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();

                $updated = $this->ipd->update('ipd_patients', $data, array('id' => $this->input->post('id')));
                if ($updated) {
                    $patient = $this->ipd->get_single('patients', array('user_id' => $this->input->post('patient_id')));

                    // Send SMS
                    if (has_permission(EDIT, 'ipd', 'ipd_admission_sms')) {
                        send_sms('ipd_admission', $this->input->post('id'));
                    }

                    create_log('Has been updated a IPD patient : ' . $patient->name);
                    success($this->lang->line('update_success'));
                    redirect('ipd/admitted');
                } else {
                    error($this->lang->line('update_failed'));
                    redirect('ipd/edit/' . $this->input->post('id'));
                }
            } else {
                $this->data['ipd'] = $this->ipd->get_single('ipd_patients', array('id' => $this->input->post('id')));
            }
        } else {
            if ($id) {
                $this->data['ipd'] = $this->ipd->get_single('ipd_patients', array('id' => $id));
                if (!$this->data['ipd']) {
                    redirect('ipd/admitted');
                }
            }
        }


        $ipd_bed = $this->ipd->get_single('ipd_patients', array('id' => $id));

        $this->data['doctors'] = $this->ipd->get_doctor_list();
        $this->data['references'] = $this->ipd->get_employee_list();
        $this->data['contracts'] = $this->ipd->get_contract_person_list();
        $this->data['bed_groups'] = $this->ipd->get_bed_group_list();
        $this->data['beds'] = $this->ipd->get_list('beds', array('status' => 1, 'group_id' => $ipd_bed->bed_group_id), '', '', '', 'id', 'ASC');

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

    /*****************Function discharge**********************************
     * @type            : Function
     * @function name   : discharge
     * @description     : Load "IPD Discharge Patient" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function discharge()
    {
        if ($_GET) {
            $search = trim($this->input->get('search'));
            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('ipd/discharge/?search=' . $search);
            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->ipd->get_discharge_list($config['per_page'], $offset, $search, NULL, NULL, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->ipd->get_discharge_list($config['per_page'], $offset, $search, 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['search'] = $search;
        } 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->ipd->get_discharge_list($config['per_page'], $offset, NULL, date('Y-m-d'), date('Y-m-d'), $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->ipd->get_discharge_list($config['per_page'], $offset, NULL, date('Y-m-d'), date('Y-m-d'), $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        }

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

    /*****************Function get_single_ipd**********************************
     * @type            : Function
     * @function name   : get_single_ipd
     * @description     : Load "IPD List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function get_single_ipd($id)
    {
        $ipd = $this->ipd->get_single('ipd_patients', array('id' => $id));
        echo json_encode($ipd);
    }

    /*****************Function dischargePatient**********************************
     * @type            : Function
     * @function name   : dischargePatient
     * @description     : Load "IPD Discharge Patient" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function dischargePatient()
    {

        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('to_date', $this->lang->line('date'), 'trim|required');
            if ($this->form_validation->run() === TRUE) {

                $this->db->trans_start();

                // IPD Patients
                // $ipd_data['discharged'] = 1;
                // $ipd_data['discharged_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('to_date')));
                // $ipd_data['modified_at'] = date('Y-m-d H:i:s');
                // $ipd_data['modified_by'] = logged_in_user_id();
                // $this->ipd->update('ipd_patients', $ipd_data, array('id' => $this->input->post('id')));

                $this->ipd->update('ipd_patients', array('bed_empty' => 1), array('id' => $this->input->post('id')));

                // ipd_beds
                $ipd_bed_data['to_date'] = date('Y-m-d H:i', strtotime($this->input->post('to_date')));
                $ipd_bed_data['note'] = $this->input->post('note');
                $ipd_bed_data['discharged'] = 1;
                $ipd_bed_data['modified_at'] = date('Y-m-d H:i:s');
                $ipd_bed_data['modified_by'] = logged_in_user_id();
                $this->ipd->update('ipd_beds', $ipd_bed_data, array('ipd_id' => $this->input->post('id'), 'bed_id' => $this->input->post('bed_id')));

                // beds
                $bed_data['is_active'] = 0;
                $bed_data['modified_at'] = date('Y-m-d H:i:s');
                $bed_data['modified_by'] = logged_in_user_id();
                $this->ipd->update('beds', $bed_data, array('id' => $this->input->post('bed_id')));

                // Send SMS
                if (has_permission(ADD, 'ipd', 'ipd_discharged_sms')) {
                    send_sms('ipd_discharged', $this->input->post('id'));
                }

                // trans_complete
                $this->db->trans_complete();
                if ($this->db->trans_status() === FALSE) {
                    $array = array('status' => 'failed', 'message' => $this->lang->line('update_failed'));
                    echo json_encode($array);
                    die;
                }

                $patient = $this->ipd->get_single('patients', array('user_id' => $this->input->post('patient_id')));
                create_log('Has been discharged a patient bed: ' . $patient->name);
                success($this->lang->line('update_success'));
                redirect($_SERVER['HTTP_REFERER']);
            } else {
                success($this->lang->line('update_failed'));
                redirect('ipd/admitted');
                $this->data = $_POST;
            }
        }
    }

    /*****************Function profile**********************************
     * @type            : Function
     * @function name   : profile
     * @description     : Load "IPD Patient Profile" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function profile($ipd_id)
    {
        $this->data['patient'] = $this->ipd->get_single_ipd_patient($ipd_id);
        $this->data['total_investigation_due'] = $this->ipd->get_total_investigation_due($this->data['patient']->patient_id);
        $this->data['total_pharmacy_due'] = $this->ipd->get_total_pharmacy_due($this->data['patient']->patient_id);
        $this->data['total_ipd_advanced'] = $this->ipd->get_total_ipd_advaced($ipd_id, $this->data['patient']->patient_id);

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

    /*****************Function create**********************************
     * @type            : Function
     * @function name   : create
     * @description     : Load "IPD Create Bill" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function create($ipd_id)
    {

        check_permission(ADD);

        $this->data['patient'] = $this->ipd->get_single_ipd_patient($ipd_id);

        // Advanced 
        $advance = $this->ipd->get_patient_total_advance($ipd_id, $this->data['patient']->patient_id);

        $bed = $this->ipd->get_patient_bed_list($ipd_id, $this->data['patient']->patient_id);
        $bed_amounts = [];
        foreach ($bed as $item) {
            if ($item->discharged == 1) {
                if (date('H:i:s', strtotime($item->to_date)) < '11:59:00') {
                    $from_date = new DateTime(substr($item->from_date, 0, 10));
                    $to_date = $item->to_date ? new DateTime(substr($item->to_date, 0, 10)) : new DateTime(date('Y-m-d'));
                    $interval = $to_date->diff($from_date, true)->days + 1;
                    $interval = ($interval - 1);
                    $amount = abs((float) $item->price) * abs($interval);
                } else {
                    $from_date = new DateTime(substr($item->from_date, 0, 10));
                    $to_date = $item->to_date ? new DateTime(substr($item->to_date, 0, 10)) : new DateTime(date('Y-m-d'));
                    $interval = $to_date->diff($from_date, true)->days + 1;
                    $amount = abs((float) $item->price) * abs($interval);
                }
            } else {
                $from_date = new DateTime(substr($item->from_date, 0, 10));
                $to_date = $item->to_date ? new DateTime(substr($item->to_date, 0, 10)) : new DateTime(date('Y-m-d'));
                $interval = $to_date->diff($from_date, true)->days + 1;
                $amount = abs((float) $item->price) * abs($interval);
            }
            array_push($bed_amounts, [
                'type' => '',
                'dates' => $from_date->format('M d, Y h:iA') . '-' . $to_date->format('M d, Y h:iA'),
                'price' => $item->price + 0,
                'name' => $item->bed_group . ' - ' . $item->name,
                'qty' => $interval,
                'amount' => $amount + 0
            ]);
        }

        $surgeon = $this->ipd->get_patient_surgeon_list($ipd_id, $this->data['patient']->patient_id);
        $surgeon_amounts = [];
        foreach ($surgeon as $item) {
            array_push($surgeon_amounts, [
                'type' => 'Surgeon',
                'dates' => date('M d, Y', strtotime($item->date)),
                'price' => $item->charge + 0,
                'name' => $item->surgeon,
                'qty' => 1,
                'amount' => $item->charge + 0
            ]);
        }

        $anesthesia = $this->ipd->get_patient_anesthesia_list($ipd_id, $this->data['patient']->patient_id);
        $anesthesia_amounts = [];
        foreach ($anesthesia as $item) {
            array_push($anesthesia_amounts, [
                'type' => 'Anesthesia',
                'dates' => date('M d, Y', strtotime($item->date)),
                'price' => $item->charge + 0,
                'name' => $item->anesthesia,
                'qty' => 1,
                'amount' => $item->charge + 0
            ]);
        }


        $assistant = $this->ipd->get_patient_assistant_list($ipd_id, $this->data['patient']->patient_id);
        $assistant_amounts = [];
        foreach ($assistant as $item) {
            array_push($assistant_amounts, [
                'type' => 'Assistant',
                'dates' => date('M d, Y', strtotime($item->date)),
                'price' => $item->charge + 0,
                'name' => $item->assistant,
                'qty' => 1,
                'amount' => $item->charge + 0
            ]);
        }


        $consultant = $this->ipd->get_patient_consultant_list($ipd_id, $this->data['patient']->patient_id);
        $consultant_amounts = [];
        foreach ($consultant as $item) {
            array_push($consultant_amounts, [
                'type' => 'Consultant',
                'dates' => date('M d, Y', strtotime($item->dates)),
                'price' => round($item->rate) + 0,
                'name' => $item->consultant,
                'qty' => $item->qty,
                'amount' => round($item->amount) + 0
            ]);
        }


        $charge = $this->ipd->get_patient_charge_list($ipd_id, $this->data['patient']->patient_id);
        $charge_amounts = [];
        foreach ($charge as $item) {
            array_push($charge_amounts, [
                'type' => '',
                'dates' => date('M d, Y', strtotime($item->dates)),
                'price' => round($item->rate) + 0,
                'name' => $item->charge_name,
                'qty' => $item->qty,
                'amount' => round($item->amount) + 0
            ]);
        }


        $this->data['list'] = TRUE;
        $this->data['total_advanced'] = $advance;
        $this->data['bed_amounts'] = $bed_amounts;
        $this->data['surgeon_amounts'] = $surgeon_amounts;
        $this->data['anesthesia_amounts'] = $anesthesia_amounts;
        $this->data['assistant_amounts'] = $assistant_amounts;
        $this->data['consultant_amounts'] = $consultant_amounts;
        $this->data['charge_amounts'] = $charge_amounts;

        $this->layout->title($this->lang->line('create') . ' ' . $this->lang->line('bill') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('ipd/create', $this->data);
    }

    /*****************Function add**********************************
     * @type            : Function
     * @function name   : add
     * @description     : Load "IPD Create Invoice" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function add()
    {

        check_permission(ADD);

        if ($_POST) {
            $data['custom_invoice_id'] = get_datewise_custom_invoice_id('ipd_invoices', 'INV-', date('Y'), date('m'), date('d'));
            $data['prev_invoice_id'] = $this->input->post('prev_invoice_id') ?? null;
            $data['invoice_type'] = 'ipd';
            $data['ipd_id'] = $this->input->post('ipd_id');
            $data['patient_id'] = $this->input->post('patient_id');

            // Commission
            $commission_user_id = explode('-', $this->input->post('commission_user_id'));
            $coms = $this->ipd->get_single('employees', array('user_id' =>  $commission_user_id[0]));

            if (isset($coms->user_id)) {
                $data['commission_user_id'] = $commission_user_id[0];
            } else {
                $data['commission_name'] = $this->input->post('commission_user_id');
            }

            $reference_person = explode('-', $this->input->post('reference_person'));
            $emps = $this->ipd->get_single('employees', array('user_id' =>  $reference_person[0]));

            if (isset($emps->user_id)) {
                $data['reference_person'] = $emps->user_id;
            } else {
                $data['reference_person'] = null;
            }

            $data['bill_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('bill_date')));
            $data['total_bill'] = '0.00';
            $data['discount'] = $this->input->post('discount') > 0 ? $this->input->post('discount') : '0.00';
            $advanced = $this->input->post('advanced') > 0 ? $this->input->post('advanced') : '0.00';
            $data['advanced'] = $this->input->post('paid') + $advanced;
            $data['commission_amount'] = $this->input->post('commission') > 0 ? $this->input->post('commission') : '0.00';
            $data['payable_commission'] = $this->input->post('commission') > 0 ? $this->input->post('commission') : '0.00';

            $details = $this->input->post('charges');
            if (count($details) == 0 || empty($details)) {
                $array = array('status' => 'failed', 'error' => $this->lang->line('insert_success'));
                echo json_encode($array);
                die;
            }

            foreach ($details as $detail) {
                $data['total_bill'] += $detail['total'];
            }

            $data['net_payable'] = $data['total_bill'];
            $data['paid_status'] = 'unpaid';
            if ($data['discount'] > 0) {
                $data['net_payable'] -=  $data['discount'];
            }

            $data['due_amount'] = $data['net_payable'] - $data['advanced'];
            if ($data['due_amount'] <= 0) {
                $data['paid_status'] = 'paid';
            }

            $data['note'] = $this->input->post('note') ? $this->input->post('note') : null;
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            if ($this->input->post('created_by') > 0 && !empty($this->input->post('created_by'))) {
                $data['created_by'] = $this->input->post('created_by');
            } else {
                $data['created_by'] = logged_in_user_id();
            }

            $this->db->trans_start();
            $insert_id = $this->ipd->insert('ipd_invoices', $data);

            // IPD Advanced Payment Table
            if ($this->input->post('advanced') > 0) {
                $advance_data['payment_type'] = 1;
                $advance_data['custom_invoice_id'] = get_datewise_custom_invoice_id('ipd_advance_payments', 'INV-', date('Y'), date('m'), date('d'));;
                $advance_data['ipd_id'] = $this->input->post('ipd_id');
                $advance_data['patient_id'] = $this->input->post('patient_id');
                $advance_data['payment_date'] = date('Y-m-d H:i:s');
                $advance_data['amount'] = $this->input->post('advanced') > 0 ? $this->input->post('advanced') : '0.00';
                $advance_data['payment_status'] = 'complete';
                $advance_data['status'] = 1;
                $advance_data['created_at'] = date('Y-m-d H:i:s');
                $advance_data['created_by'] = logged_in_user_id();
                $this->ipd->insert('ipd_advance_payments', $advance_data);
            }

            //  ipd_invoice_details
            foreach ($details as $detail) {
                $details_data['invoice_id'] = $insert_id;
                $details_data['ipd_id'] = $this->input->post('ipd_id');
                $details_data['qty'] = $detail['quantity'];
                $details_data['name'] = $detail['name'];
                $details_data['price'] = $detail['price'];
                $details_data['total_rate'] = $detail['total'];

                $details_data['status'] = 1;
                $details_data['created_at'] = date('Y-m-d H:i:s');
                if ($this->input->post('created_by') > 0 && !empty($this->input->post('created_by'))) {
                    $details_data['created_by'] = $this->input->post('created_by');
                } else {
                    $details_data['created_by'] = logged_in_user_id();
                }
                $this->ipd->insert('ipd_invoice_details', $details_data);
            }

            // Payment Invoice Data
            $paymentdata['invoice_id'] = $insert_id;
            $paymentdata['ipd_id'] = $this->input->post('ipd_id');
            $paymentdata['collection_type'] = '1';
            $paymentdata['payment_date'] = date('Y-m-d H:i:s', strtotime($this->input->post('bill_date')));
            $paymentdata['amount'] = $this->input->post('advanced') ? $this->input->post('advanced') : '0.00';
            $paymentdata['payment_status'] = 'complete';
            $paymentdata['status'] = 1;
            $paymentdata['created_at'] = date('Y-m-d H:i:s');
            if ($this->input->post('created_by') > 0 && !empty($this->input->post('created_by'))) {
                $paymentdata['created_by'] = $this->input->post('created_by');
            } else {
                $paymentdata['created_by'] = logged_in_user_id();
            }
            $this->ipd->insert('ipd_payments', $paymentdata);
            $this->ipd->update('ipd_patients', array('discharged' => 1, 'discharged_date' => $data['bill_date']), array('id' => $data['ipd_id'], 'patient_id' =>  $data['patient_id']));

            // trans_complete
            $this->db->trans_complete();
            if ($this->db->trans_status() === FALSE) {
                $array = array('status' => 'failled', 'message' => $this->lang->line('insert_success'));
                echo json_encode($array);
                die;
            }

            if ($insert_id) {
                create_log('Has been created a invoice : ' . $data['custom_invoice_id']);
            }
            $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'), 'id' => $insert_id);
            echo json_encode($array);
        }
    }

    /*****************Function service_search**********************************
     * @type            : Function
     * @function name   : service_search
     * @description     : Load "IPD Service" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function service_search()
    {
        $search = $this->ipd->get_service_search($this->input->post('name'));
        echo json_encode($search);
    }

    /*****************Function commission_search**********************************
     * @type            : Function
     * @function name   : commission_search
     * @description     : Load "IPD Commission" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function commission_search()
    {
        $search = $this->ipd->get_commission_search($this->input->post('name'));
        echo json_encode($search);
    }

    /*****************Function employee_search**********************************
     * @type            : Function
     * @function name   : employee_search
     * @description     : Load "IPD Commission" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function employee_search()
    {
        $search = $this->ipd->get_employee_search($this->input->post('name'));
        echo json_encode($search);
    }

    /*****************Function get_doctor_charge**********************************
     * @type            : Function
     * @function name   : get_doctor_charge
     * @description     : Load "IPD Doctor Charge" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function get_doctor_charge()
    {
        $user_id = $this->input->post('user_id');
        if ($user_id > 0) {
            $doctor_charges = $this->ipd->get_single('doctor_charges', array('doctor_id' => $user_id));
            $doctor_charge = array(
                'charge' => $doctor_charges->ipd_charge
            );
        }
        echo (json_encode($doctor_charge));
    }

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

    public function print()
    {
        $this->data['patient'] = $this->ipd->get_print_list($this->input->post('id'));
        $this->load->view('ipd/print', $this->data);
    }

    public function consent()
    {
        $this->data['patient'] = $this->ipd->get_print_list($this->input->post('id'));
        $this->data['surgeon'] = $this->ipd->get_single_surgeon($this->input->post('id'), $this->data['patient']->patient_id);
        $this->data['anesthesias'] = $this->ipd->get_single_anesthesia($this->input->post('id'), $this->data['patient']->patient_id);
        $this->load->view('ipd/consent', $this->data);
    }

    public function invoice($ipd_id, $invoice_id)
    {

        check_permission(VIEW);

        $this->data['patient'] = $this->ipd->get_single_ipd_patient($ipd_id);
        $this->data['invoices'] = $this->ipd->get_invoice_list($ipd_id, $invoice_id);
        $this->data['invoice'] = $this->ipd->get_single('ipd_invoices', array('id' => $invoice_id));
        $this->data['reference'] = $this->ipd->get_single('employees', array('user_id' => $this->data['invoice']->commission_user_id));

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


    /*****************Function invoice_print**********************************
     * @type            : Function
     * @function name   : invoice_print
     * @description     : Load "Invoice print" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function invoice_print()
    {
        $this->load->library('Numbertowords');
        $this->data['patient'] = $this->ipd->get_single_ipd_patient($this->input->post('ipd_id'));
        $this->data['invoices'] = $this->ipd->get_invoice_list($this->input->post('ipd_id'), $this->input->post('invoice_id'));
        $this->data['invoice'] = $this->ipd->get_single('ipd_invoices', array('id' => $this->input->post('invoice_id')));
        $this->data['created_by'] = $this->ipd->get_single('employees', array('user_id' => $this->data['invoice']->created_by));
        $this->load->view('ipd/invoice-print', $this->data);
    }

    public function billing()
    {

        check_permission(VIEW);

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

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            if ($search || $date) {
                $config['base_url'] = site_url('ipd/billing/?date=' . $date . '&type=' . $type . '&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->ipd->get_bill_list($config['per_page'], $offset, $search, $type, $form_date, $to_date, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['bills'] = $this->ipd->get_bill_list($config['per_page'], $offset, $search, $type, $form_date, $to_date, $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['date'] = $date;
            $this->data['type'] = $type;
        } else {
            $search = trim($this->input->get('search'));
            $type = $this->input->get('type');
            $form_date = date('Y-m-d');
            $to_date = date('Y-m-d');
            $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->ipd->get_bill_list($config['per_page'], $offset, $search, $type, $form_date, $to_date, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['bills'] = $this->ipd->get_bill_list($config['per_page'], $offset, $search, $type, $form_date, $to_date, $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['date'] = $form_date;
            $this->data['type'] = $type;
        }

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

    /*****************Function getInvoiceId**********************************
     * @type            : Function
     * @function name   : getInvoiceId
     * @description     : Load "getInvoiceId" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function getInvoiceId($id)
    {
        $invoice = $this->ipd->get_single('ipd_invoices', array('id' =>  $id));
        echo json_encode($invoice);
    }
    /*****************Function payment_status**********************************
     * @type            : Function
     * @function name   : payment_status
     * @description     : Load "payment_status" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function payment_status()
    {
        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('payment_status', $this->lang->line('payment') . ' ' . $this->lang->line('status'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['payment_status'] = $this->input->post('payment_status');
                $data['note'] = $this->input->post('note');

                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();

                $updated_id = $this->ipd->update('ipd_invoices', $data, array('id' => $this->input->post('invoice_id')));
                if ($updated_id) {
                    create_log('Has been update a invoice : ' . $this->input->post('invoice_id'));
                }
                $array = array('status' => 'success', 'message' => $this->lang->line('update_success'));
            } else {
                $this->data = $_POST;
                $msg = array(
                    'payment_status' => form_error('payment_status')
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }

    /*     * ***************Function delete_bill**********************************
     * @type            : Function
     * @function name   : delete_bill
     * @description     : delete_bill "Invoice Delete" data from database
     *                     and unlink all information server
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */

    public function delete_bill($id = null)
    {

        check_permission(DELETE);

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

        $invoice = $this->ipd->get_single('ipd_invoices', array('id' => $id));
        if (!empty($invoice)) {

            // delete invoice data
            $this->ipd->delete('ipd_invoices', array('id' => $id));
            // delete invoice details data
            $this->ipd->delete('ipd_invoice_details', array('invoice_id' => $invoice->id));

            // delete invoice payment data
            $this->ipd->delete('ipd_payments', array('invoice_id' => $invoice->id));

            create_log('Has been deleted a invoice : ' . $invoice->id . '-> [' . $invoice->custom_invoice_id . ']');
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function history($ipd_id, $invoice_id)
    {

        check_permission(VIEW);

        $this->data['patient'] = $this->ipd->get_single_ipd_patient($ipd_id);
        $this->data['payments'] = $this->ipd->get_payment_history_list($ipd_id, $invoice_id);
        $this->data['invoice'] = $this->ipd->get_single('ipd_invoices', array('id' => $invoice_id));
        $this->data['reference'] = $this->ipd->get_single('employees', array('user_id' => $this->data['invoice']->commission_user_id));

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

    /*****************Function get_payment_data**********************************
     * @type            : Function
     * @function name   : get_payment_data
     * @description     : Load "Payment Amount" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function get_payment_data($ipd_id, $invoice_id)
    {
        $invoice = $this->ipd->get_single('ipd_invoices', array('ipd_id' => $ipd_id, 'id ' => $invoice_id));
        $amount = array('amount' => $invoice->due_amount);
        echo json_encode($amount);
    }


    public function add_payment()
    {

        check_permission(ADD);

        if ($_POST) {
            $due = $this->ipd->get_single('ipd_invoices', array('id' => $this->input->post('invoice_id'), 'ipd_id' => $this->input->post('ipd_id')));

            $data['payment_type'] = '2';
            $data['custom_invoice_id'] = get_datewise_custom_invoice_id('ipd_advance_payments', 'INV-', date('y'), date('m'), date('d'));
            $data['ipd_id'] = $this->input->post('ipd_id');
            $data['patient_id'] = $due->patient_id;
            $data['payment_date'] = $this->input->post('date') ? date('Y-m-d H:i:s', strtotime($this->input->post('date'))) : NULL;
            $data['amount'] = $this->input->post('amount');
            $data['note'] = $this->input->post('note');
            $data['payment_status'] = 'complete';

            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();

            $this->ipd->insert('ipd_advance_payments', $data);

            if ($this->input->post('amount') > 0 || $this->input->post('amount') == 0) {
                if ($this->input->post('second_less') > 0) {
                    $data_payment['net_payable'] =   $due->net_payable - $this->input->post('second_less');
                }
                $data_payment['due_amount'] =   ($due->due_amount - ($data['amount'] + $this->input->post('second_less')));
                $data_payment['advanced'] = ($due->advanced + $data['amount']);
                $data_payment['discount'] =   ($due->discount + $this->input->post('second_less'));

                if ($data_payment['due_amount'] <= 0) {
                    $data_payment['paid_status'] = 'paid';
                }
                $data_payment['modified_at'] = date('Y-m-d H:i:s');
                $data_payment['modified_by'] = logged_in_user_id();
                $this->ipd->update('ipd_invoices', $data_payment, array('id' =>  $this->input->post('invoice_id'), 'ipd_id' =>  $this->input->post('ipd_id')));
            }
            create_log('Has been created a IPD payment : ' . $data['custom_invoice_id']);
            $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('insert_success'));
        } else {
            $msg = array(
                'amount' => form_error('amount'),
            );
            $array = array('status' => 'failed', 'error' => $msg, 'message' => '');
        }

        echo json_encode($array);
    }

    public function ipd_admission_sms($id = null)
    {
        check_permission(VIEW);
        if ($id) {
            send_sms('ipd_admission', $id);
        }
    }

    public function ipd_discharged_sms($id = null)
    {
        check_permission(VIEW);
        if ($id) {
            send_sms('ipd_discharged', $id);
        }
    }
}
