<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Report_Model extends MY_Model {

    function __construct() {
        parent::__construct();
    }

    public function get_doctor_list() {
        $this->db->select('C.*, E.name, E.phone, E.user_id');
        $this->db->from('doctor_charges AS C');
        $this->db->join('employees AS E', 'E.user_id = C.doctor_id', 'left');
        $this->db->join('users AS U', 'U.id = E.user_id', 'left');
        $this->db->where('U.role_id', DOCTOR);
        $this->db->where('E.status', 1);
        $this->db->order_by('E.id', 'ASC');
        return $this->db->get()->result();
    }

    public function get_invoice_test_list($limit, $offset, $keyword, $form_date, $to_date, $doctor_id, $count) {
        $this->db->select('I.*, P.patient_unique_id, P.name as patient_name, P.phone, D.name as ref_by');
        $this->db->from('invoices AS I');
        $this->db->join('patients AS P', 'P.user_id = I.patient_id', 'left');
        $this->db->join('employees AS D', 'D.user_id = I.ref_dr_id', 'left');
        if ($keyword) {
            $this->db->group_start();
            $this->db->like('P.patient_unique_id', $keyword);
            $this->db->or_like('P.name', $keyword);
            $this->db->or_like('P.phone', $keyword);
            $this->db->or_like('I.custom_invoice_id', $keyword);
            $this->db->group_end();
        }
        if ($form_date && $to_date) {
            $this->db->where("DATE(I.bill_date) BETWEEN '$form_date' AND '$to_date'");
        }
        if ($doctor_id) {
            $this->db->where('I.ref_dr_id', $doctor_id);
        }
        $this->db->where('I.payment_status', 'complete');
        $this->db->order_by('I.id', 'DESC');
        if ($count) {
            return $this->db->count_all_results();
        } else {
            $this->db->limit($limit, $offset);
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                return $query->result();
            }
        }
        return array();
    }

    public function get_report_list($limit, $offset, $keyword, $form_date, $to_date, $doctor_id, $count) {
        $this->db->select('R.*, I.custom_invoice_id, I.bill_date, I.ref_dr_name, I.self, I.ref_dr_id, P.patient_unique_id, P.name as patient_name, P.phone, D.name as ref_by');
        $this->db->from('diagnostic_reports AS R');
        $this->db->join('patients AS P', 'P.user_id = R.patient_id', 'left');
        $this->db->join('invoices AS I', 'I.id = R.invoice_id', 'left');
        $this->db->join('employees AS D', 'D.user_id = I.ref_dr_id', 'left');
        if ($keyword) {
            $this->db->group_start();
            $this->db->like('P.patient_unique_id', $keyword);
            $this->db->or_like('P.name', $keyword);
            $this->db->or_like('P.phone', $keyword);
            $this->db->or_like('I.custom_invoice_id', $keyword);
            $this->db->group_end();
        }
        if ($form_date && $to_date) {
            $this->db->where("DATE(R.created_at) BETWEEN '$form_date' AND '$to_date'");
        }
        if ($doctor_id) {
            $this->db->where('I.ref_dr_id', $doctor_id);
        }
        //$this->db->where('R.template_status', 1);
        $this->db->where('R.sample_collect', 1);
        $this->db->group_by('R.invoice_id');
        $this->db->order_by('R.id', 'DESC');
        if ($count) {
            return $this->db->count_all_results();
        } else {
            $this->db->limit($limit, $offset);
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                return $query->result();
            }
        }
        return array();
    }

    public function get_test_list($invoice_id, $patient_id) {
        $this->db->select('ID.*, DT.name as test_name');
        $this->db->from('invoice_details AS ID');
        $this->db->join('diagnostic_tests AS DT', 'DT.id = ID.investagation_id', 'left');
        $this->db->join('invoices AS I', 'I.id = ID.invoice_id', 'left');
        $this->db->where('ID.invoice_id', $invoice_id);
      	
        $this->db->where('I.patient_id', $patient_id);
        $this->db->order_by('DT.id', 'ASC');
        return $this->db->get()->result();
    }

    public function get_sample_collect_list($invoice_id, $patient_id) {
        $this->db->select('DR.*, DT.name as test_name, T.name as template_name');
        $this->db->from('diagnostic_reports AS DR');
        $this->db->join('diagnostic_tests AS DT', 'DT.id = DR.investagation_id', 'left');
        $this->db->join('diagnostic_templates AS T', 'T.id = DR.template_id', 'left');
        $this->db->where('DR.invoice_id', $invoice_id);
        $this->db->where('DR.patient_id', $patient_id);
        $this->db->order_by('DT.id', 'ASC');
        return $this->db->get()->result();
    }

    public function get_invoice_by_test_list($invoice_id) {
        $this->db->select('ID.*, ID.investagation_id, D.name as department, D.id as department_id, G.name as group, DT.name as test_name, I.patient_id');
        $this->db->from('invoice_details AS ID');
        $this->db->join('diagnostic_tests AS DT', 'DT.id = ID.investagation_id', 'left');
        $this->db->join('diagnostic_departments AS D', 'D.id = DT.department_id', 'left');
        $this->db->join('diagnostic_groups AS G', 'G.id = DT.group_id', 'left');
        $this->db->join('invoices AS I', 'I.id = ID.invoice_id', 'left');
        $this->db->where('ID.invoice_id', $invoice_id);
        // if ($this->session->userdata('role_id') == PATHOLOGIST) {
        //     $this->db->where('D.id', 1);
        // }
        // if ($this->session->userdata('role_id') == RADIOLOGIST) {
        //     $this->db->where('D.id', 2);
        // }
      	$this->db->where_in('D.id', 1,6,10);
        $this->db->order_by('DT.id', 'ASC');
        return $this->db->get()->result();
    }

    public function get_invoice_by_report_list($invoice_id) {
        $this->db->select('DR.*, DR.id as report_id, DT.name as test_name, T.name as template_name');
        $this->db->from('diagnostic_reports AS DR');
        $this->db->join('diagnostic_tests AS DT', 'DT.id = DR.investagation_id', 'left');
        $this->db->join('diagnostic_templates AS T', 'T.id = DR.template_id', 'left');
        $this->db->where('DR.invoice_id', $invoice_id);
        // if ($this->session->userdata('role_id') == PATHOLOGIST) {
        //     $this->db->where('DR.department_id', 1);
        // }
        // if ($this->session->userdata('role_id') == RADIOLOGIST) {
        //     $this->db->where('DR.department_id', 2);
        // }
        $this->db->where('DR.template_status', '1');
        $this->db->order_by('DR.id', 'ASC');
        return $this->db->get()->result();
    }

    public function get_print_report($report_id) {
        $this->db->select('DR.*, DR.note as remark, DR.modified_at, DT.name as dtname, T.name as tname, T.specimen, G.name as group, P.created_at as createdpatient, P.patient_unique_id, P.name as patient, P.dob, P.gender, P.phone as mobile, I.created_at as billcreate, I.custom_invoice_id, I.ref_dr_id, I.ref_dr_name, I.self, E.name as doctor, E.specialist');
        $this->db->from('diagnostic_reports AS DR');
        $this->db->join('diagnostic_templates AS DT', 'DT.id = DR.template_id', 'left');
        $this->db->join('diagnostic_tests AS T', 'T.id = DR.investagation_id', 'left');
      	$this->db->join('diagnostic_groups AS G', 'G.id = T.group_id', 'left');
        $this->db->join('patients AS P', 'P.user_id = DR.patient_id', 'left');
        $this->db->join('invoices AS I', 'I.id = DR.invoice_id', 'left');
        $this->db->join('employees AS E', 'E.user_id = I.ref_dr_id', 'left');
        $this->db->where('DR.id ', $report_id);
        return $this->db->get()->row();
    }

    public function get_templates_by_investigation_ids($investigation_ids) {
        $this->db->select('t.*, d.name as department, g.name as group, dt.name as test_name');
        $this->db->from('diagnostic_tests_template t');
        $this->db->join('diagnostic_departments d', 'd.id = t.department_id', 'left');
        $this->db->join('diagnostic_groups g', 'g.id = t.group_id', 'left');
        $this->db->join('diagnostic_tests dt', 'dt.id = t.test_id', 'left');
        $this->db->where_in('t.test_id', $investigation_ids);
        $this->db->where('t.status', 1);
        $this->db->order_by('t.sort_by', 'ASC');
        return $this->db->get()->result();
    }

    public function get_result_options($test_id) {
        $this->db->select('O.*');
        $this->db->from('diagnostic_tests_option O');
        $this->db->join('diagnostic_tests_template T', 'T.test_id = O.test_id', 'inner');
        $this->db->where('O.test_id', $test_id);
        $this->db->where('O.status', 1);
        $this->db->group_by('O.id');
        $query = $this->db->get();
        return $query->result();
    }

    /*****************Function save_test_result**********************************
     * @type            : Function
     * @function name   : save_test_result
     * @description     : Save test result to diagnostic_tests_result table
     *
     * @param           : $data array
     * @return          : boolean
     * ********************************************************** */
    public function save_test_result($data) {
        // Check if record already exists
        $existing = $this->db->get_where('diagnostic_tests_result', array(
            'invoice_id' => $data['invoice_id'],
            'template_id' => $data['template_id']
        ))->row();
        
        if ($existing) {
            // Update existing record
            return $this->db->update('diagnostic_tests_result', $data, array(
                'invoice_id' => $data['invoice_id'],
                'template_id' => $data['template_id']
            ));
        } else {
            // Insert new record
            return $this->db->insert('diagnostic_tests_result', $data);
        }
    }

    /*****************Function check_test_result_exists**********************************
     * @type            : Function
     * @function name   : check_test_result_exists
     * @description     : Check if test result exists for given test and invoice
     *
     * @param           : $invoice_id, $test_id
     * @return          : boolean
     * ********************************************************** */
    public function check_test_result_exists($invoice_id, $test_id) {
        // First get the template ID for this test
        $template = $this->db->get_where('diagnostic_tests_template', array(
            'test_id' => $test_id,
            'status' => 1
        ))->row();
        
        if (!$template) {
            return false;
        }
        
        // Then check if result exists for this template
        $result = $this->db->get_where('diagnostic_tests_result', array(
            'invoice_id' => $invoice_id,
            'template_id' => $template->id,
            'status' => 1
        ))->row();
        
        return !empty($result);
    }

    /*****************Function get_template_id_by_test**********************************
     * @type            : Function
     * @function name   : get_template_id_by_test
     * @description     : Get template ID for a given test ID
     *
     * @param           : $test_id
     * @return          : int or null
     * ********************************************************** */
    public function get_template_id_by_test($test_id) {
        $template = $this->db->get_where('diagnostic_tests_template', array(
            'test_id' => $test_id,
            'status' => 1
        ))->row();
        
        return $template ? $template->id : null;
    }
}