<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Models\DailyMonitoring;
use App\Models\RequestDailyMonitoring;
use App\Models\MedicalPlan;
use DB;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;
use App\Models\File;

/**
 * Bagaskoro BSD 27-10-2023
 *
 * Controller untuk daily monitoring
 */
class DailyMonitoringController extends Controller
{
    protected $path_for_store  = 'public/lab_result';
    protected function messages()
    {
        return [
            'required'      => ':attribute harus diisi',
            'integer'       => ':attribute harus angka',
            'unique'        => ':attribute (:input) sudah ada',
            'max'           => ':attribute maximal :max karakter',
            'exists'        => ':attribute (:input) tidak ditemukan',
            'numeric'       => ':attribute harus angka',
            'digits_between'=> ':attribute maximal :max digit minimal :min digit'
        ];
    }

    /**
     * Member List
     */
    public function GetMemberList()
    {
        $memberList = DB::table('request_logs')
            ->leftJoin('members', 'request_logs.member_id', '=', 'members.id')
            ->leftJoin('member_plans', 'request_logs.member_id', '=', 'member_plans.member_id')
            ->leftJoin('organizations', 'organizations.id', '=', 'request_logs.organization_id')
            ->select('members.member_id','members.name','members.members_effective_date AS startdate','members.members_expire_date AS enddate', 'request_logs.submission_date as addmision_date', 'organizations.name as provider' )
            ->where('request_logs.service_code', 'IP')
            ->where('request_logs.status_final_log', 'approved')
            ->groupBy('request_logs.member_id')
            ->orderBy('request_logs.created_at', 'desc')
            ->get();

        return response()->json([
            'error'   => false,
            'message' => "success",
            'data'    => [
                'member_list'=> $memberList,
            ]
        ],200);
    }

    /**
     * Claim List - by member id
     */
    public function GetClaimList(Request $request, $member_id)
    {
        $memberDetail = DB::table('members')
            ->select('id','member_id','name')
            ->where('member_id', $member_id)
            ->first();

        $claimList = DB::table('request_logs')
            ->leftJoin('services', 'services.code', '=', 'request_logs.service_code')
            ->leftJoin('members', 'members.id', '=', 'request_logs.member_id')
            ->select('request_logs.id','request_logs.submission_date AS admission_date','request_logs.discharge_date','request_logs.code','services.name as service_name','request_logs.status','members.name', 'members.member_id')
            ->where('request_logs.service_code', 'IP')
            ->where('request_logs.status_final_log', 'approved')
            ->where("request_logs.member_id", "=", $memberDetail->id)
            ->orderBy("request_logs.created_at", "desc")
            ->get();

        return response()->json([
            'error'   => false,
            'message' => "success",
            'data'    => [
                'member_detail'=> $memberDetail,
                'claim_list'   => $claimList,
            ]
        ],200);
    }

    /**
     * Detail Monitoring List - by claim_code
     */
    public function GetDetailMonitoringList(Request $request, $request_code)
    {
        // get id request log
        $request_logs = DB::table('request_logs')
            ->select('id')
            ->where('code', $request_code)
            ->first();

        $detail_list = RequestDailyMonitoring::where('request_log_id', empty($request_logs) == false ? $request_logs->id : '')
                            ->orderBy("created_at", "desc")
                            ->get();

        return response()->json([
            'error'   => false,
            'message' => "success",
            'data'    => [
                'detail_list'=> $detail_list,
            ]
        ],200);
    }

    /**
     * Add Detail Monitoring List
     */
    public function AddDetailMonitoringList(Request $request, $claim_code)
    {
        $request->merge(['claim_code' => $claim_code]);

        // validation rule
        $validator = Validator::make($request->all(),[
            'claim_code'        => 'required|exists:claim_requests,code',
            'subject'           => 'required',
            'sistole'           => 'required|numeric',
            'diastole'          => 'required|numeric',
            'body_temperature'  => 'required|numeric',
            'respiration_rate'  => 'required|numeric',
            'analysis'          => 'required',
            'complaints'        => 'required',
            'medical_plan'      => 'required',
        ],$this->messages());

        // validation error
        if ($validator->fails()) {
            return response()->json([
                'error'   => true,
                'message' => $validator->getMessageBag()
            ],400);
        }

        // get claim request
        $claim_request = DB::table('claim_requests')
            ->select('id')
            ->where('code', $claim_code)
            ->first();

        // get claim
        $claim = DB::table('claims')
            ->select('id')
            ->where('claim_request_id', $claim_request->id)
            ->first();
        DB::beginTransaction();
        try {
            // insert claim daily monitoring
            $db_response = DailyMonitoring::create([
                'claim_id'          => $claim->id,
                'subject'           => $request->subject,
                'sistole'           => $request->sistole,
                'diastole'          => $request->diastole,
                'body_temperature'  => $request->body_temperature,
                'respiration_rate'  => $request->respiration_rate,
                'analysis'          => $request->analysis,
                'complaints'        => $request->complaints,
            ]);


            // cek medical plan
            $num_medical_plan = 0;

            foreach ($request->medical_plan as $row) {
                if ($row['medical_plan_str']) {
                    $num_medical_plan++;
                }
            }

            if ($num_medical_plan == 0) {
                DB::rollBack();

                return response()->json([
                    'error'   => true,
                    'message' => [
                        'medical_plan' => ['medical plan harus diisi']
                    ],
                    'data'    => []
                ],400);
            }

            // insert medical plan
            foreach ($request->medical_plan as $row) {
                MedicalPlan::create([
                    'claim_daily_monitoring_id' => $db_response->id,
                    'plan'                      => $row['medical_plan_str'],
                ]);
            }

            DB::commit();

            return response()->json([
                'error'   => false,
                'message' => "success",
                'data'    => []
            ],200);
        }
        catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'error'   => true,
                'message' => $e->getMessage(),
                'data'    => []
            ],500);
        }
    }

    /**
     * Add Detail Request LOG LIST
     */
    public function AddDetailMonitoringListRequestLog(Request $request, $request_code)
    {
        $request->merge(['request_code' => $request_code]);

        // validation rule
        $validator = Validator::make($request->all(),[
            'request_code'      => 'required|exists:request_logs,code',
            'subject'           => 'required',
            'body_temperature'  => 'required|numeric',
            'sistole'           => 'required|numeric',
            'diastole'          => 'required|numeric',
            'respiration_rate'  => 'required|numeric',
            'analysis'          => 'required',
            'medical_plan'      => 'required',
            'non_medikamentosa_plan' => 'required',
        ],$this->messages());

        // validation error
        if ($validator->fails()) {
            return response()->json([
                'error'   => true,
                'message' => $validator->getMessageBag()
            ],400);
        }

        // get claim request
        $request_log = DB::table('request_logs')
            ->select('id')
            ->where('code', $request_code)
            ->first();
        DB::beginTransaction();
        try {
            // insert claim daily monitoring
            $db_response = RequestDailyMonitoring::create([
                'request_log_id'    => $request_log->id,
                'subject'           => $request->subject,
                'sistole'           => $request->sistole,
                'diastole'          => $request->diastole,
                'body_temperature'  => $request->body_temperature,
                'respiration_rate'  => $request->respiration_rate,
                'analysis'          => $request->analysis,
                'lab_date'          => $request->lab_date,
                'provider'          => $request->provider,
                'examination'       => $request->examination,
                'created_by'        => auth()->user()->id,
            ]);


            // cek medical plan
            $num_medical_plan = 0;
            foreach ($request->medical_plan as $row) {
                if ($row['medical_plan_str']) {
                    $num_medical_plan++;
                }
            }

            if ($num_medical_plan == 0) {
                DB::rollBack();
                return response()->json([
                    'error'   => true,
                    'message' => [
                        'medical_plan' => ['medical plan harus diisi']
                    ],
                    'data'    => []
                ],400);
            }

            // insert medical plan
            foreach ($request->medical_plan as $row) {
                DB::table('request_log_medical_plan')->insert([
                    'request_log_daily_monitoring_id' => $db_response->id,
                    'plan' => $row['medical_plan_str'],
                    'type' => 1,
                    'created_at' => date('Y-m-d'),
                ]);
            }

            // insert non medical plan
            foreach ($request->non_medikamentosa_plan as $row) {
                DB::table('request_log_medical_plan')->insert([
                    'request_log_daily_monitoring_id' => $db_response->id,
                    'plan' => $row['non_medikamentosa_plan_str'],
                    'type' => 2,
                    'created_at' => date('Y-m-d'),
                ]);
            }

            // insert file result
            if ($request->confirmation_medical_leter){
                foreach ($request->confirmation_medical_leter as $file) {
                    $name     = 'labresult-' . uniqid();
                    $extension= $file->getClientOriginalExtension();
                    $fileName = $name . '.' . $extension;
                    $path = $file->storeAs($this->path_for_store, $fileName);
                    File::create([
                        'fileable_type' => 'App\Models\LaboratoriumResult',
                        'fileable_id'   => $db_response->id,
                        'type'          => 'confirmation-medical-letter',
                        'name'          => $name,
                        'original_name' => $fileName,
                        'extension'     => $extension,
                        'path'          => $path,
                    ]);

                }
            }
            if ($request->medical_action_letter){
                foreach ($request->medical_action_letter as $file) {
                    $name     = 'labresult-' . uniqid();
                    $extension= $file->getClientOriginalExtension();
                    $fileName = $name . '.' . $extension;
                    $path = $file->storeAs($this->path_for_store, $fileName);
                    File::create([
                        'fileable_type' => 'App\Models\LaboratoriumResult',
                        'fileable_id'   => $db_response->id,
                        'type'          => 'medical-action-letter',
                        'name'          => $name,
                        'original_name' => $fileName,
                        'extension'     => $extension,
                        'path'          => $path,
                    ]);

                    // $file->storeAs($this->path_for_store, $fileName);
                }
            }
            if ($request->result){
                foreach ($request->result as $file) {
                    $name     = 'labresult-' . uniqid();
                    $extension= $file->getClientOriginalExtension();
                    $fileName = $name . '.' . $extension;
                    $path = $file->storeAs($this->path_for_store, $fileName);
                    File::create([
                        'fileable_type' => 'App\Models\LaboratoriumResult',
                        'fileable_id'   => $db_response->id,
                        'type'          => 'laboratorium-result',
                        'name'          => $name,
                        'original_name' => $fileName,
                        'extension'     => $extension,
                        'path'          => $path,
                    ]);

                    // $file->storeAs($this->path_for_store, $fileName);
                }
            }


            DB::commit();

            return response()->json([
                'error'   => false,
                'message' => "success",
                'data'    => []
            ],200);
        }
        catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'error'   => true,
                'message' => $e->getMessage(),
                'data'    => []
            ],500);
        }
    }

    /**
     * Update Status Request LOG
     */
    public function UpdateListRequestLog(Request $request, $request_code)
    {
        // get claim request
        $request_log = DB::table('request_logs')
                ->where('code', $request_code)
                ->update([
                    'discharge_date' => now(),
                    'updated_by' => auth()->user()->id,
                    'updated_at' => now()
                ]);
        if ($request_log) {
            return response()->json([
                'error'   => false,
                'message' => "success",
                'data'    => []
            ], 200);
        } else {
            return response()->json([
                'error'   => true,
                'message' => $e->getMessage(),
                'data'    => []
            ],500);
        }
    }
}
