<?php

namespace Modules\HospitalPortal\Http\Controllers\Api;

use App\Events\ClaimRequested;
use App\Helpers\Helper;
use App\Models\ClaimRequest;
use App\Models\File;
use App\Models\Member;
use App\Services\ClaimRequestService;
use App\Services\ClaimService;
use Exception;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\HospitalPortal\Transformers\ClaimRequestResource;
use Modules\HospitalPortal\Transformers\ClaimRequestShowResource;
use PDF;

class ClaimRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(request $request)
    {
        $claimRequests = ClaimRequest::query()
                                ->when($request->search, function ($q, $search) {
                                    $q->where('code', 'LIKE', "%".$search."%");
                                })
                                ->when($request->orderBy, function ($q, $orderBy) use ($request) {
                                    if (in_array($orderBy, ['submission_date', 'code'])) {
                                        $q->orderBy($orderBy, $request->order);
                                    }
                                })
                                ->when($request->status, function($q, $status) {
                                    $q->where('status', $status);
                                })
                                ->with(['member'])
                                ->orderBy('created_at', 'DESC')
                                ->paginate();

        return Helper::responseJson($claimRequests);
    }

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

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

        $member = Member::find($request->member_id);
        $newClaimRequest = ClaimRequestService::storeClaimRequest(member: $member, paymentType: 'reimbursement', serviceCode: $request->service_code);

        ClaimRequested::dispatch($newClaimRequest);

        // Log History
        $newClaimRequest->histories()->create([
            'title' => 'New Claim Requested',
            'description' => "Claim Requested for Member : {$member->member_id} - ({$member->full_name})",
            'type' => 'info',
            'system_origin' => 'hospital-portal'
        ]);

        if ($request->hasFile('result_files')) {
            foreach ($request->result_files as $file) {
                $pathFile = File::storeFile('claim-result', $newClaimRequest->id, $file);
                $newClaimRequest->files()->updateOrCreate([
                    'type' => 'claim-result',
                    'name' => File::getFileName('claim-result', $newClaimRequest->id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        if ($request->hasFile('diagnosa_files')) {
            foreach ($request->diagnosa_files as $file) {
                $pathFile = File::storeFile('claim-diagnosis', $newClaimRequest->id, $file);
                $newClaimRequest->files()->updateOrCreate([
                    'type' => 'claim-diagnosis',
                    'name' => File::getFileName('claim-diagnosis', $newClaimRequest->id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        if ($request->hasFile('result_files')) {
            foreach ($request->result_files as $file) {
                $pathFile = File::storeFile('claim-kondisi', $newClaimRequest->id, $file);
                $newClaimRequest->files()->updateOrCreate([
                    'type' => 'claim-kondisi',
                    'name' => File::getFileName('claim-kondisi', $newClaimRequest->id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        return Helper::responseJson(data: $request->toArray(), message: 'Claim Request berhasil ajukan!');
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        $claimRequest = ClaimRequest::findOrFail($id);
        $claimRequest->load([
            'histories' => function ($history) {
                $history->latest();
            }
        ]);

        return Helper::responseJson(data: ClaimRequestShowResource::make($claimRequest));
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('hospitalportal::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 generateLog($claim_request_id)
    {
        $claimRequest = ClaimRequest::findOrFail($claim_request_id);

        if ($claimRequest->status != 'approved') {
            throw new Exception("Belum Teverifikasi", 1);
        }

        $member = Member::findOrFail($claimRequest->member_id)
                ->load(['currentPlan', 'currentPolicy', 'currentPlan.corporateBenefits', 'currentPlan.corporateBenefits.benefit']);

        $pdf = PDF::loadView('pdf.guaranted_leter', compact('member', 'claimRequest'));
        return $pdf->download('Guaranted Letter - '.$member->full_name.'.pdf');
        
        return $claimRequest;
    }
}
