<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Resources\SampleTestResource;
use App\Models\BaseModel;
use App\Models\Comment;
use App\Models\Department;
use App\Models\LabConfigure;
use App\Models\Laboratory;
use App\Models\Patient;
use App\Models\Physician;
use App\Models\SampleSource;
use App\Models\Sample;
use App\Models\SampleDetail;
use App\Models\TestGroup;
use App\Models\TestGroupDetail;
use App\Models\TestResult;
use App\Models\Province;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShareController extends Controller
{
    protected $patientModel;
    protected $base;
    protected $physicianModel;
    protected $sampleModel;
    protected $laboratoryConfigures;
    protected $testResultModel;
    protected $testGroupModel;
    protected $departmentModel;
    protected $sampleDetailModel;
    protected $testGroupDetailModel;


    function __construct()
    {
        $this->patientModel = new Patient();
        $this->physicianModel = new Physician();
        $this->sampleModel = new Sample();
        $this->testResultModel = new TestResult();
        $this->laboratoryConfigures = new LabConfigure();
        $this->testGroupModel = new TestGroup();
        $this->departmentModel = new Department();
        $this->sampleDetailModel = new SampleDetail();
        $this->testGroupDetailModel = new TestGroupDetail();
    }

    public function index($id){
        $sample = Sample::with(['patient','invoice'])->where(['id' => $id])->first();
        $labSettings = Laboratory::query()->find($sample->lab_id);
        $samplePhysician = Physician::query()->where('id', $sample->physician_id)->first();
        $labConfigures = $this->laboratoryConfigures::query()->where(['lab_id' => $sample->lab_id, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get()->toArray();


        $preview_form_id = ($labSettings->lab_category_id==0? 1:2);

        $resultTemplateId = (collect($labConfigures)->where('atrribute_code', 'RESULT_TEMPLATE')->pluck('assigned_attribute_value')->first());
        if(!empty($resultTemplateId)){
            $preview_form_id = $resultTemplateId;
        }

        if($sample->result_template_id > 0){
            $preview_form_id = $sample->result_template_id;
        }

        return view('shared.test_result', [
            'sample' => $sample,
            'preview_result_id' => $preview_form_id,
            'labSettings' =>$labSettings,
            'samplePhysician' => $samplePhysician,
            'labConfigures' => $labConfigures,
            'firstPrvSampleId' => (int)@$this->getPreviousSample($sample->patient_id, $id)->first()->id,
            'firstPrvSampleDate' => (string) !empty($this->getPreviousSample($sample->patient_id, $id)->first()) ? date('d-m-Y', strtotime($this->getPreviousSample($sample->patient_id, $id)->first()->admission_date)) : '',
        ]);
    }

    function getTestItemBySampleId($sampleId, $previousId = 0){
        try{
            $data = Sample::with(['entryBy','modifiedBy','sample_tests', 'physician'])->where(['id' => $sampleId])->get()->first();
            $arrData = array();
            $arrData['result_comment'] = [];
            $arrData['sample'] = array(
                'sample_number' => $data->sample_number,
                'collected_date' => date('d-M-Y H:i', strtotime($data->collected_date)),
                'received_date' => date('d-M-Y H:i', strtotime($data->received_date)),
                'requested_by' => $data->physician
            );
            $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.`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,
                                                -- IF(ts.`field_type` = 2, \'Signle\', IF(ts.`field_type`=3,\'Multiple\', ts.unit_sign)) AS unit_sign,
                                                ts.unit_sign AS unit_sign,
                                                -- tnv.`minimum` as minimum,
						                        -- tnv.`maximum` as maximum,
						                        ifnull(tr.test_result,"") as test_result,
						                        ifnull(prev_r.test_result,"") as prev_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,
						                        ts.is_bold,
						                        ts.lab_id,
						                        tr.test_date,
						                        tr.comment,
						                        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`
                                            /*AND t.`lab_id` = ts.`lab_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 tr.record_status_id = 1
                                            ) prev_r
                                            ON prev_r.test_sample_id = tr.`test_sample_id`

                                            WHERE s.`id` = '.$sampleId.'
                                            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();
            $refComment = collect($this->getRefCommentV2($sampleTypeIds));

            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->sample_type_id]['sample_type_id'] = $row->sample_type_id;
                $departmentArray[$row->dweight]['samples'][$row->sample_type_id]['sample_type_name'] = $row->sample_type;
                $departmentArray[$row->dweight]['samples'][$row->sample_type_id]['sample_descr'] = (string)$row->sample_descr !=''? '('.$row->sample_descr.')' : '';


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

                $organismResult = [];
                if(in_array($row->field_type, [2,3])) {
                    $organismResult = $this->getOrganismResult($row->test_result_id);
                }


                $refRanges = (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: '',
                    'ref_range' => (isset($refRanges->minimum) /*&& !empty($refRanges->minimum)*/) ? in_array($refRanges->sign, ['<','<=','Neg <', 'Neg<']) ? $refRanges->sign.' '.$refRanges->maximum : (in_array($refRanges->sign, ['>','>=']) ? $refRanges->sign. ' '.$refRanges->minimum : ((isset($refRanges->minimum) /*&& !empty($refRanges->minimum)*/) ? $refRanges->minimum   .' '. $refRanges->sign .' '. $refRanges->maximum : '')) : '',
                    //'ref_range' => ((isset($refRanges->minimum) && !empty($refRanges->minimum)) ? $refRanges->minimum   .' '. $refRanges->sign .' '. $refRanges->maximum : ''),
                    'test_result' => !is_null($row->format) && 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,
                    'group_result' => (string) $row->group_result,
                    'commission_type' => NULL,
                    '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,
                    'ts' => $row->test_result,
                    'lab_id' => $row->lab_id,
                    'format' => (int)$row->format
                );
                //dd($testItemArray);
                $departmentArray[$row->dweight]['samples'][$row->sample_type_id]['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
            ])->whereIn('sample_type_id', $sampleTypeIds)->get()->toArray();
    }

    function getOrgAntibioticResult($sampleId){
        $resultItems = DB::select('
                                        SELECT
                                            ogr.test_result_id,
                                            tsr.id AS test_organism_id,
                                            ogr.organism_id,
                                            att.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 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
                                        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 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;
    }


    /**
     * New Implementation for Patient Profile
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */

    public function startAnonymousSession($hashLabId){
        $this->base = Laboratory::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->where('allow_external_request', 1)
            ->whereRaw('MD5(id)="'.$hashLabId.'"')->first();
          $provinces = Province::where('id','<>', 25)->orderBy('name_kh')->get();
            if(empty($this->base)) return view('errors.404');
        return view('shared.anonymous_login', ['labSettings' => (object) $this->base, 'provinces' => $provinces ]);
    }

    public function searchPatientToSelect2(Request $request, $labId){
        $patients = [];
        if(!empty(trim($request->term))){
        $patients = $this->patientModel::query()
            ->where(['record_status_id' => 1, 'lab_id' => $labId])
            //->whereRaw('MD5(lab_id)="'.$hashLabId.'"')
            ->when(!empty(trim($request->term)), function ($patients) use($request){
                $patients->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->term)."%'");
                //->orWhereRaw("replace(phone_number, ' ','') like '%".str_replace(" ","",$request->term)."%'");
            })->limit(3)->orderBy('name_en', 'asc')->get();
        }
        $items = $patients->map(function ($item){
            return array('id'=>$item->id, 'text' => $item->name_en . ' : '.$item->phone_number . ', '.($item->gender==1 ? 'M' : 'F').', '.(date('Y') - date('Y',strtotime($item->dob))));
        });
        return response()->json(['results' => $items]);
    }

    public function searchPatientPhoneToSelect2(Request $request, $labId){
        $patients = [];
        if(!empty(trim($request->term))){
        $patients = $this->patientModel::query()
            ->where(['record_status_id' => 1, 'lab_id' => $labId])
            ->when(!empty(trim($request->term)), function ($patients) use($request){
                $patients->whereRaw("replace(phone_number, ' ','') like '%".str_replace(" ","",$request->term)."%'");
            })->limit(3)->orderBy('phone_number', 'asc')->get();
        }
        $items = [];
        if(count($patients)>0) {
            $items = $patients->map(function ($item){
                return array('id'=>$item->phone_number, 'text' => $item->name_en . ' : '.$item->phone_number . ', '.($item->gender==1 ? 'M' : 'F').', '.(date('Y') - date('Y',strtotime($item->dob))));
            });
            }
        return response()->json(['results' => $items]);
    }

    public function anonymousRegister(Request $request, $hashLabId){
        DB::beginTransaction();
        try{
            $dob = $request->dob;
			$patient_name=strtoupper($request->name_en);
            $datePart = explode("-",$dob);
            $phoneNumber = $request->phone_number;// preg_replace('/ /i', '', trim($request->phone_number));
            if($datePart[1]>12){
            	$dob =  $datePart[1].'-'.$datePart[0].'-'.$datePart[2];
            }
            $requests = collect($request)->merge([
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => '1',
                'record_status_id' => 1
            ])->replace([
                    'dob' => date('Y-m-d', strtotime($dob)),
                    'phone_number' => $phoneNumber,
					'name_en'=> $patient_name
                ]);

            $patientNumber = $this->generateAutoId(date('Y-m-d'), $request->short_name, $request->lab_id);
            $requests = $requests->merge(['patient_uuid' => $patientNumber]);
            $patient = $this->patientModel::query()->create($requests->all());
            DB::commit();

            $request->session()->put('anonymous_id', $patient->id);
            $request->session()->put('base_lab_id', $patient->lab_id);
            if ($request->session()->has('anonymous_id')) {
                return redirect(url('customer/'.$hashLabId.'?request-test'));
            }

        } catch (\Exception $e){
            dd($e);
            DB::rollBack();
            Log::error($e);
            return response()->json(['success'=> false , 'message' => __('patient.create_fail') , 'errors' => $e->getMessage()]);
        }
    }

    public function generateAutoId($admissionDate, $labShortName, $labId){
        $prefix = date('y',strtotime($admissionDate));
        $patientCount = $this->patientModel::query()->where('lab_id', $labId)->whereRaw('year(created_at) ="'. date('Y',strtotime($admissionDate)).'"')->count();
        if($labId==34) $patientCount = $patientCount+5; // solve problem when delete patient
        return 'P-'.$labShortName.'-'.$prefix.'-'.(str_pad(($patientCount+1),5,'0',STR_PAD_LEFT));
    }

    public function anonymousLogin(Request $request, $hashLabId){
        if(empty($request->patient_id) && empty($request->phone_number)) {
            session()->flash('message', 'មិនមានលេខនេះនៅក្នុងប្រព័ន្ធយើងខ្ញុំទេ');
            return redirect()->back();
        }
        $pattern = '/ /i';
        $phoneNumber = $request->phone_number;// preg_replace($pattern, '', trim($request->phone_number));
        $patient = $this->patientModel::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->whereRaw('MD5(lab_id)="'.$hashLabId.'"')
            ->when(!empty($request->phone_number) && empty($request->patient_id), function($patient) use($request){
                 $patient->whereRaw("replace(phone_number, ' ','') = '".str_replace(" ","",$request->phone_number)."'");
            })->when(!empty($request->patient_id), function($patient) use($request){
                $patient->where('id', $request->patient_id);
            })->first();
            //->where('phone_number', $phoneNumber)->first();
        if(empty($patient)){
            session()->flash('message', 'មិនមានលេខនេះនៅក្នុងប្រព័ន្ធយើងខ្ញុំទេ');
            return redirect()->back();
        }
        else{
            $request->session()->put('anonymous_id', $patient->id);
            $request->session()->put('base_lab_id', $patient->lab_id);
            if ($request->session()->has('anonymous_id')) {
                return redirect(url('customer/'.$hashLabId));
            }
        }
    }

    public function anonymousLogOut(Request $request, $hashLabId){
        if ($request->session()->has('anonymous_id')) {
            $request->session()->forget('anonymous_id');
            $request->session()->forget('base_lab_id');
            return redirect(url('anonymous/'.$hashLabId));
        }
    }

    public function profile(Request $request, $hashLabId)
    {
        if (!$request->session()->has('anonymous_id')) {
            return redirect(url('anonymous/'.$hashLabId));
        }
        $patient = $this->patientModel::query()
            ->where(['id' => $request->session()->get('anonymous_id'), BaseModel::RECORD_STATUS_FIELD => BaseModel::RECORD_STATUS_ACTIVE])
            ->whereRaw('MD5(lab_id)="'.$hashLabId.'"')->first();
        $this->base = Laboratory::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->whereRaw('MD5(id)="'.$hashLabId.'"')->first();
        $samples = $this->sampleModel::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->where('patient_id', $request->session()->get('anonymous_id'))
            ->whereRaw('MD5(lab_id)="'.$hashLabId.'"')->orderBy(BaseModel::CREATED_AT_FIELD,'desc')->paginate(5);
        $testGroups = $this->testGroupModel::with(['testGroupDetails'])->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereRaw('MD5(lab_id)="'.$hashLabId.'"')->orderBy('created_at')->get();
        $physicians = $this->physicianModel::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereRaw('MD5(lab_id)="'.$hashLabId.'"')->orderBy('name_en')->get();
        return view('shared.patient_profile',
            [
                'patient' => $patient,
                'samples' => $samples,
                'labSettings' => (object) $this->base,
                'testGroups' => $testGroups,
                'physicians' => $physicians
            ]);
    }

    function getPreviousSample($patientId, $curSampleId){
        return $this->sampleModel::query()->where(['patient_id' => $patientId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->where('id','<', $curSampleId)->orderBy('id', 'desc')->get(['id','admission_date']);
    }

    public function viewLabResult(Request $request, $hashLabId, $hashSampleId){
        if (!$request->session()->has('anonymous_id')) {
            return redirect(url('anonymous/'.$hashLabId));
        }
        $sample = $this->sampleModel::with(['patient','invoice'])->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
        ->whereRaw('MD5(lab_id)="'.$hashLabId.'" AND MD5(id)="'.$hashSampleId.'"')->first();
        $this->base = Laboratory::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->whereRaw('MD5(id)="'.$hashLabId.'"')->first();
        $labConfigures = $this->laboratoryConfigures::query()
            ->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereRaw('MD5(id)="'.$hashLabId.'"')
            ->get()->toArray();
        $samplePhysician = $this->physicianModel::query()->where('id', $sample->physician_id)->first();


        return view('shared.preview_result',
            [
                'sample' => $sample,
                'sample_id' => $sample->id,
                'labSettings' => (object) $this->base,
                'labConfigures' => $labConfigures,
                'samplePhysician' => $samplePhysician
            ]);
    }

    public function cloneRequestedLabServices(Request $request, $hashLabId, $hashSampleId){
        if (!$request->session()->has('anonymous_id')) {
            return redirect(url('anonymous/'.$hashLabId));
        }
        DB::beginTransaction();
        try{
            $sample = $this->sampleModel::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
                ->whereRaw('MD5(lab_id)="'.$hashLabId.'" AND MD5(id)="'.$hashSampleId.'"')->first();

            $requestedSample = [];
            if(!empty($sample)){
                $reSampleArray = array(
                    'patient_id' => $sample->patient_id,
                    'sample_number' => $this->generateSampleNumber($sample->lab_id, date('Y-m-d H:i:s')),
                    'admission_date' => date('Y-m-d H:i:s'),
                    'sample_source_id' => $sample->sample_source_id,
                    'physician_id' => $sample->physician_id,
                    'requested_date' => date('Y-m-d H:i:s'),
                    'collected_date' => date('Y-m-d H:i:s'),
                    'is_accept_request' => 0,
                    'lab_id' => $sample->lab_id,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => $sample->patient_id,
                );

                $requestedSample = $this->sampleModel::query()->create($reSampleArray);
                $previousTests = $this->testResultModel::query()->where([
                    BaseModel::RECORD_STATUS_FIELD => BaseModel::RECORD_STATUS_ACTIVE,
                    'sample_id' => $sample->id,
                    'lab_id' => $sample->lab_id
                ])->get();
                if(!empty($requestedSample) && !empty($previousTests)){
                    $items = [];
                    foreach ($previousTests as $previousItem){
                        $items[] = array(
                            'sample_id' => $requestedSample->id,
                            'test_sample_id' => $previousItem->test_sample_id,
                            'test_result' => NULL,
                            'created_at' => date('Y-m-d H:i:s'),
                            'created_by' => $sample->patient_id,
                            'lab_id' => $previousItem->lab_id
                        );
                    }
                    $this->testResultModel::query()->insert($items);
                }
            }
            DB::commit();
            return response()->json(['success'=> true , 'message' => __('ប្រតិបត្តិការបានសម្រេច'), 'data' => $requestedSample]);
        } catch (\Exception $e){
            DB::rollBack();
            return response()->json(['success'=> false , 'message' => __('ប្រតិបត្តិការមិនបានសម្រេច'), 'errors' => [$e->getMessage()]]);
        }
    }

    public function generateSampleNumber($labId, $admissionDate){
        $this->base = Laboratory::query()->where(BaseModel::RECORD_STATUS_FIELD, BaseModel::RECORD_STATUS_ACTIVE)
            ->where('id', $labId)->first();
        $prefix = date('ymd',strtotime($admissionDate));
        $sample = Sample::query();
        $sampleCount = $sample->where('lab_id', $labId)->whereRaw('date(admission_date) ="'. date('Y-m-d',strtotime($admissionDate)).'"')->count();
        return 'S-'.$this->base['short_name'].'-'.$prefix.'-'.(str_pad(($sampleCount+1),3,'0',STR_PAD_LEFT));
    }


    function getTestItem(Request $request){
        try{
            $departments = $this->departmentModel::with(['samples','samples.testSamples.test','samples.testSamples.childTest'])
                ->where(['lab_id' => $request->session()->get('base_lab_id'), 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()]);
        }
    }

    /** Request Test */

    public function storeSampleDetail(Request $sampleCreateRequest){

        set_time_limit(6000);
        ini_set('memory_limit', '10240M');
        DB::beginTransaction();
        try{

            $labId = $sampleCreateRequest->session()->get('base_lab_id');
            $patientId = $sampleCreateRequest->session()->get('anonymous_id');

            $sampleSourceId = SampleSource::where(['lab_id' => $labId, 'is_default' => 1, 'record_status_id' => 1])->get()->first();
            //$physicianId = Physician::where(['lab_id' => $labId, 'is_default' => 1, 'record_status_id' => 1])->get()->first();

            // create sample first
            $sampleRequest = array(
                'patient_id' => $patientId,
                'sample_number' => $this->generateSampleNumber($labId, date('Y-m-d H:i:s')),
                'admission_date' => date('Y-m-d H:i:s'),
                'sample_source_id' => @$sampleSourceId->id, // cannot null
                'physician_id' => $sampleCreateRequest->physician_id, // @$physicianId->id, // cannot null
                'requested_date' => date('Y-m-d H:i:s'),
                'received_date' => date('Y-m-d H:i:s'),
                'collected_date' => date('Y-m-d H:i:s'),
                'is_accept_request' => 0,
                'lab_id' => $labId,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => $patientId,
            );

            $requestedSample = $this->sampleModel::query()->create($sampleRequest);

            //$this->sampleDetailModel::query()->where(['sample_id' => $requestedSample->id, 'lab_id' => $labId])->update(array(BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE));
            if(!empty($requestedSample)) {
                if (!empty($sampleCreateRequest->sample_tests)) {
                    /*$this->testResultModel::query()->where(['sample_id' => $requestedSample->id, 'lab_id' => $labId])
                        ->whereNotIn('test_sample_id', $sampleCreateRequest->sample_tests)
                        ->delete();*/
                    foreach ($sampleCreateRequest->sample_tests as $test) {
                        $testResult = $this->testResultModel::query()->create([
                            'sample_id' => $requestedSample->id,
                            'test_sample_id' => $test,
                            'created_at' => date('Y-m-d H:i:s'),
                            'created_by' => $patientId,
                            'lab_id' => $labId,
                        ]);
                    }
                }
                /*else {
                    $this->testResultModel::query()->where(['sample_id' => $sampleCreateRequest->sample_id, 'lab_id' => $this->baseLabId])->delete();
                }*/
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => __('sample.assign_tests_success')]);
        } catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return response()->json(['success'=> false , 'errors' => [$e->getMessage()]]);
        }
    }

    public function getTestGroup($id, $labId){
        try{
            $testGroupItems = $this->testGroupDetailModel::query()->where(['test_group_id' => $id, 'lab_id' => $labId, 'record_status_id'=> 1])->get()->pluck('test_sample_id')->toArray();
            return response()->json(['success' => true, 'data' => $testGroupItems]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'errors' => [$e->getMessage()]]);
        }
    }



}
