<?php

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

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

class Report extends MY_Controller {

    public $data = array();

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

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

        check_permission(VIEW);

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

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('diagnostic/report/?keyword=' . $keyword . '&date=' . $date . '&doctor_id=' . $doctor_id);

            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->report->get_report_list($config['per_page'], $offset, $keyword, $form_date, $to_date, $doctor_id, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['reports'] = $this->report->get_report_list($config['per_page'], $offset, $keyword, $form_date, $to_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['doctor_id'] = $doctor_id;
        } 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->report->get_report_list($config['per_page'], $offset, null, date('Y-m-d'), date('Y-m-d'), null, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['reports'] = $this->report->get_report_list($config['per_page'], $offset, null, date('Y-m-d'), date('Y-m-d'), null, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        }

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

    /*****************Function create**********************************
     * @type            : Function
     * @function name   : create
     * @description     : Load "Create Report" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function create() {

        check_permission(ADD);

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

            $config = array();
            $config = get_pagination(ADMIN_PER_PAGE);
            $config['base_url'] = site_url('diagnostic/report/create/?keyword=' . $keyword . '&date=' . $date . '&doctor_id=' . $doctor_id);

            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->report->get_invoice_test_list($config['per_page'], $offset, $keyword, $form_date, $to_date, $doctor_id, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['invoices'] = $this->report->get_invoice_test_list($config['per_page'], $offset, $keyword, $form_date, $to_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['doctor_id'] = $doctor_id;
        } 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->report->get_invoice_test_list($config['per_page'], $offset, null, date('Y-m-d'), date('Y-m-d'), null, $count = TRUE);
            $this->pagination->initialize($config);
            $this->data['invoices'] = $this->report->get_invoice_test_list($config['per_page'], $offset, null, date('Y-m-d'), date('Y-m-d'), null, $count = FALSE);
            $this->data['sl_count'] = ($this->input->get('page') == 0 ? 1 : (($this->input->get('page') - 1) * $config["per_page"] + 1));
        }

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

    /*****************Function generate**********************************
     * @type            : Function
     * @function name   : generate
     * @description     : Load "Generate Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function generate($invoice_id) {
        check_permission(VIEW);
        $this->data['tests'] = $this->report->get_invoice_by_test_list($invoice_id);
        $this->data['reports'] = $this->report->get_invoice_by_report_list($invoice_id);

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

    /*****************Function sample_collect**********************************
     * @type            : Function
     * @function name   : sample_collect
     * @description     : Load "Sample Collect Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function sample_collect() {

        check_permission(ADD);

        if ($_POST) {
            $patient_id = $this->input->post('patient_id');
            $invoice_id = $this->input->post('invoice_id');
            if (!empty($_POST['sample_collect'])) {
                foreach ($_POST['sample_collect'] as $key => $value) {
                    $report = $this->report->get_single('diagnostic_reports', array('patient_id' => $patient_id, 'invoice_id' => $invoice_id, 'investagation_id' =>  $_POST['investagation_id'][$value]));
                    if ($report) {
                        $data['patient_id'] =  $patient_id;
                        $data['invoice_id'] =  $invoice_id;
                        $data['department_id'] = $_POST['department_id'][$value];
                        $data['investagation_id'] = $_POST['investagation_id'][$value];
                        $data['sample_collect'] = $_POST['sample_collect'] ? 1 : 0;

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

                        $this->report->update('diagnostic_reports', $data, array('patient_id' => $patient_id, 'invoice_id' => $invoice_id, 'investagation_id' =>  $value));
                        create_log('Has been created sample collect: Patient ID => ' . $patient_id . ', invoice_id => ' . $invoice_id);
                        success($this->lang->line('update_success'));
                    } else {
                        $data['custom_report_id'] = get_custom_invoice('diagnostic_reports', 'R');
                        $data['patient_id'] =  $patient_id;
                        $data['invoice_id'] =  $invoice_id;
                        $data['department_id'] = $_POST['department_id'][$value];
                        $data['investagation_id'] = $_POST['investagation_id'][$value];
                        $data['template_status'] = 0;
                        $data['sample_collect'] = $_POST['sample_collect'] ? 1 : 0;
                        $data['source'] = 1;

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

                        $this->report->insert('diagnostic_reports', $data);
                        create_log('Has been created sample collect: Patient ID => ' . $patient_id . ', invoice_id => ' . $invoice_id);
                        success($this->lang->line('insert_success'));
                    }
                }
            }
            redirect($_SERVER['HTTP_REFERER']);
        }
    }

    /*****************Function getReport**********************************
     * @type            : Function
     * @function name   : getReport
     * @description     : Load "Get Single Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function getReport() {
        $report_id = $this->input->post('report_id');
        $report = $this->report->get_single('diagnostic_reports', array('id' => $report_id));
        echo json_encode($report);
    }

    /*****************Function template**********************************
     * @type            : Function
     * @function name   : template
     * @description     : Load "Get Template" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */
    public function template() {
        $template_id = $this->input->post('template_id');
        $template = $this->report->get_single('diagnostic_templates', array('id' => $template_id));
        echo json_encode($template);
    }

    /*****************Function generateReport**********************************
     * @type            : Function
     * @function name   : generateReport
     * @description     : Load "Generate Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function generateReport() {
        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('template_id', $this->lang->line('template') . ' ' . $this->lang->line('name'), 'trim|required');
            $this->form_validation->set_rules('template', $this->lang->line('template'), 'trim|required');

            if ($this->form_validation->run() === TRUE) {
                $template = $this->report->get_single('diagnostic_reports', array('id' => $this->input->post('report_id')));

                if ($template) {
                    $update = array(
                        'template_id' => $this->input->post('template_id'),
                        'template' => $this->input->post('template'),
                        'note' => $this->input->post('note'),
                        'template_status' => 1,
                        'delivery_status' => 1,
                        'modified_at' => date('Y-m-d H:i:s'),
                        'modified_by' => logged_in_user_id()
                    );
                    $updated_id = $this->report->update('diagnostic_reports', $update, array('id' => $this->input->post('report_id')));
                    if ($updated_id) {
                        create_log('Has been updated a report : ID= ' . $template->id . ', invoice_id = ' . $template->invoice_id);
                    }
                    $array = array('status' => 'success', 'message' => $this->lang->line('update_success'), 'report_id' => $this->input->post('report_id'));
                } else {
                    $insert = array(
                        'template_id' => $this->input->post('template_id'),
                        'template' => $this->input->post('template'),
                        'note' => $this->input->post('note'),
                        'template_status' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => logged_in_user_id()
                    );
                    $insert_id = $this->report->insert('diagnostic_reports', $insert);

                    if ($insert_id) {
                        create_log('Has been created a report : ID= ' . $this->input->post('report_id'));
                    }
                    $array = array('status' => 'success', 'message' => $this->lang->line('insert_success'), 'report_id' => $this->input->post('report_id'));
                }
            } else {
                $msg = array(
                    'template_id' => form_error('template_id'),
                    'template' => form_error('template'),
                );
                $array = array('status' => 'failed', 'error' => $msg);
            }
            echo json_encode($array);
        }
    }

    /*****************Function view**********************************
     * @type            : Function
     * @function name   : view
     * @description     : Load "View Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function view($invoice_id) {
        check_permission(VIEW);
        $this->data['tests'] = $this->report->get_invoice_by_test_list($invoice_id);
        $this->data['reports'] = $this->report->get_invoice_by_report_list($invoice_id);

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

    /*****************Function single**********************************
     * @type            : Function
     * @function name   : single
     * @description     : Load "Single Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function single() {
        check_permission(VIEW);

        $this->data["template"] = $this->report->get_print_report($this->uri->segment(4, 0));
        $this->data["signature_1"] = $this->report->get_single('diagnostic_laboratorists', array('status' => 1, 'sort_by' => 1, 'department_id' => $this->data["template"]->department_id), '', '', '', 'id', 'ASC');
        $this->data["signature_2"] = $this->report->get_single('diagnostic_laboratorists', array('status' => 1, 'sort_by' => 2, 'department_id' => $this->data["template"]->department_id), '', '', '', 'id', 'ASC');
        $this->data["signature_3"] = $this->report->get_single('diagnostic_laboratorists', array('status' => 1, 'sort_by' => 3, 'department_id' => $this->data["template"]->department_id), '', '', '', 'id', 'ASC');

        //$this->data["signature_count"] = $this->report->count_all('diagnostic_laboratorists', array('status' => 1, 'department_id' => $this->data["template"]->department_id), '', '', '', 'sort_by', 'ASC');
        $this->data["created_by"] = $this->report->get_single('employees', array('status' => 1, 'user_id' => $this->data["template"]->created_by));

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

    /*****************Function print**********************************
     * @type            : Function
     * @function name   : print
     * @description     : Load "Print Report List" user interface
     *
     * @param           : null
     * @return          : null
     * ********************************************************** */

    public function print() {
        check_permission(VIEW);

        $this->data["template"] = $this->report->get_print_report($this->input->post("report_id"));
        $this->data["signature_1"] = $this->report->get_single('diagnostic_laboratorists', array('status' => 1, 'sort_by' => 1, 'department_id' => $this->data["template"]->department_id), '', '', '', 'id', 'ASC');
        $this->data["signature_2"] = $this->report->get_single('diagnostic_laboratorists', array('status' => 1, 'sort_by' => 2, 'department_id' => $this->data["template"]->department_id), '', '', '', 'id', 'ASC');
        $this->data["signature_3"] = $this->report->get_single('diagnostic_laboratorists', array('status' => 1, 'sort_by' => 3, 'department_id' => $this->data["template"]->department_id), '', '', '', 'id', 'ASC');

        //$this->data["signatures"] = $this->report->get_list('diagnostic_laboratorists', array('status' => 1, 'department_id' => $this->data["template"]->department_id), '', '', '', 'sort_by', 'ASC');
        //$this->data["signature_count"] = $this->report->count_all('diagnostic_laboratorists', array('status' => 1, 'department_id' => $this->data["template"]->department_id), '', '', '', 'sort_by', 'ASC');
        $this->load->view('diagnostic/report/print', $this->data);
    }

    /*****************Function delete**********************************
     * @type            : Function
     * @function name   : delete
     * @description     : delete "Report List" 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('diagnostic/report');
        }

        $report = $this->report->get_single('diagnostic_reports', array('id' => $id));

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