<?php

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

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

class Appointment extends MY_Controller
{

    public $data = array();

    function __construct()
    {
        parent::__construct();
        $this->load->library('Numbertowords');
        $this->load->model('Appointment_Model', 'appointment', true);
        $this->data['doctors'] = $this->appointment->get_doctor_list();
        $this->data['references'] = $this->appointment->get_list('employees', array('status' => 1));
        $this->data['employees'] = $this->appointment->get_employee_list();
    }

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

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

        check_permission(VIEW);

        if (empty($this->input->get('patient'))) {
            $keyword = $this->input->get('keyword');
            $date = $this->input->get('date');
            $doctor_id = $this->input->get('doctor_id');

            $config = array();
            $config = get_pagination(20);
            if ($date || $keyword) {
                $config['base_url'] = site_url('frontoffice/appointment/?keyword=' . $keyword . '&date=' . $date . '&doctor_id=' . $doctor_id);
            } 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->appointment->get_appointment_list($config['per_page'], $offset, $keyword, $date, $doctor_id, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['appointments'] = $this->appointment->get_appointment_list($config['per_page'], $offset, $keyword, $date, $doctor_id, $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['doctor_id'] = $doctor_id;
        }
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_appointment') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('appointment/index', $this->data);
    }

    /*****************Function patient**********************************
     * @type            : Function
     * @function name   : patient
     * @description     : Load "Patient List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function patient()
    {
        check_permission(VIEW);

        if ($_GET) {
            $patient = $this->input->get('patient');

            $config = array();
            $config = get_pagination(20);
            if ($patient) {
                $config['base_url'] = site_url('frontoffice/appointment/?patient=' . $patient);
            } 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->appointment->get_patient_list($config['per_page'], $offset, $patient, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->appointment->get_patient_list($config['per_page'], $offset, $patient, $count = FALSE);

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

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

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

        check_permission(ADD);

        $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') . ' ' . $this->lang->line('name'), '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('gender', $this->lang->line('gender'), 'trim|required');

        if ($this->form_validation->run() === TRUE) {
            $data['patient_id'] = $this->input->post('patient_id') ? $this->input->post('patient_id') : 0;
            $data['doctor_id'] = $this->input->post('doctor_id');
            $data['reference_id'] = $this->input->post('reference_id');

            $data['serial_no'] = get_custom_serial_number('appointments', $this->input->post('doctor_id'), date('Y-m-d', strtotime($this->input->post('date'))));
            $data['appointment_no'] = get_custom_appointment_number($data['serial_no']);
            $data['date'] = $this->input->post('date') ? date('Y-m-d', strtotime($this->input->post('date'))) : NULL;
            $data['name'] = $this->input->post('name');
            $data['phone'] = $this->input->post('phone');
            $data['gender'] = $this->input->post('gender');
            $data['address'] = $this->input->post('address');
            $data['note'] = $this->input->post('note');
            $data['appointment_status'] = $this->input->post('appointment_status');
            $data['source'] = 0;
            $data['is_opd'] = 0;
            $data['is_ipd'] = 0;
            $data['status'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = logged_in_user_id();

            $inserted_id = $this->appointment->insert('appointments', $data);

            if (has_permission(ADD, 'frontoffice', 'appointment_sms')) {
                send_sms('appointment', $inserted_id);
            }

            create_log('Has been created a Appointment : ' . $data['name']);
            $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('insert_success'));
        } else {
            $msg = array(
                'doctor_id' => form_error('doctor_id'),
                'name' => form_error('name'),
                'phone' => form_error('phone'),
                'gender' => form_error('gender'),
            );
            $array = array('status' => 'failed', 'error' => $msg, 'message' => '');
        }

        echo json_encode($array);
    }

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

        $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') . ' ' . $this->lang->line('name'), '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('gender', $this->lang->line('gender'), 'trim|required');

        if ($this->form_validation->run() === TRUE) {
            $app = $this->appointment->get_single('appointments', array('id' => $this->input->post('id')));
            $data['doctor_id'] = $this->input->post('doctor_id') ?? $app->doctor_id;
            $data['reference_id'] = $this->input->post('reference_id') ?? $app->reference_id;
            $data['date'] = $this->input->post('date') ? date('Y-m-d', strtotime($this->input->post('date'))) : NULL;
            if ($this->input->post('doctor_id') == $app->doctor_id && date('Y-m-d', strtotime($this->input->post('date'))) == date('Y-m-d', strtotime($app->date))) {
                $data['serial_no'] = $app->serial_no;
                $data['appointment_no'] = $app->appointment_no;
            } else {
                $data['serial_no'] = get_custom_serial_number('appointments', $this->input->post('doctor_id'), date('Y-m-d', strtotime($this->input->post('date'))));
                $data['appointment_no'] = get_custom_appointment_number($data['serial_no']);
            }
            $data['name'] = $this->input->post('name');
            $data['phone'] = $this->input->post('phone');
            $data['gender'] = $this->input->post('gender');
            $data['address'] = $this->input->post('address');
            $data['note'] = $this->input->post('note');
            $data['appointment_status'] = $this->input->post('appointment_status');
            $data['is_opd'] = $this->input->post('is_opd');
            $data['source'] = 0;
            // $data['is_ipd'] = 0;
            $data['status'] = 1;
            if ($this->input->post('created_by') !== $app->created_by) {
                $data['created_by'] = $this->input->post('created_by') ?? $app->created_by;
                $invoice = $this->appointment->get_single('invoices', array('appointment_id' => $app->id, 'marketing_id' => $app->created_by), '', '', '', 'id', 'ASC');
                if (isset($invoice) && !empty($invoice)) {
                    $this->appointment->update('invoices', array('marketing_id' => $this->input->post('created_by')), array('id' => $invoice->id));
                }
            }
            $data['modified_at'] = date('Y-m-d H:i:s');
            $data['modified_by'] = logged_in_user_id();

            $this->appointment->update('appointments', $data, array('id' => $this->input->post('id')));

            appointment_history($app, $data);

            if (has_permission(EDIT, 'frontoffice', 'appointment_sms')) {
                send_sms('appointment', $this->input->post('id'));
            }

            create_log('Has been updated a Appointment : ' . $data['name']);
            $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('update_success'));
        } else {
            $msg = array(
                'doctor_id' => form_error('doctor_id'),
                'name' => form_error('name'),
                'phone' => form_error('phone'),
                'gender' => form_error('gender'),
            );
            $array = array('status' => 'failed', 'error' => $msg, 'message' => '');
        }

        echo json_encode($array);
    }

    /*****************Function addemployee**********************************
     * @type            : Function
     * @function name   : addemployee
     * @description     : Load "Add Employee" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function addemployee()
    {
        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') . ' ' . $this->lang->line('type'), 'trim|required');
            $this->form_validation->set_rules('phone', $this->lang->line('phone'), 'trim|required|callback_reference_phone');

            if ($this->form_validation->run() === TRUE) {
                $data['name'] = $this->input->post('name');
                $data['phone'] = $this->input->post('phone');
                $data['commission_type'] = $this->input->post('commission_type');
                $data['employee_type'] = 'other';
                $data['status'] = 1;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = logged_in_user_id();
                // create user
                $data['user_id'] = $this->appointment->create_user();
                $doc = $this->appointment->get_single('employees', array('user_id' => $data['user_id']));


                $insert_id = $this->appointment->insert('employees', $data);
                if ($insert_id) {
                    create_log('Has been created a VD : ' . $data['name']);
                }
                $doc = $this->appointment->get_single('employees', array('user_id' => $data['user_id']));
                $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'), 'emp_user_id' => $doc->user_id, 'emp_name' => $doc->name, 'emp_phone' => $doc->phone);
            } else {
                $this->data = $_POST;
                $msg = array(
                    'name' => form_error('name'),
                    'phone' => form_error('phone'),
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }

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

    /*****************Function addPatient**********************************
     * @type            : Function
     * @function name   : addPatient
     * @description     : Load "Add Patient" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function addPatient($appointment_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('name', $this->lang->line('patient') . ' ' . $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');

            if ($this->form_validation->run() === TRUE) {
                $data['name'] = $this->input->post('name');
                $data['phone'] = $this->input->post('phone');
                $data['gender'] = $this->input->post('gender');
                $data['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));
                $data['dob'] = date('Y-m-d', strtotime($dob));
                $data['age'] = floor((time() - strtotime($data['dob'])) / 31556926);
                // End Age Calculation

                $data['discharged'] = 0;
                $data['status'] = 1;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['created_by'] = logged_in_user_id();
                // create patient_unique_id
                $data['patient_unique_id'] = $this->appointment->get_custom_id('patients', '1');
                // create user
                $data['user_id'] = $this->appointment->create_user();

                $insert_id = $this->appointment->insert('patients', $data);
                $this->appointment->update('appointments', array('is_opd' => 1, 'patient_id' => $data['user_id']), array('id' => $appointment_id));
                if ($insert_id) {
                    create_log('Has been created a patient : ' . $data['name']);
                    success($this->lang->line('insert_success'));
                    redirect('frontoffice/appointment/move/' . $data['user_id'] . '?app_id=' . $appointment_id);
                } else {
                    error($this->lang->line('insert_failed'));
                    redirect($_SERVER['HTTP_REFERER']);
                }
            } else {
                $this->data = $_POST;
            }
        }
        $this->data['appointment'] = $this->appointment->get_single('appointments', array('id' => $appointment_id));
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('add') . ' ' . $this->lang->line('patient') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('appointment/add_patient', $this->data);
    }

    public function move($patient_id)
    {
        $this->data['patient'] = $this->appointment->get_single('patients', array('user_id' => $patient_id));
        $this->data['appointment'] = $this->appointment->get_single('appointments', array('id' => $this->input->get('app_id')));
        $this->data['doctor'] = $this->appointment->get_single('employees', array('user_id' => $this->data['appointment']->doctor_id));
        $this->data['reference'] = $this->appointment->get_single('employees', array('user_id' => $this->data['appointment']->reference_id));
        $this->data['doctor_charge_info'] = $this->appointment->get_single('doctor_charges', array('doctor_id' => $this->data['appointment']->doctor_id));

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

    /*****************Function get_single_appointment_patient**********************************
     * @type            : Function
     * @function name   : get_single_appointment_patient
     * @description     : Load "Single Appointment Patient" user interface
     *                    and process to store "patients" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function get_single_appointment_patient($id)
    {
        $patient = $this->appointment->get_single('appointments', array('id' => $id));
        echo json_encode($patient);
    }

    /*****************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->appointment->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->appointment->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;
        }
    }

    /*****************Function get_patient_details**********************************
     * @type            : Function
     * @function name   : get_patient_details
     * @description     : Load "Opd Single Patient" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function get_patient_details()
    {
        $user_id = $this->input->post('user_id');
        if (!empty($user_id)) {
            $patient = $this->appointment->get_patient_details($user_id);
            echo json_encode($patient);
        }
    }


    /*****************Function get_doctor_charge**********************************
     * @type            : Function
     * @function name   : get_doctor_charge
     * @description     : Load "Opd Doctor Charge" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function get_doctor_charge()
    {
        $user_id = $this->input->post('user_id');
        $old_patient = $this->input->post('old_patient');
        if ($user_id > 0 && $old_patient != "") {
            $doctor_charges = $this->appointment->get_doctor_charges($user_id);
            if ($old_patient == 0) {
                $doctor_charge = array(
                    // 'charge' => $doctor_charges->first_fee,
                    // 'hospital_commission' => $doctor_charges->hospital_commission,
                    'charge' => $doctor_charges->first_fee,
                    'discount_limit' => $doctor_charges->discount_limit,
                    'is_discount' => $doctor_charges->is_discount,
                    'is_limit' => $doctor_charges->is_limit,
                );
            } else {
                $doctor_charge = array(
                    // 'charge' => $doctor_charges->second_fee,
                    // 'hospital_commission' => 0,
                    'charge' => $doctor_charges->second_fee,
                    'discount_limit' => $doctor_charges->discount_limit,
                    'is_discount' => $doctor_charges->is_discount,
                    'is_limit' => $doctor_charges->is_limit,
                );
            }
        } else {
            $doctor_charge = array(
                // 'charge' => 0,
                // 'hospital_commission' => 0,
                'charge' => 0,
                'discount_limit' => 0,
                'is_discount' => 0,
                'is_limit' => 0,

            );
        }
        echo (json_encode($doctor_charge));
    }

    public function addOpdPatient()
    {
        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('patient_id', $this->lang->line('patient') . ' ' . $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('appointment_date', $this->lang->line('appointment') . ' ' . $this->lang->line('date'), 'trim|required');
            $this->form_validation->set_rules('doctor_id', $this->lang->line('doctor') . ' ' . $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('old_patient', $this->lang->line('patient') . ' ' . $this->lang->line('type'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['appointment_id'] = $this->input->post('appointment_id');
                $data['patient_id'] = $this->input->post('patient_id');
                $data['custom_invoice_id '] = get_custom_invoice('opd_patients', 'B-', date('Y'), date('m'));
                // create patient_opd unique_no
                $data['opd_no'] = $this->appointment->get_custom_id('opd_patients', 'OPD');
                $data['appointment_date'] = date('Y-m-d', strtotime($this->input->post('appointment_date')));
                //$data['serial_no'] = get_custom_serial_number('opd_patients', array('doctor_id' => $this->input->post('doctor_id'), 'appointment_date' => date('Y-m-d', strtotime($this->input->post('appointment_date')))));
                $data['serial_no'] = $this->input->post('serial_no');
                $data['height'] = $this->input->post('height');
                $data['weight'] = $this->input->post('weight');
                $data['bp'] = $this->input->post('bp');
                $data['symptoms'] = $this->input->post('symptoms');
                $data['doctor_id'] = $this->input->post('doctor_id');
                $data['reference_id'] = $this->input->post('reference_id');
                $data['discount'] = $this->input->post('discount') > 0 ? $this->input->post('discount') : 0;
                $doctor_charge = $this->appointment->get_single('doctor_charges', array('doctor_id' => $data['doctor_id']));
                $total_amount = ($doctor_charge->hospital_commission ? $doctor_charge->hospital_commission : 0) + ($doctor_charge->reference_commission ? $doctor_charge->reference_commission : 0);

                if ($this->input->post('old_patient') == 1) {
                    $data['doctor_charge'] = $doctor_charge->second_fee;
                    $data['hospital_commission'] = 0;
                    $data['reference_commission'] = 0;
                    $data['discount'] = 0;
                } else {
                    $data['doctor_charge'] = $doctor_charge->first_fee;
                    if ($doctor_charge->is_discount) {
                        if (isset($data['reference_id']) &&  $data['reference_id'] > 0) {
                            if ($data['discount'] > 0 && $doctor_charge->reference_commission > $data['discount']) {
                                $data['hospital_commission'] = $doctor_charge->hospital_commission;
                                $data['reference_commission'] = $doctor_charge->reference_commission - $data['discount'];
                            } else {
                                if ($data['discount'] > 0 && $total_amount < $data['discount']) {
                                    $data['hospital_commission'] = 0;
                                    $data['reference_commission'] = 0;
                                } else {
                                    if (isset($data['reference_id']) &&  $doctor_charge->reference_commission <= $data['discount']) {
                                        $data['hospital_commission'] = $total_amount - $data['discount'];
                                        $data['reference_commission'] = 0;
                                    } else {
                                        $data['hospital_commission'] = $doctor_charge->hospital_commission;
                                        $data['reference_commission'] = $doctor_charge->reference_commission;
                                    }
                                }
                            }
                        } else {
                            if ($data['discount'] > 0 && $total_amount >= $data['discount']) {
                                $data['hospital_commission'] = $total_amount - $data['discount'];
                                $data['reference_commission'] = 0;
                            } else {
                                if ($total_amount < $data['discount']) {
                                    $data['hospital_commission'] = 0;
                                    $data['reference_commission'] = 0;
                                } else {
                                    $data['hospital_commission'] = $doctor_charge->hospital_commission + $doctor_charge->reference_commission;
                                    $data['reference_commission'] = 0;
                                }
                            }
                        }
                    } else {
                        if (isset($data['reference_id']) &&  $data['reference_id'] > 0) {
                            $data['hospital_commission'] = $doctor_charge->hospital_commission;
                            $data['reference_commission'] = $doctor_charge->reference_commission;
                            $data['discount'] = 0;
                        } else {
                            $data['hospital_commission'] = $doctor_charge->hospital_commission + $doctor_charge->reference_commission;
                            $data['reference_commission'] = 0;
                            $data['discount'] = 0;
                        }
                    }
                }

                // if ($this->input->post('old_patient') == 1) {
                //     $data['doctor_charge'] = $doctor_charge->second_fee;
                //     $data['hospital_commission'] = 0;
                //     $data['reference_commission'] = 0;
                //     $data['discount'] = 0;
                // } else {
                //     $data['doctor_charge'] = $doctor_charge->first_fee;
                //     if ($doctor_charge->is_discount) {
                //         $data['discount'] = $this->input->post('discount') > 0 ? $this->input->post('discount') : 0;
                //         $amount = $doctor_charge->hospital_commission + $doctor_charge->reference_commission;
                //         if ($amount > $data['discount']) {
                //             if ($doctor_charge->reference_commission >=  $data['discount'] &&  $data['discount'] > 0 && $data['reference_id']) {
                //                 $data['reference_commission'] = $doctor_charge->reference_commission - $this->input->post('discount') ?? 0;
                //                 $data['hospital_commission'] = $doctor_charge->hospital_commission;
                //             } else {
                //                 $data['reference_commission'] = 0;
                //                 $data['hospital_commission'] = $amount - $data['discount'];
                //             }
                //         } else {
                //             $data['hospital_commission'] = 0;
                //             $data['reference_commission'] = 0;
                //         }
                //     } else {
                //         $data['discount'] = 0;
                //     }
                // }

                // if ($data['discount'] > 0) {
                //     $data['hospital_commission'] = $this->input->post('hospital_commission') - $this->input->post('discount');
                // } else {
                //     $data['hospital_commission'] = $this->input->post('hospital_commission');
                // }
                $data['old_patient'] = $this->input->post('old_patient');
                $data['case'] = $this->input->post('case');
                $data['casualty'] = $this->input->post('casualty');
                $data['payment_method'] = $this->input->post('payment_method');
                $data['note'] = $this->input->post('note');

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

                $insert_id = $this->appointment->insert('opd_patients', $data);
                if ($insert_id) {
                    create_log('Has been created a OPD Patient : ' . $data['appointment_date']);
                }
                $array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('insert_success'), 'user_id' => $data['patient_id'], 'opd_id' => $insert_id, 'appointment_id' => $this->input->post('appointment_id'));
                $this->appointment->update('appointments', array('is_opd' => 1), array('id' => $this->input->post('appointment_id')));

                if ($this->input->post('old_patient') == 1) {
                    $this->appointment->update('patients', array('old_patient' => 1), array('user_id' => $data['patient_id']));
                } else {
                    $this->appointment->update('patients', array('old_patient' => 0), array('user_id' => $data['patient_id']));
                }
            } else {
                $this->data = $_POST;
                $msg = array(
                    'patient_id' => form_error('patient_id'),
                    'appointment_date' => form_error('appointment_date'),
                    'doctor_id' => form_error('doctor_id'),
                    'old_patient' => form_error('old_patient'),
                );
                $array = array('status' => 'failed', 'error' => $msg, 'message' => '');
            }
            echo json_encode($array);
        }
    }

    public function get_patient_visit_bill()
    {
        $patient_id = $this->input->post("patient_id");
        $opd_id = $this->input->post("opd_id");
        $appointment_id = $this->input->post("appointment_id");
        $this->data["patient"] = $this->appointment->get_patient_visit_bill($patient_id, $opd_id, $appointment_id);
        $this->load->view('frontoffice/appointment/visit_bill', $this->data);
    }

    /*****************Function get_patient**********************************
     * @type            : Function
     * @function name   : get_patient
     * @description     : Load "Patient List" user interface
     *                    and process to store "appointments" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function get_patient($user_id)
    {
        $patient = $this->appointment->get_single('patients', array('user_id' => $user_id));
        echo json_encode($patient);
    }

    /*****************Function get_appointment**********************************
     * @type            : Function
     * @function name   : get_appointment
     * @description     : Load "Single Appointment" user interface
     *                    and process to store "appointments" into database
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function get_appointment($id)
    {
        $appointment = $this->appointment->get_single('appointments', array('id' => $id));
        // $data = array(
        //     'id' => $appointment->id,
        //     'user_id' => $appointment->patient_id,
        //     'name' => $appointment->name,
        //     'phone' => $appointment->phone,
        //     'date' => date('Y-m-d', strtotime($appointment->date)),
        //     'doctor_id' => $appointment->doctor_id,
        //     'reference_id' => $appointment->reference_id,
        //     'gender' => $appointment->gender,
        //     'address' => $appointment->address,
        //     'note' => $appointment->note,
        //     'appointment_status' => $appointment->appointment_status,
        //     'is_opd' => $appointment->is_opd,
        // );
        echo json_encode($appointment);
    }


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

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

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Appointment" 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/appointment');
        }

        $appointment = $this->appointment->get_single('appointments', array('id' => $id));

        if ($this->appointment->delete('appointments', array('id' => $id))) {
            create_log('Has been deleted a Appointment : ' . $appointment->name);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }

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