<?php

namespace App\Http\Controllers\Api\OLDLMS;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\Icd;
use App\Models\Member;
use App\Models\Claim;
use App\Models\Speciality;
use App\Services\ClaimService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ClaimController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'member_id' => 'required',
            'user_id' => 'required',
            'type' => 'required|in:consultation,teleconsultation,medicine',
            // 'speciality_code' => 'required',
            'total_claim' => 'required',
            'detail' => 'required',
        ]);

        $currentSpeciality = Speciality::where('code', $request->speciality_code)->first();
        
        $gpSpecialityName = config('aso.general_practitioner_speciality_name', 'Umum');
        $isGp = $gpSpecialityName == ($currentSpeciality ? $currentSpeciality->name : false);

        if ($request->type == 'medicine') {
            $benefitCode = 'OPMEDI1';
        } else if ($isGp) {
            $benefitCode = 'OPCONS1';
        } else {
            $benefitCode = 'OPCONS2';
        }

        $member = Member::query()
                        ->where('member_id', $request->member_id)
                        ->with([
                            'currentPlan',
                        ])
                        ->firstOrFail();
        $benefit = $member->currentPlan->benefits()->where('code', $benefitCode)->first();
        
        $claim = ClaimService::storeClaim($member, null, $request->total_claim, $benefit, 'requested');
        $claim->status = 'approved';
        $claim->save();
        
        return Helper::responseJson($claim);
    }

    public function updateClaimDiagnosis(Request $request)
    {
        $request->validate([
            'claim_code' => 'required',
            'icd_codes' => 'required'
        ]);

        $claim = Claim::where('code', $request->claim_code)->firstOrFail();

        try {
            DB::beginTransaction();
            $claim->fill(['status' => 'postpone'])->update();

            $icds = Icd::whereIn('code', $request['icd_codes'])->get();
            $icds = $icds->map(function($icd) use ($claim) {
                return [
                    'claim_id' => $claim->id,
                    'type' => 'primary',
                    'diagnosis_id' => $icd->id,
                    'note' => 'HIS Summary',
                    'description'=> ''
                ];
            })->toArray();

            return $claim->diagnoses()->insert($icds);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();

            return Helper::responseJson($e, 500);
        };
    }
}
