<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\ClaimRequest;
use App\Models\Organization;
use App\Services\ClaimService;
use App\Services\ImportService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Internal\Transformers\ClaimRequestResource;
use Modules\Internal\Transformers\ClaimRequestShowResource;
use Illuminate\Support\Facades\Storage;
use App\Services\ClaimRequestService;
use App\Exceptions\ImportRowException;
use App\Events\ClaimRequested;


use App\Models\File;
use App\Models\FilesMcu;
use Illuminate\Support\Facades\DB;
use App\Models\Member;

class ClaimRequestController extends Controller
{
    private static $code_prefix = 'CRQ-C';

    /**
     * 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."%");
                                    $q->orWhereHas('member', function ($subQuery) use ($search) {
                                        $subQuery->where('name', 'LIKE', "%".$search."");
                                    });
                                })
                                ->when($request->orderBy, function ($q, $orderBy) use ($request) {
                                    if (in_array($orderBy, ['submission_date', 'code'])) {
                                        $q->orderBy($orderBy, $request->order);
                                    }
                                })
                                ->when(empty($request->orderBy), function ($q) {
                                    $q->orderBy('created_at', 'desc');
                                })
                                ->when($request->status, function($q, $status) {
                                    $q->where('status', $status);
                                })
                                ->with(['member', 'files', 'service', 'member.currentPolicy'])
                                ->paginate();

        return Helper::paginateResources(ClaimRequestResource::collection($claimRequests));
    }

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

    /**
     * Create New Calim Request
     *
     * Bagaskoro, BSD 03 November 2023
     */
    public function createNew(Request $request)
    {
        $request->validate([
            'member_id' => 'required|array',
            'member_id.*' => 'required',
            'service_code.*' => 'required|in:OP,IP'
        ]);

        if ($request->member_id){
            foreach($request->member_id as $key => $member_id){

                $code = $this->getNextCode();
                $member = Member::find($member_id);

                DB::beginTransaction();

                try {
                    $newClaimRequest = ClaimRequestService::storeClaimRequest(
                        row: [],
                        code: $code,
                        member: $member,
                        paymentType: 'reimbursement',
                        serviceCode: $request->service_code[$key],
                    );

                    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' => 'client-portal'
                    ]);

                    // Claim Log
                    DB::table('claim_logs') ->insert([
                        'claim_request_id' => $newClaimRequest->id,
                        'status' => 'requested',
                        'date' => date('Y-m-d H:i:s'),
                        'description' => "Claim Requested for Member : {$member->member_id} - ({$member->full_name})",
                        'system_origin' => 'hospital-portal',
                        'created_by' => auth()->user()->id,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at'=> date('Y-m-d H:i:s'),
                    ]);

                    $storage_path = storage_path() . "/app/public";
                    $folder       = "claim/";

                    if (is_dir($storage_path . "/" . $folder) == false) {
                        mkdir($storage_path . "/" . $folder, 0770, true);
                    }

                    if (isset($_FILES['file_penunjang'])) {
                        foreach ($_FILES['file_penunjang']['error']["member_" .$member_id] as $key => $value) {
                            if ($value == 0) {
                                $new_file_name  = "claim-result-" . time() . "-" . uniqid();
                                $ekstension     =  "." . explode("/", $_FILES['file_penunjang']['type']["member_" .$member_id][$key])[1];
                                $pathFile       = $folder . $new_file_name . $ekstension;

                                $tmp_name       = $_FILES['file_penunjang']['tmp_name']["member_" .$member_id][$key];
                                $full_path      = $_FILES['file_penunjang']['full_path']["member_" .$member_id][$key];

                                if (move_uploaded_file($tmp_name, $storage_path . "/" . $pathFile)) {
                                    $newClaimRequest->files()->updateOrCreate([
                                        'type'          => 'claim-result',
                                        'name'          => $new_file_name,
                                        'original_name' => $full_path,
                                        'extension'     => $ekstension,
                                        'path'          => $pathFile,
                                        'created_by'    => auth()->user()->id,
                                        'updated_by'    => auth()->user()->id,
                                    ]);
                                }
                            }
                        }
                    }

                    if (isset($_FILES['file_diagnosa'])) {
                        foreach ($_FILES['file_diagnosa']['error']["member_" .$member_id] as $key => $value) {
                            if ($value == 0) {
                                $new_file_name  = "claim-diagnosis-" . time() . "-" . uniqid();
                                $ekstension     =  "." . explode("/", $_FILES['file_diagnosa']['type']["member_" .$member_id][$key])[1];
                                $pathFile       = $folder . $new_file_name . $ekstension;

                                $tmp_name       = $_FILES['file_diagnosa']['tmp_name']["member_" .$member_id][$key];
                                $full_path      = $_FILES['file_diagnosa']['full_path']["member_" .$member_id][$key];

                                if (move_uploaded_file($tmp_name, $storage_path . "/" . $pathFile)) {
                                    $newClaimRequest->files()->updateOrCreate([
                                        'type'          => 'claim-diagnosis',
                                        'name'          => $new_file_name,
                                        'original_name' => $full_path,
                                        'extension'     => $ekstension,
                                        'path'          => $pathFile,
                                        'created_by'    => auth()->user()->id,
                                        'updated_by'    => auth()->user()->id,
                                    ]);
                                }
                            }
                        }
                    }

                    if (isset($_FILES['file_kondisi'])) {
                        foreach ($_FILES['file_kondisi']['error']["member_" .$member_id] as $key => $value) {
                            if ($value == 0) {
                                $new_file_name  = "claim-kondisi-" . time() . "-" . uniqid();
                                $ekstension     =  "." . explode("/", $_FILES['file_kondisi']['type']["member_" .$member_id][$key])[1];
                                $pathFile       = $folder . $new_file_name . $ekstension;

                                $tmp_name       = $_FILES['file_kondisi']['tmp_name']["member_" .$member_id][$key];
                                $full_path      = $_FILES['file_kondisi']['full_path']["member_" .$member_id][$key];

                                if (move_uploaded_file($tmp_name, $storage_path . "/" . $pathFile)) {
                                    $newClaimRequest->files()->updateOrCreate([
                                        'type'          => 'claim-kondisi',
                                        'name'          => $new_file_name,
                                        'original_name' => $full_path,
                                        'extension'     => $ekstension,
                                        'path'          => $pathFile,
                                        'created_by'    => auth()->user()->id,
                                        'updated_by'    => auth()->user()->id,
                                    ]);
                                }
                            }
                        }
                    }

                    DB::commit();
                }
                catch (\Throwable $th) {
                    DB::rollBack();

                    return Helper::responseJson(status: 'failed', statusCode: 500, message: $th->getMessage());
                }
            }
        }

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

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

        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('internal::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        $claimRequest = ClaimRequest::findOrFail($id);
        $claimRequest->load([
            'histories' => function ($history) {
                $history->latest();
            },
            'files',
            'member',
            'claim',
            'organization',
        ]);
        $organization = Organization::where('code', $request->provider_code)->first();
        if (!$organization) {
            return response()->json(['error' => true, 'message' => 'Data tidak ditemukan'], 404);
        }

        $updateClaimRequest = ClaimRequestService::updateClaimRequest(organization_id: $organization->id, claim_request_id: $id);

        ClaimRequested::dispatch($updateClaimRequest);
        // Log History
        $updateClaimRequest->histories()->create([
            'title' => 'Update Claim Requested',
            'description' => "Update Claim Requested for Member : {$claimRequest->member->member_id} - ({$claimRequest->member->full_name})",
            'type' => 'update',
            'system_origin' => 'prime-center'
        ]);

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

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

        return response()->json([
            'error' => false,
            'message' => 'Update succses',
            'data' =>  $updateClaimRequest],
        200);

    }

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

    public function approve($id)
    {
        $claimRequest = ClaimRequest::findOrFail($id);
        $member = $claimRequest->member;

        try {

            // Create New Claim
            $newClaim = ClaimService::storeClaim(member: $member, status: 'received', claimRequest: $claimRequest);

            // Update Claim Request Status & Link with Claim
            $claimRequest->status = 'approved';
            $claimRequest->claim_id = $newClaim->id;
            $claimRequest->save();

            // Store Generated Documents LOG
            $logContent = view('pdf.guaranted_leter', compact('member', 'claimRequest'));
            $claimRequest->generatedDocuments()->create([
                'type' => 'guarantee_letter',
                'title' => 'Guarantee Letter for '. $member->full_name,
                'document_type' => 'type',
                'html_content' => $logContent,
                'system_origin' => 'primecenter'
            ]);

            // Claim Log
            DB::table('claim_logs')
            ->insert([
                'claim_request_id' => $id,
                'status' => 'reviewed',
                'date' => date('Y-m-d H:i:s'),
                'description' => "Claim Requested Successfully Reviewed",
                'system_origin' => 'prime-center',
                'created_by' => auth()->user()->id,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at'=> date('Y-m-d H:i:s'),
            ]);

        } catch (\Exception $e) {
            return $e->getMessage();
        }

        return $claimRequest;
    }

    public function filesMcu(Request $request)
    {
        $request->validate([
            'id' => 'required',
            'memberid' => 'required'
        ]);
        if ($request->hasFile('result_files')) {
            $pathFile = File::storeFile('claim-result', $request->id, $request->result_files);
            $data = [
                'memberid' => $request->id,
                'original_name' => $request->result_files->getClientOriginalName(),
                'path' => $pathFile,
                'created_by' => auth()->user()->id,
                'updated_by' => auth()->user()->id
            ];
            FilesMcu::create($data);
            return Helper::responseJson(data: $request->toArray(), message: 'Berhasil tambah file MemberID '.$request->memberid.', silahkan lihat dilaporan');
        }
        else
        {
            return Helper::responseJson(data: $request->toArray(), message: 'Tidak ada file member yang ditambahkan');
        }

    }

    public function importClaim(Request $request)
    {

        $request->validate([
            'file' => 'required|file|mimes:xls,xlsx,csv,txt',
        ]);
        $file_name = now()->getPreciseTimestamp(3) . '-' . $request->file('file')->getClientOriginalName();
        $file = $request->file('file')->storeAs('temp', $file_name);
        $fileWrite = Storage::disk('public')->path('temp/result-' . $file_name);
        $fileRead = Storage::path('temp/' . $file_name);
        $import = new ImportService();
        $import->read($fileRead);
        $import->write($fileWrite, 'xsls');
        foreach ($import->sheetsIterator() as $sheetIndex => $sheet) {
            if ($sheetIndex == 1) { // Rename First Sheet to Writer
                $firstWriterSheet = $import->writer->getCurrentSheet();
                $firstWriterSheet->setName($sheet->getName());
            } else { // Add New Sheet to Writer
                $nextWriterSheet = $import->writer->addNewSheetAndMakeItCurrent();
                $nextWriterSheet->setName($sheet->getName());
            }

            $headers_map_to_table_fields = ClaimRequest::$doc_headers_to_field_map;

            // Write Header to File
            $result_headers = array_keys($headers_map_to_table_fields);
            $result_headers = array_merge($result_headers, ['Ingest Code', 'Ingest Note']);

            $import->addArrayToRow($result_headers);
            $doc_headers_indexes = [];
            foreach ($sheet->getRowIterator() as $index => $row) {
                if ($index == 1) { // First Row Must be Header
                    foreach ($row->getCells() as $index => $cell) {
                        $title = $cell->getValue();
                        $title = preg_replace("/\r|\n/", " ", $title);
                        $title = preg_replace('/\xc2\xa0/', " ", $title);
                        $title = rtrim($title);
                        $title = ltrim($title);
                        $doc_headers_indexes[$index] = $title;
                    }
                    // TODO Validate if First Row not Header
                } else { // Next Row Should be Data
                    $row_data = [];
                    foreach ($row->getCells() as $header_index => $cell) {
                        if (isset($headers_map_to_table_fields[$doc_headers_indexes[$header_index]]))
                            $row_data[$headers_map_to_table_fields[$doc_headers_indexes[$header_index]]] = $cell->getValue();
                    }
                    try { // Process the Row Data
                        $claimRequestService = new ClaimRequestService();

                        $claimRequestService->handleClaimRequestRow($row_data);

                        // Write Success Result to File
                        // $import->read($fileRead);
                        // $import->write($fileWrite, 'xsls');
                        $result_headers = array_merge($row_data, ['Ingest Code' =>200, 'Ingest Note' => 'Success']);

                        $import->addArrayToRow($result_headers, $sheet->getName());

                    } catch (ImportRowException $e) {
                        // Write Data Validation Error to File
                        // $import->read($fileRead);
                        // $import->write($fileWrite, 'xsls');

                        $import->addArrayToRow(array_merge($row_data, [
                            'Ingest Code' => $e->getCode(),
                            'Ingest Note' => $e->getMessage(),
                        ]), $sheet->getName());
                    }
                    // catch (\Exception $e) {
                    //     // throw new \Exception($e);
                    //     // Write Server Error to File
                    //     // $import->read($fileRead);
                    //     // $import->write($fileWrite, 'xsls');
                    //     dd( $e->getMessage());
                    //     $import->addArrayToRow(array_merge($row_data, [
                    //         'Ingest Code' => 500,
                    //         'Ingest Note' => env('APP_DEBUG') ? $e->getMessage() : 'Server Error',
                    //     ]), $sheet->getName());
                    // }
                }
            }
        }
        $import->reader->close();
        Storage::delete('temp/' . $file_name);
        $import->writer->close();

        return [
            // 'total_successed_row' => $imported_plan_data,
            // 'total_failed_row' => count($failed_plan_data),
            // 'failed_row' => $failed_plan_data,
            'result_file' => [
                'url' => Storage::disk('public')->url('temp/result-' . $file_name),
                'name' => 'result-' . $file_name,
            ]
        ];
    }

    public function claimRequestDetail($claimRequestId)
    {
        $status = DB::table('claim_requests')
                    ->leftJoin('claims', 'claim_requests.id', '=', 'claims.claim_request_id')
                    ->leftJoin('members', 'claim_requests.member_id', '=', 'members.id')
                    ->leftJoin('corporate_employees', 'members.id', '=', 'corporate_employees.member_id')
                    ->leftJoin('corporate_divisions', 'corporate_employees.division_id', '=', 'corporate_divisions.id')
                    ->where('claim_requests.id', '=', $claimRequestId)
                    ->select(
                        'claim_requests.submission_date',
                        'claim_requests.code',
                        DB::raw('
                            CASE
                                WHEN claim_requests.status = "requested" THEN "requested"
                                WHEN claim_requests.status = "approved" AND claims.status = "approved" THEN "approved"
                                WHEN claim_requests.status = "approved" AND claims.status = "declined" THEN "declined"
                                WHEN claim_requests.status = "approved" AND claims.status = "disbrusmented" THEN "disbrusmented"
                                /*WHEN claim_requests.status = "approved" AND claims.status = "received" THEN "pending"*/
                                WHEN claim_requests.status = "approved" AND claims.status = "received" THEN "reviewed"
                                ELSE ""
                            END AS status
                        ')
                    )
                    ->first();
        $results['status'] = $status;
        $timeline = DB::table('claim_logs')
                        ->where('claim_logs.claim_request_id', '=', $claimRequestId)
                        ->select(
                            DB::raw('
                                CASE
                                    WHEN claim_logs.status = "requested" THEN "Request"
                                    WHEN claim_logs.status = "reviewed" THEN "Review"
                                    WHEN claim_logs.status = "approved" THEN "Approval"
                                    WHEN claim_logs.status = "declined" THEN "Decline"
                                    ELSE "-"
                                END AS txt_status
                            '),
                            DB::raw('
                                CASE
                                    WHEN claim_logs.status = "requested" THEN "#159C9C"
                                    WHEN claim_logs.status = "reviewed" THEN "#0C53B7"
                                    WHEN claim_logs.status = "approved" THEN "#229A16"
                                    WHEN claim_logs.status = "declined" THEN "#FF4842"
                                    ELSE "-"
                                END AS txt_status_color
                            '),
                            DB::raw('
                                CASE
                                    WHEN claim_logs.status = "requested" THEN "#00AB5529"
                                    WHEN claim_logs.status = "reviewed" THEN "#1890FF29"
                                    WHEN claim_logs.status = "approved" THEN "#54D62C29"
                                    WHEN claim_logs.status = "declined" THEN "#FF48427A"
                                    ELSE "-"
                                END AS txt_status_backgroundColor
                            '),
                            'claim_logs.date',
                            'claim_logs.description',
                            'claim_logs.status'
                        )
                        ->orderBy('claim_logs.id', 'desc')
                        ->get();
        $results['timeline'] = $timeline;
        $request_files = DB::table('claim_request_files')
                        ->where('claim_request_files.claim_request_id', '=', $claimRequestId)
                        ->select(
                            'claim_request_files.*',
                            DB::raw('(SELECT files.fileable_id FROM files WHERE files.fileable_id = claim_request_files.claim_request_id AND files.type = claim_request_files.type LIMIT 1) AS check_files'),
                        )
                        ->get();
        $results['request_files'] = $request_files;
        $documents = DB::table('files')
                                ->where('fileable_type', 'App\Models\ClaimRequest')
                                ->where('fileable_id', $claimRequestId)
                                ->select('original_name', \DB::raw("CONCAT('" . env('APP_URL') . "/storage/', path) as path"), 'type')
                                ->orderBy('id', 'desc')
                                ->get();
        $results['documents'] = $documents;
        $dialog_submits = DB::table('claim_requests')
                            ->leftJoin('members', 'claim_requests.member_id','=', 'members.id')
                            ->where('claim_requests.id', $claimRequestId)
                            ->select('claim_requests.code', 'members.name', 'claim_requests.submission_date', 'claim_requests.service_code','claim_requests.status')
                            ->first();
        $results['dialog_submits'] = $dialog_submits;

        return Helper::responseJson($results);
    }

    public function invoiceFiles(Request $request, $claim_id)
    {
        if ($request->hasFile('invoice_files')) {
            foreach ($request->invoice_files as $file) {
                $pathFile = File::storeFile('claim-invoice', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-invoice',
                    'name' => File::getFileName('claim-invoice', $claim_id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }
        if($request->date)
        {
            DB::table('claim_requests')
            ->where('id', $claim_id)
            ->update(['invoice_date' => $request->date]);

        }
        return Helper::responseJson(data: $request->toArray(), message: 'Invoice Success Uploaded');
    }

    /**
     * Get Claim Member - Infinite Scroll
     *
     * Bagaskoro, BSD 31 Oktober 2023
     */
    public function getClaimMemberInfiniteScroll(Request $request)
    {
        $offset  = 0;
        $limit   = 10;
        $page    = $request->get('page');
        $keyword = $request->get('keyword');

        if ($page > 1) {
            $offset = ($page*$limit)-$limit;
        }

        $memberList = DB::table('members')
            ->select('id','member_id','name')
            ->where("name", "like", "%$keyword%")
            ->orWhere("member_id", "like", "%$keyword%")
            ->orderBy('created_at', 'asc')
            ->offset($offset)
            ->limit($limit)
            ->get();
        
        $data = [];
        if(count($memberList)>0){
            $temp = [];
            foreach($memberList as $d){
                $serviceType = $this->getServiceMember($d->id);
                $temp['id'] = $d->id;
                $temp['member_id'] = $d->member_id;
                $temp['name'] = $d->name;
                $temp['service_type'] = $serviceType;


                array_push($data, $temp);
            }

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

    public function getServiceMember($id){
        $service = DB::table('member_plans')
            ->select('plans.service_code as code', 'services.name')
            ->join('plans', 'member_plans.plan_id', '=', 'plans.id')
            ->join('services', 'plans.service_code', '=', 'services.code')
            ->where('member_id', $id)
            ->get()
            ->toArray();
        return $service;
    }

    public static function getNextCode()
    {
        // $last_number = ClaimRequest::max('code');
        // $next_number = empty($last_number) ? 1 : ((int) explode('-', $last_number)[2] + 1);
        // return self::makeCode($next_number);

        $last_numeric_code = ClaimRequest::select(DB::raw('MAX(CAST(SUBSTRING_INDEX(code, "-", -1) AS SIGNED)) as max_numeric_code'))
                                    ->whereRaw('SUBSTRING_INDEX(code, "-", -1) REGEXP "^[0-9]+$"')
                                    ->value('max_numeric_code');
        // $next_number = 1;
        if ($last_numeric_code) {
        //     // Jika ada kode sebelumnya, pecah kode dan tambahkan 1 ke angka terakhir
        //     $parts = explode('-', $last_code);
        //     $last_number = (int) end($parts);
            $next_number = $last_numeric_code + 1;
        }

        return self::makeCode($next_number);
    }


    public static function makeCode($next_number)
    {
        // Pastikan $next_number adalah integer positif
        $next_number = max(1, (int) $next_number);

        // Menghasilkan kode dengan format yang diinginkan
        return self::$code_prefix . '-' . str_pad($next_number, 5, '0', STR_PAD_LEFT);
    }

    public function requestFiles(Request $request, $claim_id)
    {

        if ($request->hasFile('fileDiagnosis')) {
            foreach ($request->fileDiagnosis as $file) {
                $pathFile = File::storeFile('claim-diagnosis', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-diagnosis',
                    'name' => File::getFileName('claim-diagnosis', $claim_id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        if ($request->hasFile('fileKondisis')) {
            foreach ($request->fileKondisis as $file) {
                $pathFile = File::storeFile('claim-kondisi', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-kondisi',
                    'name' => File::getFileName('claim-kondisi', $claim_id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        if ($request->hasFile('fileResults')) {
            foreach ($request->fileResults as $file) {
                $pathFile = File::storeFile('claim-result', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-result',
                    'name' => File::getFileName('claim-result', $claim_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: 'Invoice Success Uploaded');
    }
}
