<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\RequestLog;
use App\Models\Organization;
use App\Models\Icd;
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\RequestLogResource;
use Modules\Internal\Transformers\RequestLogShowResource;
use Illuminate\Support\Facades\Storage;
use App\Exceptions\ImportRowException;
use App\Events\RequestLoged;
use Carbon\Carbon;

use Maatwebsite\Excel\Facades\Excel;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;


use Exception;
use PDF;



use App\Models\File;
use App\Models\FilesMcu;
use Illuminate\Support\Facades\DB;
use App\Models\Member;
use Modules\Internal\Services\RequestLogService;
use App\Services\RequestLogService as AppRequestLogService;

class RequestLogController extends Controller
{
    private static $code_prefix = 'LOG';

    /**
     * Display a listing of the resource.
     * @return Renderable
     */

    public function __construct()
    {
        $this->requestLogService = New RequestLogService;
    }

    public function index(Request $request)
    {
        $requestLog = RequestLog::query()
                                ->where('deleted_at', null)
                                ->when($request->final_log, function($q, $final_log) {
                                    $q->where('final_log', $final_log);
                                })
                                ->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', 'service_code', 'status'])) {
                                        $q->orderBy($orderBy, $request->order);
                                    }
                                })
                                ->when(empty($request->orderBy), function ($q) {
                                    $q->orderBy('submission_date', 'desc');
                                })
                                ->when($request->service_code, function($q, $service_code) {
                                    if ($service_code == 'IP'){ // Penjagaan sementara agar ini hanya muncul di inpatient monitoring
                                        $q->where('service_code', $service_code);
                                    } else {
                                        $q->where('service_code', '!=', 'IP'); // Dan selain IP muncul di final LOG
                                    }
                                })
                                // ->where('status', $request->status)
                                ->with(['member', 'files', 'service', 'member.currentPolicy'])
                                ->paginate();

        return Helper::paginateResources(RequestLogResource::collection($requestLog));
    }

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

    /**
     * Create New Request Request
     *
     * Tb, BSD 28 November 2023
     */
    public function createNew(Request $request)
    {
        $request->validate([
            'member_id' => 'required',
            'service_code' => 'required',
        ]);

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

            $memberValid = false;
            if ($member){
                if (($member->members_effective_date <= date('Y-m-d')) &&
                    ($member->members_expire_date >= date('Y-m-d')) &&
                    ($member->active == 1) &&
                    ($member->suspended == 'N')
                ){
                    DB::beginTransaction();
                    try {
                        $newRequestLog = AppRequestLogService::storeRequestLog(
                            row: [],
                            code: $code,
                            member: $member,
                            paymentType: 'cashless',
                            serviceCode: $request->service_code,
                            submissionDate: $request->submission_date,
                            // status: 'approved',
                            status: 'requested', // di nonaktifkan dulu auto approved
                            organization_id: $request->organization_id,
                            source: $request->source
                        );

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

                        return Helper::responseJson(status: 'failed', statusCode: 500, message: $th->getMessage());
                    }
                } else {
                    DB::beginTransaction();
                    try {
                        $newRequestLog = AppRequestLogService::storeRequestLog(
                            row: [],
                            code: $code,
                            member: $member,
                            paymentType: 'cashless',
                            serviceCode: $request->service_code,
                            submissionDate: $request->submission_date,
                            status: 'requested',
                            organization_id: $request->organization_id,
                            source: $request->source
                        );

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

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

        }

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

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        $claimRequest = RequestLog::findOrFail($id);
        $claimRequest->load([
            'histories' => function ($history) {
                $history->latest();
            },
            'files',
            'member',
            'member.currentPlan' => function($memberPlan) {
                $memberPlan->join('request_logs', 'request_logs.service_code', '=', 'plans.service_code');
            },
            // 'member.current_policy',
            'claim',
            'organization',

        ]);

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

    public function diagnosis(){
        $icds = Icd::query()
                    ->get();

        $manipulatedIcds = $icds->map(function ($icd) {
            // Contoh manipulasi, tambahkan atau ubah properti sesuai kebutuhan
            return [
                'value' => $icd->code,  // Ganti dengan properti yang sesuai dari model Icd
                'label' => $icd->code . ' - ' .$icd->name,  // Ganti dengan properti yang sesuai dari model Icd
            ];
        });
        return Helper::responseJson(data: $manipulatedIcds);
    }

    /**
     * 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)
    {
        $requestLog = RequestLog::findOrFail($id);
        // Jika ada nilai yang dikirimkan dalam permintaan, maka edit entitas
        if (!empty($request->submission_date)) {
            $requestLog->submission_date = $request->submission_date;
        }

        if (!empty($request->keterangan)) {
            $requestLog->keterangan = $request->keterangan;
        }

        if (!empty($request->hak_kamar_pasien)) {
            $requestLog->hak_kamar_pasien = $request->hak_kamar_pasien;
        }

        if (!empty($request->penempatan_kamar)) {
            $requestLog->penempatan_kamar = $request->penempatan_kamar;
        }

        if (!empty($request->catatan)) {
            $requestLog->catatan = $request->catatan;
        }

        if (!empty($request->reason)) {
            $requestLog->reason = $request->reason;
        }

        if ($request->status){
            $requestLog->status =  $request->status;
            $requestLog->approved_by = auth()->user()->id;
            $requestLog->approved_at = Carbon::now();
        }

        $requestLog->save();

        // update nirc member
        if (!empty($request->no_identitas)) {
            $member = Member::findOrFail($requestLog->member_id);
            $member->nric = $request->no_identitas;
            $member->save();
        }

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

    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy(Request $request, $id)
    {
        $requestLog = RequestLog::findOrFail($id);
        $requestLog->reason = 'Reason Delete ' .$request->reason;
        $requestLog->deleted_at = Carbon::now();
        $requestLog->deleted_by = auth()->user()->id;
        // Delete the record
        $requestLog->save();
    }

    public function deleteFinalLog(Request $request, $id){
        $requestLog = RequestLog::findOrFail($id);
        $requestLog->status_final_log = null;
        $requestLog->final_log = 0;
        $requestLog->reason_final = 'Reason Delete ' .$request->reason;
        $requestLog->save();
        return response()->json([
            'error' => false,
            'message' => 'Delete Final LOG',
            'data' =>  $requestLog],
        200);
    }

    /**
     * Generate Request LOG PDF
     */
    public function generateRequestLog($id)
    {
        $requestLog = RequestLog::find($id);
        $service_code = $requestLog->service_code;
        if ($requestLog->status != 'approved') {
            return response()->json([
                'error' => true,
                'message' => 'LOG Belum Terverifikasi',
                'data' =>  $requestLog],
            200);
        }

        $member = Member::findOrFail($requestLog->member_id)
                ->load([
                        // 'currentPlan',
                        'currentPlan' => function ($plan) use ($id, $service_code) {
                            $plan->where('plans.service_code', $service_code);
                        },
                        'currentPolicy',
                        'currentPlan.corporateBenefits',
                        'currentPlan.corporateBenefits.benefit'
                ]);

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

        return $requestLog;
    }

    /**
     * Generate Export Excel Request LOG
     */

    public function generateDataRequestLogExcel(){
        $file_name = 'Data Request LOG';
        // Membuat penulis entitas Spout
        $writer = WriterEntityFactory::createXLSXWriter();
         // Membuka penulis untuk menulis ke file
        $writer->openToFile(public_path('files/Data Request LOG.xlsx'));

       // Sheet 1
        $writer->getCurrentSheet()->setName('Data');
        $headers_map_to_table_fields = RequestLog::$listing_data_doc_headers;
        $headerRow = WriterEntityFactory::createRowFromArray($headers_map_to_table_fields);
        $writer->addRow($headerRow);

        $dataRequestLog = RequestLog::query()
            // ->whereHas('corporatePlan', function ($corporatePlan) use ($corporate_id) {
            //     $corporatePlan->where('corporate_id', $corporate_id);
            // })
            ->with('member')
            ->orderBy('id', 'desc')
            ->get()->toArray();

        // dd($dataRequestLog);
        foreach ($dataRequestLog as $index => $row){
            $serviceType = $this->getServiceName($row['service_code']);

            $rowData = [
                $row['id'], // id
                $row['code'], // code
                $row['member']['name'], // name
                $row['submission_date'], // submission date
                $serviceType, // service type
                $row['payment_type_name'], // service type
                $row['status'], // service type
            ];
            $row = WriterEntityFactory::createRowFromArray($rowData);
            $writer->addRow($row);
        }
        $writer->close();

        return Helper::responseJson([
            'file_name' => "Data Request Log " . date('Y-m-d h:i:s'),
            "file_url" => url('files/Data Request LOG.xlsx')
        ]);
    }

    /**
     * Submit Request LOG to Final LOG
     */
    public function updateFinalLog(Request $request)
    {
        $id = $request->id;
        $requestLog = RequestLog::findOrFail($id);
        $status = $request->status ?? 'requested';


        // Update Request LOG untuk lanjut ke Final LOG
        if (!empty($request->catatan)) {
            $requestLog->catatan = $request->catatan;
        }
        if ($request->discharge_date) {
            $requestLog->discharge_date = $request->discharge_date;
        }
        if (!empty($request->icdCodes)) {
            $diagnosis = implode(',', $request->icdCodes);

            $requestLog->diagnosis = $diagnosis;
        }
        if (!empty($request->status)) {
            $requestLog->status_final_log = $status;
        }

        if (!empty($request->reason)) {
            $requestLog->reason_final = $request->reason;
        }

        $requestLog->final_log = 1;
        $requestLog->approved_final_log_by = auth()->user()->id;
        $requestLog->approved_final_log_at = Carbon::now();
        // if($requestLog->service_code != 'IP'){
            // $requestLog->discharge_date = Carbon::now();
        // }
        
        $requestLog->save();


        if ($request->hasFile('result_files')) {
            foreach ($request->result_files as $file) {
                $pathFile = File::storeFile('final-log-result', $id, $file);
                $requestLog->files()->updateOrCreate([
                    'type' => 'final-log-result',
                    'name' => File::getFileName('final-log-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('final-log-diagnosis', $id, $file);
                $requestLog->files()->updateOrCreate([
                    'type' => 'final-log-diagnosis',
                    'name' => File::getFileName('final-log-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('final-log-kondisi', $id, $file);
                $requestLog->files()->updateOrCreate([
                    'type' => 'final-log-kondisi',
                    'name' => File::getFileName('final-log-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' =>  $requestLog],
        200);

    }

    public function updateStatus($id)
    {
        $requestLog = RequestLog::findOrFail($id);
        $member = $requestLog->member;

        try {

            // Update Request LOG Status & Link with Claim
            $requestLog->status = 'approved';
            $requestLog->save();

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


        } 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 importRequestLog(Request $request)
    {
         // setting tambahan php
        Helper::setCustomPHPIniSettings();
        $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);

        $reader = ReaderEntityFactory::createXLSXReader(Storage::path('temp/' . $file_name));
        $reader->open(Storage::path('temp/' . $file_name));

        $writer = WriterEntityFactory::createXLSXWriter();
        $writer->openToFile(Storage::disk('public')->path('temp/result-' . $file_name));

        $headers_map_to_table_fields = $this->requestLogService->doc_headers_to_field_map;

        // Write Header to File with certain Format from MemberEnrollmentService::$result_doc_headers
        $result_headers = $this->requestLogService->listing_doc_headers;
        $singleRow = WriterEntityFactory::createRow($this->requestLogService->makeResultRow($result_headers));
        $writer->addRow($singleRow);

        $imported_member_data = 0;
        $failed_member_data = [];

        foreach ($reader->getSheetIterator() as $sheet) {
            $doc_headers_indexes = [];
            foreach ($sheet->getRowIterator() as $index => $row) {
                if ($index == 1) { // First Row Must be Header
                    foreach ($row->getCells() as $index => $cell) {
                        // Clear up the string and remove all spaces
                        $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;
                    }
                } else { // Next Row Should be Data
                    // Collecting Values from table rows and map it to correct fields
                    $requestLog = [];
                    foreach ($row->getCells() as $header_index => $cell) {
                        if (isset($headers_map_to_table_fields[$doc_headers_indexes[$header_index]])) {
                            $requestLog[$headers_map_to_table_fields[$doc_headers_indexes[$header_index]]] = $cell->getValue();
                        }
                    }
                    try {
                        $rowResponse = $this->requestLogService->handleImportRow($requestLog);
                        // Write Success Result to File
                        $singleRow = WriterEntityFactory::createRow($this->requestLogService->makeResultRowWithResultFormat($rowResponse));
                        $writer->addRow($singleRow);
                        $imported_member_data++;
                    } catch (ImportRowException $e) {
                        // Write Data Validation Error to File
                        $requestLog = array_merge($requestLog, [
                            'ingestion_code' => $e->getCode(),
                            'ingestion_status' => $e->getMessage(),
                        ]);
                        // try {
                            $singleRow = WriterEntityFactory::createRow($this->requestLogService->makeResultRowWithResultFormat($requestLog));
                            $writer->addRow($singleRow);
                        // } catch (\Exception $e) {
                            $failed_member_data[] = ['row_number' => $index, 'error' => $e->getMessage(), 'data' => $requestLog];
                        // }
                    } catch (\Exception $e) {
                        // Write Server Error to File
                        $requestLog = array_merge($requestLog, [
                            'ingestion_code' => $e->getCode(),
                            'ingestion_status' => $e->getMessage(),
                        ]);
                        $singleRow = WriterEntityFactory::createRow($this->requestLogService->makeResultRowWithResultFormat($requestLog));
                        $writer->addRow($singleRow);
                        $failed_member_data[] = ['row_number' => $index, 'error' => $e->getMessage()];
                    }
                }
            }

            break; //only read first sheet
        }

        $reader->close();
        $writer->close();
        Storage::delete('temp/' . $file_name);
        // throw(404);
        return [
            'total_success_row' => $imported_member_data,
            'total_failed_row' => count($failed_member_data),
            'failed_row' => $failed_member_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\RequestLog')
                                ->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\RequestLog',
                    '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 function getServiceName($code){
        $service = DB::table('services')
            ->select('name')
            ->where('code', $code)
            ->get()
            ->first();
        return $service->name;
    }

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

        $source = $request->source == 'client-portal' ? 'C' : 'H';
        $organization = Organization::where(['id' => $request->organization_id, 'type' => 'hospital'])->first('code');
        $provideCode = $organization ? $organization->code : '';
        $member = Member::with('currentCorporate')->where(['id' => $request->member_id])->first();

        $data = [
            'source' => $source,
            'provideCode' => $provideCode,
            'date' => date('ymd'),
            'policy' => $member->currentPolicy->code,
            'member_code' => $member->member_id,
        ];

        $last_numeric_code = RequestLog::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;
        } else {
            $next_number = 1;
        }
        return self::makeCode($next_number, $data);
    }


    public static function makeCode($next_number, $data)
    {
        $sparator = '.';
        // Pastikan $next_number adalah integer positif
        $next_number = max(1, (int) $next_number);
        // Menghasilkan kode dengan format yang diinginkan
        return self::$code_prefix . $sparator. $data['source'] . $sparator. $data['provideCode'] . $sparator. $data['date'] . $sparator . $data['policy'] . $sparator. $data['member_code'] . $sparator. 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\RequestLog',
                    '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\RequestLog',
                    '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\RequestLog',
                    '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');
    }
}
