<?php

namespace Modules\Internal\Http\Controllers\Api;

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

/**
 * Bagaskoro BSD 28-10-2023
 *
 * Controller untuk laboratorium result
 */
class LaboratoriumResultController 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'
        ];
    }

    /**
     * Detail Lab Result List - by claim_code
     */
    public function GetDetailLabResultList(Request $request, $claim_code)
    {
        // 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', empty($claim_request)==false ? $claim_request->id : '')
            ->first();

        $detail_list = LaboratoriumResult::where('claim_id', empty($claim) == false ? $claim->id : '')->orderBy("created_at", "desc")->get()->makeHidden(['updated_at']);

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

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

        // validation rule
        $validator = Validator::make($request->all(),[
            'claim_code'        => 'required|exists:claim_requests,code',
            'date'              => 'required',
            'location'          => 'required',
            'examination'       => 'required',
            'lab_result_file'   => '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 lab result
            $db_response = LaboratoriumResult::create([
                'claim_id'          => $claim->id,
                'date'              => $request->date,
                'location'          => $request->location,
                'examination'       => $request->examination,
            ]);

            // insert file result
            foreach ($request->lab_result_file as $file) {
                $name     = 'labresult-' . uniqid();
                $extension= $file->getClientOriginalExtension();
                $fileName = $name . '.' . $extension;

                File::create([
                    'fileable_type' => 'App\Models\LaboratoriumResult',
                    'fileable_id'   => $db_response->id,
                    'type'          => 'laboratorium-result',
                    'name'          => $name,
                    'original_name' => $fileName,
                    'extension'     => $extension,
                    '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);
        }
    }
}
