<?php

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

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

class Patient extends MY_Controller
{

    public $data = array();

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

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

        check_permission(VIEW);

        if ($_GET) {
            $keyword = trim($this->input->get('keyword'));
            $create_date = $this->input->get('create_date');
            if (isset($create_date) && !empty($create_date)) {
                $exp = explode('-', $create_date);
                $create_form_date = date('Y-m-d', strtotime($exp[0]));
                $create_to_date = date('Y-m-d', strtotime($exp[1]));
            } else {
                $create_form_date = null;
                $create_to_date = null;
            }

            $followup_date = $this->input->get('followup_date');
            if (isset($followup_date) && !empty($followup_date)) {
                $exp1 = explode('-', $followup_date);
                $followup_form_date = date('Y-m-d', strtotime($exp1[0]));
                $followup_to_date = date('Y-m-d', strtotime($exp1[1]));
            } else {
                $followup_form_date = null;
                $followup_to_date = null;
            }

            $status = $this->input->get('status');
            $gender = $this->input->get('gender');
            $category_id = $this->input->get('category_id');
            $created_by = $this->input->get('created_by');

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('followup/patient/?keyword=' . $keyword . '&create_date=' . $create_date . '&followup_date=' . $followup_date . '&status=' . $status . '&gender=' . $gender . '&category_id=' . $category_id . '&created_by=' . $created_by);
            if ($this->input->get('page')) {
                $sgm = (int) trim($this->input->get('page'));
                $offset = $config['per_page'] * ($sgm - 1);
            } else {
                $offset = 0;
            }
            $config['total_rows'] = $this->patient->get_patient_list($config['per_page'], $offset, $keyword, $create_form_date, $create_to_date, $followup_form_date, $followup_to_date, $status, $gender, $category_id, $created_by, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->patient->get_patient_list($config['per_page'], $offset, $keyword, $create_form_date, $create_to_date, $followup_form_date, $followup_to_date, $status, $gender, $category_id, $created_by, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));

            $this->data['keyword'] = $keyword;
            $this->data['create_date'] = $create_date;
            $this->data['followup_date'] = $followup_date;
            $this->data['status'] = $status;
            $this->data['gender'] = $gender;
            $this->data['category_id'] = $category_id;
            $this->data['created_by'] = $created_by;
        } else {
            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = current_url();
            if ($this->input->get('page')) {
                $sgm = (int) trim($this->input->get('page'));
                $offset = $config['per_page'] * ($sgm - 1);
            } else {
                $offset = 0;
            }

            $config['total_rows'] = $this->patient->get_patient_list($config['per_page'], $offset, null, null, null, null, null, null, null, null, null, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['patients'] = $this->patient->get_patient_list($config['per_page'], $offset, null, null, null, null, null, null, null, null, null, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        }

        $this->data['employees'] = $this->patient->get_employee_list();
        $this->data['categories'] = $this->patient->get_list('followup_categories', array('status' => 1), '', '', '', 'sort_by', 'ASC');
        $this->data['list'] = TRUE;
        $this->layout->title($this->lang->line('manage_patient') . ' | ' . $this->global_setting->brand_title);
        $this->layout->view('patient/index', $this->data);
    }

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

        check_permission(ADD);

        if ($_POST) {

            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('category_id', $this->lang->line('category') . ' ' . $this->lang->line('name'), 'trim|required');
            $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');

            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');
                $data['note'] = $this->input->post('note');

                // 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['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->patient->get_custom_id('patients', '1');
                // create user
                $data['user_id'] = $this->patient->create_user();

                $insert_id = $this->patient->insert('patients', $data);

                $category = $this->patient->get_single('followup_categories', array('id' => $this->input->post('category_id')));

                $day = $category->day > 0 ? $category->day : 1;
                $followup_date = date('Y-m-d', strtotime(date('Y-m-d') . " + " . $day . " day"));

                if ($insert_id) {
                    $followup = $this->patient->insert('followup_patients', [
                        'category_id' => $this->input->post('category_id'),
                        'patient_id' => $data['user_id'],
                        'create_date' => date('Y-m-d'),
                        'followup_date' => $followup_date,
                        'note' => $data['note'],
                        'status' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => logged_in_user_id(),
                    ]);

                    // $this->patient->insert('followup_histories', [
                    //     'followup_id' => $followup,
                    //     'category_id' => $this->input->post('category_id'),
                    //     'patient_id' => $data['user_id'],
                    //     'create_date' => date('Y-m-d'),
                    //     'followup_date' => $followup_date,
                    //     'note' => $data['note'],
                    //     'status' => 1,
                    //     'created_at' => date('Y-m-d H:i:s'),
                    //     'created_by' => logged_in_user_id(),
                    // ]);
                    create_log('Has been created a patient : ' . $data['name']);
                }
                $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'), 'user_id' => $data['user_id']);
            } else {
                $this->data = $_POST;
                $msg = array(
                    'name' => form_error('name'),
                    'gender' => form_error('gender'),
                    'phone' => form_error('phone'),
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }

    /*****************Function search**********************************
     * @type            : Function
     * @function name   : search
     * @description     : Load Update "Patient search" user interface
     *                    with populate "Patient" value
     *                    and process to update "patient" into database
     * @param           : $id integer value
     * @return          : null
     * ********************************************************** */
    public function search()
    {
        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('search', $this->lang->line('search'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $search = $this->input->post('search');
                $patient = $this->patient->get_search_patient($search);
                $array = array('status' => 'success', 'message' => $this->lang->line('success'), 'patient' => $patient);
                echo json_encode($array);
            }
        }
    }

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

        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('category_id', $this->lang->line('category') . ' ' . $this->lang->line('name'), 'trim|required|callback_category');
            $this->form_validation->set_rules('patient_id', $this->lang->line('patient') . ' ' . $this->lang->line('id'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $category = $this->patient->get_single('followup_categories', array('id' => $this->input->post('category_id')));
                $day = $category->day > 0 ? $category->day : 1;

                $followup_date = date('Y-m-d', strtotime(date('Y-m-d') . " + " . $day . " day"));
                $followup = $this->patient->insert('followup_patients', [
                    'category_id' => $this->input->post('category_id'),
                    'patient_id' => $this->input->post('patient_id'),
                    'create_date' => date('Y-m-d'),
                    'followup_date' => $followup_date,
                    'note' => $this->input->post('note'),
                    'status' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => logged_in_user_id(),
                ]);

                // $this->patient->insert('followup_histories', [
                //     'followup_id' => $followup,
                //     'category_id' => $this->input->post('category_id'),
                //     'patient_id' => $this->input->post('patient_id'),
                //     'create_date' => date('Y-m-d'),
                //     'followup_date' => $followup_date,
                //     'note' => $this->input->post('note'),
                //     'status' => 1,
                //     'created_at' => date('Y-m-d H:i:s'),
                //     'created_by' => logged_in_user_id(),
                // ]);
                create_log('Has been created a patient');
                $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'));
            } else {
                $this->data = $_POST;
                $msg = array(
                    'category_id' => form_error('category_id'),
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }

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

        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('status', $this->lang->line('patient') . ' ' . $this->lang->line('status'), 'trim|required');
            $this->form_validation->set_rules('id', $this->lang->line('patient') . ' ' . $this->lang->line('id'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $data['note'] = $this->input->post('note');
                $data['status'] = $this->input->post('status') ? $this->input->post('status') : 0;
                $data['modified_at'] = date('Y-m-d H:i:s');
                $data['modified_by'] = logged_in_user_id();

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

                create_log('Has been created a followup_patients');
                $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'));
            } else {
                $this->data = $_POST;
                $msg = array(
                    'status' => form_error('status'),
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }



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

        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('followup_id', $this->lang->line('followup') . ' ' . $this->lang->line('id'), 'trim|required');
            $this->form_validation->set_rules('status', $this->lang->line('status'), 'trim|required');

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

                if ($this->input->post('status') == 1) {
                    $followup_patient = $this->patient->get_single('followup_patients', array('id' => $this->input->post('followup_id')));

                    $category = $this->patient->get_single('followup_categories', array('id' => $followup_patient->category_id));

                    $day = $category->day > 0 ? $category->day : 1;
                    $followup_date = date('Y-m-d', strtotime(date($followup_patient->followup_date) . " + " . $day . " day"));

                    $this->patient->insert('followup_histories', [
                        'followup_id' => $followup_patient->id,
                        'category_id' => $followup_patient->category_id,
                        'patient_id' => $followup_patient->patient_id,
                        'create_date' => date('Y-m-d'),
                        'followup_date' => $followup_date,
                        'note' => $this->input->post('note'),
                        'status' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => logged_in_user_id(),
                    ]);

                    $this->patient->update('followup_patients', array('followup_date' => $followup_date, 'modified_at' => date('Y-m-d H:i:s'), 'modified_by' => logged_in_user_id()), array('id' => $this->input->post('followup_id')));

                    create_log('Has been created a followup_patients');
                    $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'));
                } else {
                    $followup_patient = $this->patient->get_single('followup_patients', array('id' => $this->input->post('followup_id')));
                    $followup_historie = $this->patient->get_single('followup_histories', array('followup_id' => $this->input->post('followup_id'), 'category_id' => $followup_patient->category_id, 'patient_id' => $followup_patient->patient_id));

                    $this->patient->update('followup_patients', array('status' => 0, 'modified_at' => date('Y-m-d H:i:s'), 'modified_by' => logged_in_user_id()), array('id' => $this->input->post('followup_id')));
                    $this->patient->update('followup_histories', array('note' => $this->input->post('note'), 'modified_at' => date('Y-m-d H:i:s'), 'modified_by' => logged_in_user_id()), array('id' => $followup_historie->id));

                    create_log('Has been updated a followup_patients');
                    $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'));
                }
            } else {
                $this->data = $_POST;
                $msg = array(
                    'followup_id' => form_error('followup_id'),
                    'status' => form_error('status'),
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }


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

    public function get_single_patient()
    {
        $id = $this->input->post('id');
        $this->data['patient'] = $this->patient->get_single_patient($id);
        $this->data['doctor'] = $this->patient->get_last_visited_doctor($this->data['patient']->patient_id);
        $this->data['followup_histories'] = $this->patient->get_followup_histories($id);
        echo $this->load->view('patient/view', $this->data);
    }


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


    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Patient" 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('followup/patient');
        }

        $patient = $this->patient->get_single('followup_patients', array('id' => $id));

        if ($this->patient->delete('followup_patients', array('id' => $id))) {
            $this->patient->delete('followup_histories', array('followup_id' => $id));
            create_log('Has been deleted a Followup Patient : ' . $patient->category_id);
            success($this->lang->line('delete_success'));
        } else {
            error($this->lang->line('delete_failed'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
}
