<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Benefit;
use App\Models\Claim;
use App\Models\Icd;
use App\Models\Member;
use App\Models\Organization;
use App\Services\ClaimService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Internal\Transformers\ClaimShowResource;
use PDF;

class ClaimController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $claims = Claim::with([
                            'member',
                            'diagnoses' => function ($diagnosis) {
                                return $diagnosis->where('type', 'primary');
                            },
                            'diagnoses.icd',
                            'plan', 
                            'benefit',
                            'claimRequest',
                            'claimRequest.service'
                        ])
                        ->latest()
                        ->paginate(10);

        return response()->json($claims);
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('internal::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        $request->validate([
            'diagnosis_id' => 'required',
            'member_id' => 'required',
            'total_claim' => 'required',
            'benefit_id' => 'required'
        ]);

        // return response()->json($request->toArray());

        $member = Member::find($request->member_id);
        $benefit = Benefit::find($request->benefit_id);
        $diagnosis = Icd::find($request->diagnosis_id);

        // Check Eligibility
        $validation = ClaimService::checkMemberEligibility($member, $benefit, $diagnosis, $request->total_claim);

        // Store Claim
        if ($validation['isEligible']) {
            $claim = ClaimService::storeClaim($member, $diagnosis, $request->total_claim, $benefit, 'requested');
        } else {
            return response()->json([
                'data' => $validation,
                'message' => $validation['errors'][0]['message']
            ], 403);
        }

        return response()->json($claim);
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        $claim = Claim::query()
                ->with([
                    'member', 
                    'member.currentPlan', 
                    'member.currentPlan.benefits',
                    'member.currentCorporate',
                    'member.currentPolicy',
                    // 'diagnosis',
                    'diagnoses',
                    'diagnoses.icd',
                    'benefit',
                    'files',
                    'claimRequest',
                    'claimRequest.files',
                    'items',
                    'items.claim_itemable',
                    'encounters',
                    'encounters.doctors',
                    'encounters.primaryDiagnoses',
                    'encounters.primaryDiagnoses.diagnosis',
                    'encounters.healthcare'
                    ])
                ->findOrFail($id);

        return Helper::responseJson(ClaimShowResource::make($claim));
    }

    /**
     * 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, $id)
    {
        //
    }

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

    public function checkLimit(Request $request)
    {
        return true;
    }

    public function updateDetails(Request $request, $id)
    {
        $request->validate([
            'healthcare_id' => 'required',
            'doctor_id' => 'required',
            'start' => 'required',
            'end' => 'required'
        ]);

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

        return $claim;
    }
    
    public function updateItems(Request $request, $id)
    {
        $request->validate([]);
        $claim = Claim::findOrFail($id);
        
        $order = 1;
        $data = [];
        $claim->items()->forceDelete();
        foreach ($request->benefit_items as $benefitItem) {
            $benefit = Benefit::find($benefitItem['id']);
            if ($benefit) {
                $benefit->claimItem()->create([
                    'claim_id' => $claim->id,
                    'order' => $order,
                    'name' => $benefit->code,
                    'currency' => 'IDR',
                    'nominal_ditagihkan' => $benefitItem['biaya_diajukan'] ?? 0,
                    'nominal_dicover' => $benefitItem['biaya_disetujui'] ?? 0,
                    'nominal_total' => $benefitItem['biaya_disetujui'] ?? 0,
                ]);
            }

            $order++;
        }
        return Helper::responseJson([], message: "Item Claim berhasil di update");
    }

    public function updateDiagnosis(Request $request, $id)
    {
        $request->validate([]);
        $claim = Claim::findOrFail($id);

        $claim->diagnoses()->forceDelete();
        if ($request->primary) {
            foreach ($request->primary as $diagnosisId) {
                    $claim->diagnoses()->create([
                        'claim_id' => $claim->id,
                        'type' => 'primary', 
                        'diagnosis_id' => $diagnosisId,
                        'note' => '',
                        'description' => '',
                    ]);
            }
        }

        if ($request->secondary) {
            foreach ($request->secondary as $diagnosisId) {
                $claim->diagnoses()->create([
                    'claim_id' => $claim->id,
                    'type' => 'secondary', 
                    'diagnosis_id' => $diagnosisId,
                    'note' => '',
                    'description' => '',
                ]);
            }
        }

        return Helper::responseJson([], message: "Diagnosis berhasil di update");
    }

    public function decline($id)
    {
        $claim = Claim::findOrFail($id);
        $claim->status = 'declined';
        $claim->save();

        return Helper::responseJson($claim, message: "Claim berhasil di decline");
    }

    public function approve($id)
    {
        $claim = Claim::findOrFail($id);
        $claim->status = 'approved';
        $claim->save();

        return Helper::responseJson($claim, message: "Claim berhasil di approve");
    }

    public function reOpen($id)
    {
        $claim = Claim::findOrFail($id);
        $claim->status = 'received';
        $claim->save();

        return Helper::responseJson($claim, message: "Claim berhasil di approve");
    }

    public function downloadFinalLog($id)
    {
        $claim = Claim::findOrFail($id);

        $hospital = $claim->finalEncounter->healthcare ?? null;

        // TODO Fix this tipu tipu
        $inpationBenefit = $claim->member->currentPlan->benefits()->first();
        
        $pdf = PDF::loadView('pdf.final_log', [
            'claim' => $claim,
            'member' => $claim->member,
            'dateOfAdmission' => $claim->start,
            'hospital' => $hospital,
            'inpationBenefit' => $inpationBenefit
        ]);
        
        return $pdf->download('Final LOG '.$claim->code.'.pdf');

        $view = view('pdf.final_log', [
            'claim' => $claim,
            'member' => $claim->member,
            'dateOfAdmission' => $claim->start,
            'hospital' => $hospital,
            'inpationBenefit' => $inpationBenefit
        ]);

        return $view;
    }
}
