<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Enums\UtilEnum;
use App\Helpers\Helpers;
use App\Http\Resources\HeadingItemResource;
use App\Http\Resources\SampleTestResource;
use App\Http\Resources\UserResource;
use App\Models\Antibiotic;
use App\Models\BaseModel;
use App\Models\Comment;
use App\Models\Department;
use App\Models\District;
use App\Models\Organism;
use App\Models\PatientType;
use App\Models\Quantity;
use App\Models\RejectComment;
use App\Models\Sample;
use App\Models\SampleType;
use App\Models\TestSample;
use App\Models\TestSampleOrganism;
use App\Models\UserLabCover;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use function Illuminate\Auth\user;

class UtilController extends Controller
{
    protected $organismModel;
    protected $antibioticModel;
    protected $sampleTypeModel;
    protected $departmentModel;
    protected $rejectCommentModel;
    protected $testSampleModel;
    protected $sampleModel;
    protected $labUserModel;
    protected $patientTypeModel;

    protected $testSampleOrganismModel;

    private $baseLabId;
    protected $base;

    public function __construct(
        Organism $organismModel, Antibiotic $antibioticModel, RejectComment $rejectCommentModel, UserLabCover $labUserModel,
        SampleType $sampleTypeModel, Department $departmentModel, TestSample $testSampleModel, Sample $sampleModel,
        PatientType $patientTypeModel, TestSampleOrganism $testSampleOrganism
    ){
        $this->organismModel = $organismModel;
        $this->antibioticModel = $antibioticModel;
        $this->sampleTypeModel = $sampleTypeModel;
        $this->departmentModel = $departmentModel;
        $this->rejectCommentModel = $rejectCommentModel;
        $this->testSampleModel = $testSampleModel;
        $this->sampleModel = $sampleModel;
        $this->labUserModel = $labUserModel;
        $this->patientTypeModel = $patientTypeModel;

        $this->testSampleOrganismModel = $testSampleOrganism;

        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    function province($responseType = 'object')
    {
        $provinces = parent::province();
        return $responseType == 'object' ? $provinces : json_encode($provinces); // TODO: Change the autogenerated stub
    }



    function district($responseType = 'object' ,$province_id = null)
    {
        $districts = parent::district($province_id);
        return $responseType == 'object' ? $districts : response()->json($districts); // TODO: Change the autogenerated stub
    }

    public function commune($responseType = 'object', $district_id = null)
    {
        $communes = parent::commune($district_id);
        return $responseType == 'object' ? $communes : json_encode($communes); // TODO: Change the autogenerated stub
    }

    public function village($responseType = 'object', $commune_id = null)
    {
        $villages = parent::village($commune_id);
        return $responseType == 'object' ? $villages : json_encode($villages); // TODO: Change the autogenerated stub
    }

    public function location()
    {
        return parent::location(); // TODO: Change the autogenerated stub
    }

    public function generatePatientUuId($responseType = 'object'){
        try{
            $location = (object) $this->location();
            $uuid = Helpers::generateUuId($location->short_name);
            return response()->json(['success'=> true , 'data' => array('uuid' => $uuid)]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    public function generateUuIdForManual($responseType, $manual_code){
        try{
            $location = (object) $this->location();
            $uuid = Helpers::generateUuIdForManual($location->short_name, $manual_code);
            return response()->json(['success'=> true , 'data' => array('uuid' => $uuid)]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    public function getDepartment(){
        try{
            $department = $this->departmentModel::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'lab_id' => $this->baseLabId])->orderBy('weight','asc')->get();
            return response()->json(['success'=> true , 'data' => $department]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'errors' => [$e->getMessage()]]);
        }
    }

     public function getDepartmentByLabId($labId){
        try{
            $department = $this->departmentModel::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'lab_id' => $labId])->orderBy('weight','asc')->get();
            return response()->json(['success'=> true , 'data' => $department]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'errors' => [$e->getMessage()]]);
        }
    }

    public function getSampleTypeByDepartment($departmentId=0){
        try{
            if($departmentId == 0) return response()->json(['success'=> true , 'data' => []]);
            $sampleType = $this->sampleTypeModel::query()->where('record_status_id', RecordStatusEnum::ACTIVE)->where('department_id', $departmentId)->get();
            return response()->json(['success'=> true , 'data' => $sampleType]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'errors' => [$e->getMessage()]]);
        }
    }

    public function getAntibiotic(Request $request, $responseType = 'object')
    {
        $antibiotics = $this->antibioticModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(isset($request->name) && $request->name !='', function ($organisms) use($request) {
                $organisms->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->name)."%'");
            })->orderBy('name_en', 'asc')->get();
        return $responseType == 'object' ? $antibiotics : json_encode($antibiotics);
    }

    public function getOrganisms($responseType = 'object', Request $request)
    {
        $organisms = $this->organismModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(isset($request->name) && $request->name !='', function ($organisms) use($request) {
                $organisms->whereRaw("replace(name_en, ' ','') like '".str_replace(" ","",$request->name)."%'");
            })->orderBy('name_en', 'asc')->limit(40)->get();
        return $responseType == 'object' ? $organisms : json_encode($organisms);
    }

    public function storeRejectComment(Request $request){
        try{
            $validator = \Validator::make($request->all(), ['name_en' => 'required']);
            if ($validator->fails()) return response()->json(['errors'=>$validator->errors()->all()]);
            $rejectComment = $this->rejectCommentModel::query()->create([
                'sample_condition_id' => 3,
                'reject_comment' => $request->name_en,
                'lab_id' => $this->baseLabId
            ]);
            return response()->json(['success'=> true , 'data' => [$rejectComment]]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'errors' => [$e->getMessage()]]);
        }
    }

    function getTestItem(){
        try{
            $departments = $this->departmentModel::with(['samples','samples.testSamples.test','samples.testSamples.childTest'])
                ->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->orderBy('weight', 'asc')->get();
            return response()->json(['success'=> true , 'data' => SampleTestResource::collection($departments)]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    function getLabUsers(){
        return $this->labUserModel::with('user')->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get();
    }


    function getTestItemBySampleId($sampleId, $previousId = 0){
        try{
            $data = $this->sampleModel::with(['entryBy','modifiedBy','sample_tests', 'physician', 'patient','sample_source'])->where(['id' => $sampleId, 'lab_id' => $this->baseLabId])->get()->first();
            $arrData = array();
            $arrData['result_comment'] = [];
            $arrData['sample'] = array(
                'sample_number' => $data->sample_number,
                'requested_by' => $data->physician,
                'patient_name' => $data->patient->name_en,
                'patient_uuid' => $data->patient->patient_uuid,
                'sample_source' => $data->sample_source->name_en,
                'sample_id' => $data->id
            );

            $arrData['sample_users'] = array('creator' => $data->entryBy->name, 'modifier' => @$data->modifiedBy->name);
            $arrData['result_users'] = [];
            $arrData['performers'] = UserResource::collection($this->getLabUsers()->pluck('user'));

            $arrData['antibiotic_results'] = $this->getOrgAntibioticResult($sampleId);

            $resultItems = DB::select('
                                            SELECT
                                                p.gender,
                                                p.dob,
                                                d.`id` AS department_id,
                                                d.`name_en` AS department_name,
                                                d.weight as dweight,
                                                st.`id` AS sample_type_id,
                                                st.weight as sweight,
                                                st.`name_en` AS sample_type,
                                                ts.`id` AS test_sample_id,
                                                ts.`heading_id` AS parent_id,
                                                ts.`field_type`,
                                                ts.formula,
                                                ts.format,
                                                ts.`usd_price`,
                                                ts.group_result,
                                                ts.description,
                                                t.`id` AS test_id,
                                                t.`name_en` AS test_name,
                                                ts.unit_sign AS unit_sign,
						                        ifnull(tr.test_result,"") as test_result,
						                        tr.is_show,
						                        tr.performed_by,
						                        tr.id as test_result_id,
						                        pct.`commission_type`,
						                        ifnull(pct.`commission_rate`, 0.00) as commission_rate,
						                        ifnull(pct.`partner_price`, 0.00) as partner_price,
						                        ts.weight,
						                        tr.test_date,
						                        tr.comment,
						                        ifnull(prev_r.test_result,"") as prev_result,
						                        ts.is_bold,
						                        ts.autocomplete_bind,
						                        ts.lab_id,
						                        sd.sample_descr
                                            FROM samples s
                                            INNER JOIN patients p
                                            ON p.id = s.patient_id AND p.lab_id = s.lab_id
                                            INNER JOIN test_results tr
                                            ON tr.`sample_id` = s.`id`
                                            AND s.`lab_id` = tr.`lab_id`
                                            INNER JOIN test_samples ts
                                            ON ts.id = tr.`test_sample_id`
                                            and ts.lab_id = tr.lab_id
                                            INNER JOIN tests t
                                            ON t.`id` = ts.`test_id`
                                            INNER JOIN sample_types st
                                            ON st.`id` = ts.`sample_type_id`
                                            INNER JOIN departments d
                                            ON d.`id` = st.`department_id`
                                            LEFT JOIN `physician_commisssion` AS pct
                                            ON pct.`test_sample_id` =  ts.`id`
                                            AND pct.`physician_id` = s.`physician_id`

                                            LEFT JOIN sample_details sd ON sd.sample_id = s.id AND sd.sample_type_id = st.id

                                            LEFT JOIN (
                                                SELECT
                                                    tr.`test_sample_id`,
                                                    tr.`test_result`
                                                FROM samples s
                                                INNER JOIN test_results tr
                                                ON tr.`sample_id` = s.`id`
                                                WHERE s.id = '.$previousId.'
                                                AND s.`lab_id` = '.$this->baseLabId.'
                                                AND tr.record_status_id = 1
                                            ) prev_r
                                            ON prev_r.test_sample_id = tr.`test_sample_id`

                                            WHERE s.`id` = '.$sampleId.'
                                            AND s.`lab_id`= '.$this->baseLabId.'
                                            and ts.lab_id = '.$this->baseLabId.'
                                            AND tr.`record_status_id` = '.BaseModel::RECORD_STATUS_ACTIVE.'

                                            ORDER BY
                                            d.`weight`,
                                            st.`weight`,
                                            ts.`weight`');
            $departmentArray = array();



            $sampleTypeIds = collect($resultItems)->pluck('sample_type_id')->unique()->values();

            $allTestSampleIds = collect($resultItems)->pluck('test_sample_id')->unique()->toArray();

            if(count($sampleTypeIds)>0) {
                $refComment = collect($this->getRefCommentV2($sampleTypeIds));
                $testSampleIds = collect($resultItems)->whereIn('field_type', [2, 3])->pluck('test_sample_id')->unique()->toArray();
                if(count($testSampleIds)>0){
                     $suggestedOrgResults = collect($this->getTestSampleOrganismV2($testSampleIds));
                }
                $testResultIds = collect($resultItems)->whereIn('field_type', [2, 3])->pluck('test_result_id')->unique()->toArray();
                if(count($testResultIds)>0){
                    $organismResults = collect($this->getOrganismResultV2($testResultIds));
                    $previousOrganismResults = collect($this->getPreviousOrganismResult($previousId));
                }
                $refCollection = collect($this->mapReferenceRangeV2($allTestSampleIds));
            }



            $discount_type = ((object) $this->location())->discount_type;

            foreach ($resultItems as $row){
                $departmentArray[$row->dweight]['department_id'] = $row->department_id;
                $departmentArray[$row->dweight]['department_name'] = $row->department_name;
                $departmentArray[$row->dweight]['samples'][$row->sweight]['sample_type_id'] = $row->sample_type_id;
                $departmentArray[$row->dweight]['samples'][$row->sweight]['sample_type_name'] = $row->sample_type;
                $departmentArray[$row->dweight]['samples'][$row->sweight]['sample_descr'] = (string)$row->sample_descr !=''? '('.$row->sample_descr.')' : '';

                $departmentArray[$row->dweight]['samples'][$row->sweight]['comments'] = $refComment->where('sample_type_id', $row->sample_type_id)->values();// (object) $this->getRefComment($row->sample_type_id);

                $organismResult = [];
                $suggestedOrgResult = [];

                $previousOrganismResult = [];

                if(in_array($row->field_type, [2,3])) {
                    $organismResult = $organismResults->where('test_result_id', $row->test_result_id)->values();// $this->getOrganismResult($row->test_result_id);
                    $suggestedOrgResult = $suggestedOrgResults->where('test_sample_id', $row->test_sample_id)->values();// $this->getTestSampleOrganism($row->test_sample_id);
                    $previousOrganismResult = $previousOrganismResults->where('test_sample_id', $row->test_sample_id)->values();
                }

                $refRanges =(object) $this->evaluateRefRanges( $refCollection->where('test_sample_id',$row->test_sample_id)->values()->toArray(), $row->gender, $row->dob); // (object) $this->mapReferenceRange($row->test_sample_id, $row->gender, $row->dob);



                $testItemArray = array(
                    'id' => (string)$row->test_sample_id,
                    'test_id' => $row->test_id,
                    'test_name' => $row->test_name,
                    'closed_parent_id' => (string) (int)$row->parent_id,
                    'field_type' => (string) $row->field_type,
                    'unit_sign' => (string) $row->unit_sign,
                    'usd_price' => $row->usd_price,
                    'min_ref_val' => isset($refRanges->minimum) ? $refRanges->minimum :'',
                    'max_ref_val' => isset($refRanges->maximum) ? $refRanges->maximum: '',
                    'org_ref_range' => $refRanges,
                    'ref_range' =>(isset($refRanges->sign) && in_array($refRanges->sign,["0.00","0.0","0"]) && isset($refRanges->minimum) && $refRanges->minimum==0 && isset($refRanges->maximum) && $refRanges->maximum==0) ? $refRanges->minimum . ' - ' . $refRanges->maximum : ((isset($refRanges->minimum)) ? in_array($refRanges->sign, ['<','<=','Neg <', 'Neg<','≤']) ? $refRanges->sign.' '.$refRanges->maximum : (in_array($refRanges->sign, ['>','>=','≥']) ? $refRanges->sign. ' '. (($refRanges->minimum == 0)? $refRanges->maximum:$refRanges->minimum) : ((isset($refRanges->minimum)) ? ($refRanges->minimum==0 && $refRanges->maximum==0 ? '' : $refRanges->minimum)   .' '. $refRanges->sign .' '. ($refRanges->maximum==0? '':$refRanges->maximum) : '')) : ''),
                    //'ref_range' =>(isset($refRanges->sign) && in_array($refRanges->sign,["0.00","0.0","0"]) && isset($refRanges->minimum) && $refRanges->minimum==0 && isset($refRanges->maximum) && $refRanges->maximum==0) ? $refRanges->minimum . ' - ' . $refRanges->maximum : ((isset($refRanges->minimum)) ? in_array($refRanges->sign, ['<','<=','Neg <', 'Neg<','≤']) ? $refRanges->sign.' '.$refRanges->maximum : (in_array($refRanges->sign, ['>','>=']) ? $refRanges->sign. ' '.$refRanges->minimum : ((isset($refRanges->minimum)) ? ($refRanges->minimum==0 && $refRanges->maximum==0 ? '' : $refRanges->minimum)   .' '. $refRanges->sign .' '. ($refRanges->maximum==0? '':$refRanges->maximum) : '')) : ''),
                    //'ref_range' => ((isset($refRanges->minimum)) ? in_array($refRanges->sign, ['<','<=','Neg <', 'Neg<','≤']) ? $refRanges->sign.' '.$refRanges->maximum : (in_array($refRanges->sign, ['>','>=']) ? $refRanges->sign. ' '.$refRanges->minimum : ((isset($refRanges->minimum)) ? ($refRanges->minimum==0 && $refRanges->maximum==0 ? '' : $refRanges->minimum)   .' '. $refRanges->sign .' '. ($refRanges->maximum==0? '':$refRanges->maximum) : '')) : ''),
                    'test_result' => !is_null($row->format) && $row->format>=0 && is_numeric($row->test_result) ? number_format($row->test_result,$row->format,'.','') : $row->test_result,
                    'prev_result' => (string)!is_null($row->format) && is_numeric($row->prev_result) ? number_format($row->prev_result,$row->format) : $row->prev_result,
                    'sign' => isset($refRanges->sign) ? $refRanges->sign: '',
                    'is_show' => $row->is_show,
                    'performed_by' => $row->performed_by,
                    'org_results' => $organismResult,
                    'prev_org_results' => $previousOrganismResult,
                    'org_suggested_results' => $suggestedOrgResult,
                    'group_result' => (string) $row->group_result,
                    'commission_type' => (!empty($row->commission_type) ? $row->commission_type : $discount_type),
                    'commission_rate' => $row->commission_rate,
                    'partner_price' => $row->partner_price,
                    'description' => (string) nl2br($row->description),
                    'formula' => (string) $row->formula,
                    'order' => (int) $row->weight,
                    'test_date' => (string) $row->test_date,
                    'comment' => (string) nl2br($row->comment),
                    'str_comment' => (string) $row->comment,
                    'is_bold' => (int) $row->is_bold,
                    'autocomplete_bind' => (int) $row->autocomplete_bind,
                    'ts' => $row->test_result,
                    'lab_id' => $row->lab_id,
                    'format' => (int)$row->format
                );
                $departmentArray[$row->dweight]['samples'][$row->sweight]['tests'][] = $testItemArray;
            }


            $arrData['sample_tests'] = $departmentArray;
            return response()->json(['success'=> true , 'data' => $arrData]);
        } catch (\Exception $e){
            Log::error($e);
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    function getRefCommentV2($sampleTypeIds){
        return Comment::query()->select('sample_type_id', 'comment_desc as name')->where(
            [
                BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE,
                'lab_id' => $this->baseLabId
            ])->whereIn('sample_type_id', $sampleTypeIds)->get()->toArray();
    }

    function getTestSampleOrganismV2($testSampleIds){
        $resultItems = DB::select('
                                        SELECT
                                            ts.id as test_sample_id,
                                            tsr.id AS test_organism_id,
                                            o.id as organism_id,
                                            o.`name_en` AS organism_name,
                                            o.is_bold,
                                            tsr.is_default
                                        FROM `test_samples` AS ts
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = ts.id
                                        INNER JOIN organisms o
                                        ON o.id = tsr.`organism_id`
                                        WHERE ts.`id` in('. implode(',',$testSampleIds) . ')
                                        AND tsr.record_status_id = 1
                                        AND ts.record_status_id = 1 and tsr.is_default=1');
        return $resultItems;
    }

    function getOrganismResultV2($testResultIds){
        $resultItems = DB::select('
                                        SELECT
                                            ogr.test_result_id,
                                            tsr.id AS test_organism_id,
                                            ogr.organism_id,
                                            ogr.quantity_id,
                                            ogr.contaminant,
                                            o.`name_en` AS organism_name,
                                            o.is_bold,
                                            qt.`quantity_name`,
                                            ogr.id
                                        FROM `organism_results` AS ogr
                                        INNER JOIN test_results trs
                                        ON trs.id = ogr.test_result_id and ogr.lab_id = trs.lab_id
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = trs.test_sample_id
                                        AND tsr.`organism_id` = ogr.`organism_id`
                                        INNER JOIN organisms o
                                        ON o.id = ogr.`organism_id`
                                        LEFT JOIN `quantities` qt
                                        ON qt.id = ogr.`quantity_id`
                                        WHERE ogr.`test_result_id` in('.implode(',', $testResultIds). ')
                                        AND ogr.record_status_id = 1
                                        AND trs.record_status_id = 1
                                        AND tsr.record_status_id = 1');
        return $resultItems;
    }

    function getPreviousOrganismResult($previousSampleId){
        $resultItems = DB::select('
                                        SELECT
                                            trs.test_sample_id,
                                            ogr.test_result_id,
                                            tsr.id AS test_organism_id,
                                            ogr.organism_id,
                                            ogr.quantity_id,
                                            ogr.contaminant,
                                            o.`name_en` AS organism_name,
                                            o.is_bold,
                                            qt.`quantity_name`,
                                            ogr.id
                                        FROM `organism_results` AS ogr
                                        INNER JOIN test_results trs
                                        ON trs.id = ogr.test_result_id and ogr.lab_id = trs.lab_id
                                        INNER JOIN samples s
                                        ON s.id = trs.sample_id
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = trs.test_sample_id
                                        AND tsr.`organism_id` = ogr.`organism_id`
                                        INNER JOIN organisms o
                                        ON o.id = ogr.`organism_id`
                                        LEFT JOIN `quantities` qt
                                        ON qt.id = ogr.`quantity_id`
                                        WHERE s.id = '.$previousSampleId.'
                                        AND s.`lab_id` = '.$this->baseLabId.'
                                        AND ogr.record_status_id = 1
                                        AND trs.record_status_id = 1
                                        AND tsr.record_status_id = 1');
        return $resultItems;
    }

    function getRefComment($sampleTypeId ){
        return Comment::query()->select('comment_desc as name')->where(
            [
                BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE,
                'lab_id' => $this->baseLabId,
                'sample_type_id' => $sampleTypeId
            ])->get();
    }

    function mapReferenceRange($testSampleId, $genderId, $patientDob){

        $referenceRanges = DB::select('
                            SELECT
                                (IF(pt.range_start=0, 1, pt.range_start) * pt.range_start_unit) + IF(pt.range_start_unit=\'>\', 1, 0) AS start_range_in_day,
                                (IF(pt.range_end=0, 1, pt.range_end) * pt.range_end_unit) + IF(pt.range_end_sign=\'<=\', 1, 0) AS end_range_in_day,
                                pt.gender,
                                pt.range_start,
                                pt.range_start_unit,
                                pt.range_start_sign,
                                pt.range_end,
                                pt.range_end_unit,
                                pt.range_end_sign,
                                tnv.test_sample_id,
                                tnv.sign,
                                ts.format,
                                tnv.`minimum` AS minimum,
                                tnv.`maximum` AS maximum
                            FROM test_normal_values tnv
                            INNER JOIN patient_types pt
                            ON pt.id = tnv.patient_type_id
                            INNER JOIN test_samples ts
                            ON ts.id = tnv.test_sample_id
                            WHERE tnv.record_status_id = 1
                            AND test_sample_id = '.$testSampleId.'
        ');

        $now = time(); // or your date as well
        $your_date = strtotime($patientDob);
        $patientAgeInDay = round(($now - $your_date)/ (60 * 60 * 24));
        $referenceRangeArray = array();
        foreach ($referenceRanges as $referenceRange){
            if((int)$patientAgeInDay >= (int)$referenceRange->start_range_in_day && (int)$patientAgeInDay <= (int)$referenceRange->end_range_in_day){
                // Log::info($patientAgeInDay . ' - '.$genderId);
                if($referenceRange->gender == $genderId){
                    //  Log::info('geneder=gender');
                    $referenceRangeArray = array(
                        'sign' => $referenceRange->sign,
                        'minimum' => !is_null($referenceRange->format) ? number_format($referenceRange->minimum,$referenceRange->format) : (fmod($referenceRange->minimum,1) == 0 ? number_format($referenceRange->minimum,0):number_format($referenceRange->minimum,2)),
                        'maximum' => !is_null($referenceRange->format) ? number_format($referenceRange->maximum,$referenceRange->format) : (fmod($referenceRange->maximum,1) == 0 ? number_format($referenceRange->maximum,0):number_format($referenceRange->maximum,2)),
                    ); break;
                }
                else{
                    if($referenceRange->gender==3) {
                        $referenceRangeArray = array(
                            'sign' => $referenceRange->sign,
                            'minimum' => !is_null($referenceRange->format) ? number_format($referenceRange->minimum,$referenceRange->format) : (fmod($referenceRange->minimum,1) == 0 ? number_format($referenceRange->minimum,0):number_format($referenceRange->minimum,2)),
                            'maximum' => !is_null($referenceRange->format) ? number_format($referenceRange->maximum,$referenceRange->format) : (fmod($referenceRange->maximum,1) == 0 ? number_format($referenceRange->maximum,0):number_format($referenceRange->maximum,2)),
                        ); break;
                    }
                    // }
                }
            }
        }
        return $referenceRangeArray;
    }

    function getTestSampleOrganism($testSampleId){
        $resultItems = DB::select('
                                        SELECT
                                            ts.id as test_sample_id,
                                            tsr.id AS test_organism_id,
                                            o.id as organism_id,
                                            o.`name_en` AS organism_name,
                                            o.is_bold,
                                            tsr.is_default
                                        FROM `test_samples` AS ts
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = ts.id
                                        INNER JOIN organisms o
                                        ON o.id = tsr.`organism_id`
                                        WHERE ts.`id` = '.$testSampleId. '
                                        AND tsr.record_status_id = 1
                                        AND ts.record_status_id = 1');
        return $resultItems;
    }

    function getOrganismResult($testResultId){
        $resultItems = DB::select('
                                        SELECT
                                            ogr.test_result_id,
                                            tsr.id AS test_organism_id,
                                            ogr.organism_id,
                                            ogr.quantity_id,
                                            ogr.contaminant,
                                            o.`name_en` AS organism_name,
                                            o.is_bold,
                                            qt.`quantity_name`,
                                            ogr.id
                                        FROM `organism_results` AS ogr
                                        INNER JOIN test_results trs
                                        ON trs.id = ogr.test_result_id and ogr.lab_id = trs.lab_id
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = trs.test_sample_id
                                        AND tsr.`organism_id` = ogr.`organism_id`
                                        INNER JOIN organisms o
                                        ON o.id = ogr.`organism_id`
                                        LEFT JOIN `quantities` qt
                                        ON qt.id = ogr.`quantity_id`
                                        WHERE ogr.`test_result_id` = '.$testResultId. '
                                        AND ogr.record_status_id = 1
                                        AND trs.record_status_id = 1
                                        AND tsr.record_status_id = 1');
        return $resultItems;
    }

    function getOrgAntibioticResult($sampleId){
        $resultItems = DB::select('
                                        SELECT
                                            ogr.test_result_id,
                                            tsr.id AS test_organism_id,
                                            ogr.organism_id,
                                            agr.antibiotic_id,
                                            agr.disk_diffusion,
                                            agr.mic,
                                            agr.sensitive,
                                            agr.is_hide,
                                            att.name_en
                                        FROM `organism_results` AS ogr
                                        INNER JOIN `antibiogram_results` agr
                                        ON agr.`organism_result_id` = ogr.`id`
                                        INNER JOIN `antibiotics` att
                                        ON att.id = agr.antibiotic_id
                                        INNER JOIN test_results trs
                                        ON trs.id = ogr.test_result_id
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = trs.test_sample_id
                                        AND tsr.`organism_id` = ogr.`organism_id`
                                        WHERE trs.`sample_id` = '.$sampleId.'
                                        AND agr.`record_status_id` = 1
                                        AND ogr.record_status_id = 1
                                        AND trs.record_status_id = 1
                                        AND tsr.record_status_id = 1
                                        order by agr.sensitive desc');
        return $resultItems;
    }

    function getTestSampleItems($sampleTypeId = null, $fieldType=""){

        try{
            $headingItems = $this->testSampleModel::with(['test'])
                ->where([
                    'lab_id' => $this->baseLabId,
                    BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE
                ])->when(!empty($sampleTypeId), function ($headingItems) use($sampleTypeId) {
                    $headingItems->where('sample_type_id', $sampleTypeId);
                })->when($fieldType !="", function ($query) use($fieldType){
                    $query->where('field_type', $fieldType);
                })->get();
            return response()->json(['success'=> true , 'data' => HeadingItemResource::collection($headingItems)]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    function getTestSampleBySampleType($sampleTypeId){
        try{
            $headingItems = $this->testSampleModel::with(['test'])
                ->where([
                    BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE,
                    'sample_type_id' => $sampleTypeId
                ])->get();
            return response()->json(['success'=> true , 'data' => HeadingItemResource::collection($headingItems)]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    public function getPatientTypes(){
        try{
            $patientTypes = $this->patientTypeModel::query()->where([ BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get();
            return response()->json(['success'=> true , 'data' => $patientTypes]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    public function getPhysicianCommission($testSampleId){
        try {
            $test = $this->testSampleModel::with(['test'])->find($testSampleId);
            $testCommissions = DB::select('
                        SELECT
                            p.id,
                            p.name_en,
                            ifnull(comm.commission_type, '.((object)$this->location())->discount_type.') as commission_type,
                            ifnull(comm.commission_rate, 0.00) as commission_rate,
                            ifnull(comm.partner_price, 0.00) as partner_price
                        FROM physicians p
                        LEFT JOIN(
                            SELECT
                                pc.`physician_id`,
                                pc.`commission_type`,
                                pc.`commission_rate`,
                                pc.partner_price,
                                pc.`test_sample_id`
                            FROM `physician_commisssion` pc
                            INNER JOIN physicians p
                            ON p.`id` = pc.`physician_id`
                            WHERE p.`lab_id` = '.$this->baseLabId.'
                            AND p.`record_status_id` = 1
                            AND pc.test_sample_id = '.$testSampleId.'
                            AND pc.`record_status_id` = 1
                        ) comm
                        ON comm.physician_id = p.`id`
                        WHERE p.`lab_id` = '.$this->baseLabId.'
                        AND p.`record_status_id` = 1
            ');
            $data = array('test_name' => $test->test->name_en, 'physicians' => $testCommissions);
            return response()->json(['success'=> true , 'data' => $data]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }









    /****** */



    function mapReferenceRangeV2($testSampleIds)
    {
        try{
        $referenceRanges = DB::select('
                            SELECT
                                ts.id as test_sample_id,
                                (IF(pt.range_start=0, 1, pt.range_start) * pt.range_start_unit) + IF(pt.range_start_unit=\'>\', 1, 0) AS start_range_in_day,
                                (IF(pt.range_end=0, 1, pt.range_end) * pt.range_end_unit) + IF(pt.range_end_sign=\'<=\', 1, 0) AS end_range_in_day,
                                pt.gender,
                                pt.range_start,
                                pt.range_start_unit,
                                pt.range_start_sign,
                                pt.range_end,
                                pt.range_end_unit,
                                pt.range_end_sign,
                                tnv.test_sample_id,
                                tnv.sign,
                                ts.format,
                                tnv.`minimum` AS minimum,
                                tnv.`maximum` AS maximum
                            FROM test_normal_values tnv
                            INNER JOIN patient_types pt
                            ON pt.id = tnv.patient_type_id
                            INNER JOIN test_samples ts
                            ON ts.id = tnv.test_sample_id
                            WHERE tnv.record_status_id = 1
                            AND test_sample_id in('. implode(',',$testSampleIds) . ')
        ');
        return $referenceRanges;
        } catch(\Exception $e)
        {
            dd($e);
            return false;
        }
    }

    function evaluateRefRanges($referenceRanges, $genderId, $patientDob){
        $now = time();
        $your_date = strtotime($patientDob);
        $patientAgeInDay = round(($now - $your_date)/ (60 * 60 * 24));
        $referenceRangeArray = array();
        foreach ($referenceRanges as $referenceRange){
            if((int)$patientAgeInDay >= (int)$referenceRange->start_range_in_day && (int)$patientAgeInDay <= (int)$referenceRange->end_range_in_day){
                if($referenceRange->gender == $genderId){
                    $referenceRangeArray = array(
                        'sign' => $referenceRange->sign,
                        'minimum' => !is_null($referenceRange->format) ? number_format($referenceRange->minimum,$referenceRange->format) : (fmod($referenceRange->minimum,1) == 0 ? number_format($referenceRange->minimum,0):number_format($referenceRange->minimum,2)),
                        'maximum' => !is_null($referenceRange->format) ? number_format($referenceRange->maximum,$referenceRange->format) : (fmod($referenceRange->maximum,1) == 0 ? number_format($referenceRange->maximum,0):number_format($referenceRange->maximum,2)),
                    ); break;
                }
                else{
                    if($referenceRange->gender==3) {
                        $referenceRangeArray = array(
                            'sign' => $referenceRange->sign,
                            'minimum' => !is_null($referenceRange->format) ? number_format($referenceRange->minimum,$referenceRange->format) : (fmod($referenceRange->minimum,1) == 0 ? number_format($referenceRange->minimum,0):number_format($referenceRange->minimum,2)),
                            'maximum' => !is_null($referenceRange->format) ? number_format($referenceRange->maximum,$referenceRange->format) : (fmod($referenceRange->maximum,1) == 0 ? number_format($referenceRange->maximum,0):number_format($referenceRange->maximum,2)),
                        ); break;
                    }
                }
            }
        }
        return $referenceRangeArray;
    }



    public function getTestSampleOrganisms($testSampleId, $sampleId){


        $test = $this->testSampleModel::with('test')->find($testSampleId);
        $defVal = count($this->getSelectedOrganismResult($sampleId, $testSampleId)) ==0 ? [-1] : $this->getSelectedOrganismResult($sampleId, $testSampleId);
        $testSampleOrganisms = $this->testSampleOrganismModel::with(['organism'])
            ->where(['test_sample_id' => $testSampleId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'lab_id' => $this->baseLabId])
            ->limit(10)->get()->map(function ($data) use ($defVal) {
                $data['selected'] = in_array($data['id'], $defVal) ? 1: 0;
                    return $data;
                })->toArray();

        $qualities = Quantity::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->select(['id','quantity_name as name'])->get()->toArray();
        $antibiotics = collect(Antibiotic::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->select(['id','name_en'])->get()->toArray());
        $resultKeyed = collect($this->getOrgAntibioticResult($sampleId))->groupBy('organism_id');

        $testSampleOrganisms = collect($testSampleOrganisms)->map(function ($item) use ($resultKeyed, $antibiotics) {
            $match = $resultKeyed->get($item['organism_id']);
            return [
                'id' => $item['id'],
                'test_sample_id' => $item['test_sample_id'],
                'organism_id' => $item['organism_id'],
                'lab_id' => $item['lab_id'],
                'record_status_id' => $item['record_status_id'],
                'selected' => $item['selected'],
                'organism' => $item['organism'],
                'antibiotics' => collect($antibiotics)->map(function ($item_) use ($match) {
                    $match = $match?->groupBy('antibiotic_id')->get($item_['id'])?->first();
                    return [
                        'id' => $item_['id'],
                        'name_en' => $item_['name_en'],
                        'antibiotic_item' => $item_,
                        'antibiotic_result' => $match ? [
                            'sensitive' => $match?->sensitive,
                            'mic' => $match?->mic,
                            'disk_diffusion' => $match?->disk_diffusion,
                            'is_hide' => $match?->is_hide,
                            'organism_id' => $match?->organism_id,
                            'test_organism_id' => $match?->test_organism_id,
                            'test_result_id' => $match?->test_result_id
                        ] : null
                    ];
                })
            ];
        })->toArray();

        return response()->json(['success'=> true , 'test' =>$test, 'data' => array_unique($testSampleOrganisms, SORT_REGULAR),'qualities' => $qualities]);
    }


    public function getTestSampleOrganismsByName(Request $request){
        $test = $this->testSampleModel::with('test')->find($request->test_sample_id);
        $defVal = count($this->getSelectedOrganismResult($request->sample_id, $request->test_sample_id)) ==0 ? [-1] : $this->getSelectedOrganismResult($request->sample_id, $request->test_sample_id);
        $selectedOrganisms = $this->testSampleOrganismModel::with(['organism','antibiotics.antibioticResult','antibiotics.antibioticItem'])
            ->where(['test_sample_id' => $request->test_sample_id, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'lab_id' => $this->baseLabId])
            ->whereIn('id', $defVal)->get()->map(function ($data) {
                $data['selected'] = 1;
                    return $data;
                })->toArray();

        $testSampleOrganisms = $this->testSampleOrganismModel::with(['organism','antibiotics.antibioticResult','antibiotics.antibioticItem'])
            ->where(['test_sample_id' => $request->test_sample_id, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'lab_id' => $this->baseLabId])
            ->when(!empty(trim($request->name)), function ($testSampleOrganisms) use($request){
                $testSampleOrganisms->whereIn('organism_id', $this->organismModel::query()->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->name)."%'")->pluck('id')->toArray());
            })->whereNotIn('id', $defVal)
            ->limit(10)->get()->map(function ($data) {
                $data['selected'] = 0;
                    return $data;
                })->toArray();
        $qualities = Quantity::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->select(['id','quantity_name as name'])->get()->toArray();
        return response()->json(['success'=> true , 'test' =>$test, 'data' => array_unique(array_merge($selectedOrganisms, $testSampleOrganisms), SORT_REGULAR), 'qualities' => $qualities, 'selected_org' => $this->getSelectedOrganismResultQty($request->sample_id, $request->test_sample_id)]);
    }


    function getSelectedOrganismResult($sampleId, $testSampleId){
        $resultItems = DB::select('
                                        SELECT
                                            tsr.id AS test_organism_id
                                        FROM `organism_results` AS ogr
                                        INNER JOIN test_results trs
                                        ON trs.id = ogr.test_result_id
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = trs.test_sample_id
                                        AND tsr.`organism_id` = ogr.`organism_id`
                                        INNER JOIN organisms o
                                        ON o.id = ogr.`organism_id`
                                        LEFT JOIN `quantities` qt
                                        ON qt.id = ogr.`quantity_id`
                                        WHERE trs.sample_id = '.$sampleId.'
                                        and trs.test_sample_id ='.$testSampleId.'
                                        AND ogr.record_status_id = 1
                                        AND trs.record_status_id = 1
                                        AND tsr.record_status_id = 1');
        $data = collect($resultItems)->pluck('test_organism_id')->toArray();
        return $data;
    }

     function getSelectedOrganismResultQty($sampleId, $testSampleId){
        $resultItems = DB::select('
                                        SELECT
                                            tsr.id AS test_organism_id,
                                            ogr.quantity_id
                                        FROM `organism_results` AS ogr
                                        INNER JOIN test_results trs
                                        ON trs.id = ogr.test_result_id
                                        INNER JOIN `test_sample_organisms` tsr
                                        ON tsr.test_sample_id = trs.test_sample_id
                                        AND tsr.`organism_id` = ogr.`organism_id`
                                        INNER JOIN organisms o
                                        ON o.id = ogr.`organism_id`
                                        LEFT JOIN `quantities` qt
                                        ON qt.id = ogr.`quantity_id`
                                        WHERE trs.sample_id = '.$sampleId.'
                                        and trs.test_sample_id ='.$testSampleId.'
                                        AND ogr.record_status_id = 1
                                        AND trs.record_status_id = 1
                                        AND tsr.record_status_id = 1');
        $data = collect($resultItems)->toArray();
        return $data;
    }


}
