<?php

namespace Modules\Internal\Http\Controllers;

use App\Helpers\Helper;
use App\Models\Claim;
use App\Models\Encounter;
use App\Models\Practitioner;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Internal\Transformers\EncounterResource;


class ClaimEncounterController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        return view('internal::index');
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('internal::create');
    }
    public function getAllData()
    {
        $encounters = Encounter::with('claim.member')->get();

        return Helper::responseJson(data: EncounterResource::collection($encounters), message: 'Data berhasil diambil');
    }


    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request, $claim_id)
    {
        $request->validate([
            'service_code' => 'required',
            'tanggal_masuk' => 'required',
            'tanggal_keluar' => 'required'
        ]);
        $claim = Claim::findOrFail($claim_id);

        // return ($request->primary_diagnosis['id']);
        // die;
        // return $request->toArray();
        try {
            DB::beginTransaction();

            $newEncounterData = [
                'status' => 'completed',
                'class' => $request->service_code,
                'type' => 'Consultation',
                'patient_id' => $claim->member->person_id,
                'start' => $request->tanggal_masuk,
                'end' => $request->tanggal_keluar,
                'number_of_bed' => $request->number_of_bed,
                'duration_day' => $request->duration_day
            ];

            if ($request->has('healthcare')) {
                $newEncounterData['healthcare_id'] = $request->healthcare['id'];
            }

            // Create New Encounter
            $newEncounter = $claim->encounters()->create($newEncounterData);

            
            // --------------------------------------------
            // Meta
            // TODO Handle if healthcare not primaya
            $newEncounter->metas()->updateOrCreate([
                'type' => 'MEDRECID',
                'system' => 'primaya-his' 
            ], [
                'type' => 'MEDRECID',
                'system' => 'primaya-his',
                'value' => $request->medical_record_number
            ]);
            
            // ---------------------------------------------
            // Handle Diagnosis
            if ($request->has('primary_diagnosis') && $request->primary_diagnosis) {
                $newEncounter->diagnoses()->create([
                    'diagnosis_id' => $request->primary_diagnosis['id'],
                    'type' => 'primary',
                    'use' => 'discharge',
                    'source' => 'primecenter',
                    'description' => 'Batching',
                ]);
            }

            if ($request->has('secondary_diagnoses')) {
                foreach ($request->secondary_diagnoses as $diagnosis) {
                    if (!isset($diagnosis['id'])) { // Handle Null Values
                        continue;
                    }
                    $newEncounter->diagnoses()->create([
                        'diagnosis_id' => $diagnosis['id'],
                        'type' => 'secondary',
                        'use' => 'discharge',
                        'source' => 'primecenter',
                        'description' => 'Batching',
                    ]);
                }
            }

            // ------------------------------------
            // Handle Doctors as primary Doctor
            if ($request->has('doctor')) {
                $newEncounter->participants()->create([
                    'type' => 'Doctor',
                    'participantable_type' => Practitioner::class,
                    'participantable_id' => $request->doctor['id'],
                ]);
            }
            DB::commit();
            
            $newEncounter->load(['diagnoses', 'doctors', 'healthcare']);
            
            return Helper::responseJson(data: EncounterResource::make($newEncounter), message: 'Encounter berhasil ditambahkan');

        } catch (\Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('internal::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('internal::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $claim_id, $encounter_id)
    {
        $request->validate([
            'service_code' => 'required',
            'tanggal_masuk' => 'required',
            'tanggal_keluar' => 'required'
        ]);
        // $claim = Claim::findOrFail($claim_id);

        // return ($request->primary_diagnosis['id']);
        // die;
        // return $request->toArray();
        try {
            DB::beginTransaction();

            $encounter = Encounter::findOrFail($encounter_id);

            $encounterData = [
                'status' => 'completed',
                'class' => $request->service_code,
                'type' => 'Consultation',
                'start' => $request->tanggal_masuk,
                'end' => $request->tanggal_keluar,
                'number_of_bed' => $request->number_of_bed,
                'duration_day' => $request->duration_day
            ];

            if ($request->has('healthcare')) {
                $encounterData['healthcare_id'] = $request->healthcare['id'];
            }

            // Update The Encounter
            $encounter->fill($encounterData);
            $encounter->save();

            
            // --------------------------------------------
            // Meta
            // TODO Handle if healthcare not primaya
            $encounter->metas()->updateOrCreate([
                'type' => 'MEDRECID',
                'system' => 'primaya-his' 
            ], [
                'type' => 'MEDRECID',
                'system' => 'primaya-his',
                'value' => $request->medical_record_number
            ]);
            
            // ---------------------------------------------
            // Handle Diagnosis
            if ($request->has('primary_diagnosis')) {
                $encounter->diagnoses()->where('type', 'primary')->delete();
                $encounter->diagnoses()->create([
                    'diagnosis_id' => $request->primary_diagnosis['id'],
                    'type' => 'primary',
                    'use' => 'discharge',
                    'source' => 'primecenter',
                    'description' => 'Batching',
                ]);
            }

            if ($request->has('secondary_diagnoses')) {
                $encounter->diagnoses()->where('type', 'secondary')->delete();
                foreach ($request->secondary_diagnoses as $diagnosis) {
                    if (!isset($diagnosis['id'])) { // Handle Null Values
                        continue;
                    }
                    $encounter->diagnoses()->create([
                        'diagnosis_id' => $diagnosis['id'],
                        'type' => 'secondary',
                        'use' => 'discharge',
                        'source' => 'primecenter',
                        'description' => 'Batching',
                    ]);
                }
            }

            // ------------------------------------
            // Handle Doctors as primary Doctor
            // if ($request->has('doctor')) {
            //     $encounter->participants()->create([
            //         'type' => 'Doctor',
            //         'participantable_type' => Practitioner::class,
            //         'participantable_id' => $request->doctor['id'],
            //     ]);
            // }
            DB::commit();
            
            $encounter->load(['diagnoses', 'doctors', 'healthcare']);
            
            return Helper::responseJson(data: EncounterResource::make($encounter), message: 'Encounter berhasil ditambahkan');

        } catch (\Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    public function xcounters($claim_id)
    {
        $claim = Claim::findOrFail($claim_id);
        $encounters = $claim->encounters()->get();
        return response()->json($encounters);
    }

    public function getEncounterData($encounter_id)
    {
        $encounter = Encounter::with('claim.member')->findOrFail($encounter_id);

        return Helper::responseJson(data: EncounterResource::make($encounter), message: 'Data berhasil diambil');
    }



    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }

    public function setFinalEncounter(Request $request, $claim_id)
    {
        $request->validate([
            'encounter_id' => 'required'
        ]);

        $claim = Claim::findOrFail($claim_id);

        $claim->final_encounter_id = $request->encounter_id;
        $claim->save();

        return Helper::responseJson(data: $claim, message: "Success Update Final Encounter");
    }
}
