<?php

namespace Modules\HospitalPortal\Http\Controllers\Api;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;
use Modules\HospitalPortal\Helpers\ApiResponse;
use Illuminate\Support\Facades\DB;
use Modules\Internal\Http\Controllers\Api\RequestLogController as primeCenterRequestLog;
use App\Helpers\Helper;
use App\Models\File;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Support\Facades\View;

class RequestLogController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function requestLog(Request $request)
    {
        $data = [
            'member_id' => $request->member_id,
            'service_code' => $request->service_code,
            'organization_id' => $request->organization_id,
            'organization_name' => $request->organization_name,
            'address_provider' => $request->address_provider,
            'submission_date' => $request->submission_date,
        ];
        $validator = Validator::make($request->all(), [
            'member_id' => 'required',
            'service_code' => 'required',
            'submission_date' => 'required'
        ], [
            'member_id.required' => trans('Validation.required',['attribute' => 'Member ID']),
            'service_code.required' => trans('Validation.required',['attribute' => 'Service Code']),
            'submission_date.required' => trans('Validation.required',['attribute' => 'Submission Date']),
        ]);
        if($request->organization_id)
        {
            $validator = Validator::make($request->all(), [
                'organization_id' => 'required',
                'member_id' => 'required',
                'service_code' => 'required',
                'submission_date' => 'required'
            ], [
                'organization_id.required' => trans('Validation.required',['attribute' => 'Provider ID']),
                'member_id.required' => trans('Validation.required',['attribute' => 'Member ID']),
                'service_code.required' => trans('Validation.required',['attribute' => 'Service Code']),
                'submission_date.required' => trans('Validation.required',['attribute' => 'Submission Date']),
            ]);
        }
        if ($validator->fails())
        {
            return ApiResponse::apiResponse('Bad Request', $data, $validator->errors(), 400);
        }
        else
        {
            //insert data to organization
            try {
                if(!$request->organization_id)
                {
                    // Memulai transaksi
                    DB::beginTransaction();

                    // Membuat singkatan dari nama rumah sakit
                    $singkatan = "";
                    $words = explode(' ', $request->organization_name);

                    foreach ($words as $word) {
                        $singkatan .= strtoupper(substr($word, 0, 2));
                    }

                    // Membuat kode organisasi
                    $kodeOrganisasi = "ORG000" . $singkatan;

                    // Insert data ke tabel organizations
                    $organization_id = DB::table('organizations')
                        ->insertGetId([
                            'name' => $request->organization_name,
                            'code' => $kodeOrganisasi,
                            'type' => 'hospital',
                            'created_at' => now(),
                            'created_by' => auth()->user()->id
                        ]);

                    // Insert data ke tabel addresses
                    $address_id = DB::table('addresses')
                        ->insertGetId([
                            'text'=> $request->address_provider,
                            'addressable_type' => 'App\Models\Organization',
                            'addressable_id' => $organization_id,
                            'type' => 'hospital',
                            'created_at' => now(),
                            'created_by' => auth()->user()->id
                        ]);

                    // Update main_address_id di tabel organizations
                    DB::table('organizations')
                        ->where('organizations.id', '=', $organization_id)
                        ->update(['main_address_id' => $address_id]);

                    // Commit transaksi
                    DB::commit();
                    $request->merge(['organization_id' => $organization_id]);
                }

                $requestLogControllerInstance = new PrimeCenterRequestLog();
                $response = $requestLogControllerInstance->createNew($request);

                if($response->original['statusCode'] == 200)
                {
                    //send email
                    // Insert data notifications
                    $emailTo = 'alarm.center@linksehat.com';
                    $dataNotif = [
                        'email' => $emailTo,
                        'title' => 'Request LOG',
                        'description' => 'Request LOG from Hospital Portal',
                        'type' => 1,
                        'isUnRead' => true,
                        'created_by' => auth()->user()->id,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    $sendNotif = Helper::insertNotification($dataNotif);
                    // Send Email after insert notifications
                    if($sendNotif)
                    {
                        //send to alarm
                        $nameTo = 'Admin LinkSehat';
                        $dataEmail = [
                            'email' => $emailTo,
                            'name' => $nameTo,
                            'subject' => 'Request LOG from Hospital Portal'. ' '.date('Y-m-d H:i:s'),
                            'body' => View::make('email/notif_email', ['name' => $nameTo, 'link' => 'https://primecenter.linksehat.com/'])->render(),
                        ];
                        Helper::sendEmail($dataEmail);
                    }
                    return ApiResponse::apiResponse("Success", $data, trans('Message.success'), 200);
                }
                else
                {
                    return ApiResponse::apiResponse('Server Error', $data, trans('Message.server_error'), 500);
                }
            } catch (\Exception $e) {
                // Rollback transaksi jika terjadi kesalahan
                DB::rollBack();

                // Handle error, bisa di-log atau dikembalikan sebagai response
                return ApiResponse::apiResponse('Server Error', $data, $e->getMessage(), 500);
            }
        }
    }

    public function getRequestLog(Request $request)
    {

        $limit = $request->has('per_page') ? $request->input('per_page') : 10;

        $results = DB::table('request_logs')
                    ->leftJoin('members', 'request_logs.member_id', '=', 'members.id')
                    ->where('request_logs.deleted_at', null)
                    ->when($request->input('search'), function ($query, $search) {
                        $query->where(function ($query) use ($search) {
                            $query->orWhere('request_logs.code', 'like', "%" . $search . "%")
                                ->orWhere('members.name', 'like', "%" . $search . "%")
                                ->orWhere('request_logs.submission_date', 'like', "%" . $search . "%");
                        });
                    })
                    ->when($request->has('orderBy'), function ($query) use ($request) {
                        $orderBy = $request->orderBy;
                        $direction = $request->order ?? 'asc';

                        $query->orderBy($orderBy, $direction);
                    })
                    ->when($request->input('start_date') && !$request->input('end_date'), function ($query, $start_date) {
                        $query->where(function ($query) use ($start_date) {
                            $query->where('request_logs.submission_date', '<', $start_date);
                        });
                    })
                    ->when($request->input('status'), function ($query, $status) {
                        $query->where(function ($query) use ($status) {

                            if ($status === 'requested') {
                                $query->where('request_logs.status', '=', 'requested');
                            }

                            if ($status === 'reviewed') {
                                $query->where('request_logs.status', '=', 'approved');
                            }

                            if ($status === 'approved') {
                                $query->where('request_logs.status', '=', 'approved');
                            }

                            if ($status === 'declined') {
                                $query->where('request_logs.status', '=', 'declined');
                            }

                        });
                    })
                    ->select(
                        'request_logs.id',
                        'request_logs.member_id',
                        'request_logs.final_log',
                        'request_logs.code',
                        'members.name as full_name',
                        'members.member_id as no_polis',
                        'members.birth_date',
                        'request_logs.service_code',
                        DB::raw('
                            CASE
                                WHEN request_logs.status = "requested" THEN "requested"
                                WHEN request_logs.status = "approved" THEN "approved"
                                WHEN request_logs.status = "declined" THEN "declined"
                                WHEN request_logs.status = "reviewed" THEN "reviewed"
                                ELSE ""
                            END AS status
                        '),
                        DB::raw('
                            (SELECT organizations.name FROM organizations WHERE organizations.id = request_logs.organization_id LIMIT 1) AS provider
                        '),
                        'request_logs.submission_date',
                        'request_logs.approved_at')
                    ->paginate($limit);
        return response()->json(Helper::paginateResources($results));
    }

    public function getFinalLog(Request $request)
    {

        $limit = $request->has('per_page') ? $request->input('per_page') : 10;

        $results = DB::table('request_logs')
                    ->leftJoin('members', 'request_logs.member_id', '=', 'members.id')
                    ->when($request->input('search'), function ($query, $search) {
                        $query->where(function ($query) use ($search) {
                            $query->orWhere('request_logs.code', 'like', "%" . $search . "%")
                                ->orWhere('members.name', 'like', "%" . $search . "%")
                                ->orWhere('request_logs.submission_date', 'like', "%" . $search . "%")
                                ->orWhere('request_logs.discharge_date', 'like', "%" . $search . "%")
                                ->orWhereRaw('(SELECT services.name FROM services WHERE services.code = request_logs.service_code LIMIT 1) LIKE ?', ["%" . $search . "%"]);
                        });
                    })
                    ->when($request->has('orderBy'), function ($query) use ($request) {
                        $orderBy = $request->orderBy;
                        $direction = $request->order ?? 'asc';

                        $query->orderBy($orderBy, $direction);
                    })
                    ->when($request->input('start_date') && !$request->input('end_date'), function ($query, $start_date) {
                        $query->where(function ($query) use ($start_date) {
                            $query->where('request_logs.submission_date', '<', $start_date);
                        });
                    })
                    ->when($request->input('status'), function ($query, $status) {
                        $query->where(function ($query) use ($status) {

                            if ($status === 'requested') {
                                $query->where('request_logs.status_final_log', '=', 'requested');
                            }

                            if ($status === 'reviewed') {
                                $query->where('request_logs.status_final_log', '=', 'approved');
                            }

                            if ($status === 'approved') {
                                $query->where('request_logs.status_final_log', '=', 'approved');
                            }

                            if ($status === 'declined') {
                                $query->where('request_logs.status_final_log', '=', 'declined');
                            }

                        });
                    })
                    ->where('request_logs.final_log', '=', 1)
                    ->select(
                        'request_logs.id',
                        'request_logs.final_log',
                        'request_logs.code',
                        'members.name as full_name',
                        'members.member_id as no_polis',
                        'members.id AS member_id',
                        'request_logs.service_code',
                        'members.birth_date',
                        DB::raw('
                            CASE
                                WHEN request_logs.status_final_log = "requested" THEN "requested"
                                WHEN request_logs.status_final_log = "approved" THEN "approved"
                                WHEN request_logs.status_final_log = "declined" THEN "declined"
                                WHEN request_logs.status_final_log = "reviewed" THEN "reviewed"
                                ELSE ""
                            END AS status
                        '),
                        'request_logs.submission_date',
                        'request_logs.approved_final_log_at',
                        'request_logs.discharge_date',
                        DB::raw('
                            (SELECT services.name FROM services WHERE services.code = request_logs.service_code LIMIT 1) AS service_type
                        '),
                        DB::raw('
                            (SELECT organizations.name FROM organizations WHERE organizations.id = request_logs.organization_id LIMIT 1) AS provider
                        '),
                        DB::raw('
                            (Select request_log_id FROM claim_requests WHERE claim_requests.request_log_id = request_logs.id LIMIT 1) AS check_claim
                        ')
                        )
                    ->paginate($limit);
        return response()->json(Helper::paginateResources($results));
    }

    public function requestFinalLog(Request $request)
    {
        $data = [
            'request_logs_id' => $request->request_logs_id,
            'discharge_date' => $request->discharge_date,
        ];
        $validator = Validator::make($request->all(), [
            'request_logs_id' => 'required',
            'discharge_date' => 'required'
        ], [
            'request_logs_id.required' => trans('Validation.required',['attribute' => 'Request Logs ID']),
            'discharge_date.required' => trans('Validation.required',['attribute' => 'Discharge Date'])
        ]);
        if ($validator->fails())
        {
            return ApiResponse::apiResponse('Bad Request', $data, $validator->errors(), 400);
        }
        else
        {
            try {
                DB::beginTransaction();
                DB::table('request_logs')
                ->where('request_logs.id', '=', $request->request_logs_id)
                ->update([
                    'status_final_log' => 'requested',
                    'final_log' => 1,
                    'discharge_date' => $request->discharge_date, 
                    'created_final_by'=> auth()->user()->id,
                    'created_final_at'=> date('Y-m-d H:i:s'),
                ]);
                if ($request->hasFile('result_files')) {
                    foreach ($request->result_files as $file) {
                        $pathFile = File::storeFile('final-log-result', $request->request_logs_id, $file);
                        File::updateOrCreate([
                            'fileable_type' => 'App\Models\RequestLog',
                            'fileable_id' => $request->request_logs_id,
                            'type' => 'final-log-result',
                            'name' => File::getFileName('final-log-result', $request->request_logs_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', $request->request_logs_id, $file);
                        File::updateOrCreate([
                            'fileable_type' => 'App\Models\RequestLog',
                            'fileable_id' => $request->request_logs_id,
                            'type' => 'final-log-diagnosis',
                            'name' => File::getFileName('final-log-diagnosis', $request->request_logs_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', $request->request_logs_id, $file);
                        File::updateOrCreate([
                            'fileable_type' => 'App\Models\RequestLog',
                            'fileable_id' => $request->request_logs_id,
                            'type' => 'final-log-kondisi',
                            'name' => File::getFileName('final-log-kondisi', $request->request_logs_id, $file),
                            'original_name' => $file->getClientOriginalName(),
                            'extension' => $file->getClientOriginalExtension(),
                            'path' => $pathFile,
                            'created_by' => auth()->user()->id,
                            'updated_by' => auth()->user()->id,
                        ]);
                    }
                }
                DB::commit();
                //send email
                // Insert data notifications
                $emailTo = 'alarm.center@linksehat.com';
                $dataNotif = [
                    'email' => $emailTo,
                    'title' => 'Request Final LOG',
                    'description' => 'Request Final LOG from Hospital Portal',
                    'type' => 1,
                    'isUnRead' => true,
                    'created_by' => auth()->user()->id,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                $sendNotif = Helper::insertNotification($dataNotif);
                // Send Email after insert notifications
                if($sendNotif)
                {
                    //send to alarm
                    $nameTo = 'Admin LinkSehat';
                    $dataEmail = [
                        'email' => $emailTo,
                        'name' => $nameTo,
                        'subject' => 'Request Final LOG from Hospital Portal'. ' '.date('Y-m-d H:i:s'),
                        'body' => View::make('email/notif_email', ['name' => $nameTo, 'link' => 'https://primecenter.linksehat.com/'])->render(),
                    ];
                    Helper::sendEmail($dataEmail);
                }
                return ApiResponse::apiResponse('Success', $data, trans('Message.success'), 200);
            }
            catch (\Exception $e) {
                DB::rollback();
                return ApiResponse::apiResponse("Error", $data, $e->getMessage(), 500);
            }
        }
    }

    public function downlodLog($request_log_id)
    {
        $dataRequestLog = DB::table('request_logs')
        ->where('request_logs.id', '=', $request_log_id)
        ->first();
        $data['dataRequestLog'] = $dataRequestLog;
        $dataMember = DB::table('members')
        ->where('members.id', '=', $dataRequestLog->member_id)
        ->select(
            'members.nric',
            'members.id',
            'members.principal_id',
            'members.name',
            'members.birth_date',
            'members.member_id',
            'members.gender',
            DB::raw('
                (Select persons.nik FROM persons WHERE persons.id = members.person_id LIMIT 1) AS nik
            '),
            // DB::raw('
            //     "LinkSehat" AS penjamin
            // '),
            DB::raw('
                (Select corporates.name FROM corporates
                    LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                    WHERE corporate_employees.member_id = members.id LIMIT 1) AS nama_perusahaan
            '),
            DB::raw('
                (Select corporates.id FROM corporates
                    LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                    WHERE corporate_employees.member_id = members.id LIMIT 1) AS id_perusahaan
            '),
            DB::raw('
                (Select corporates.code FROM corporates
                    LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                    WHERE corporate_employees.member_id = members.id LIMIT 1) AS code_perusahaan
            '),
            DB::raw('
                (Select services.name FROM services
                    WHERE services.code = "'.$dataRequestLog->service_code.'" LIMIT 1) AS jenis_perwatan
            '),
            DB::raw('
                (Select member_policies.policy_id FROM member_policies WHERE member_policies.member_id = members.member_id LIMIT 1) AS no_polis
            '),
            DB::raw('
            (Select member_policies.status FROM member_policies WHERE member_policies.member_id = members.member_id LIMIT 1) AS status_polis
            '),
            DB::raw('
                (Select plans.code FROM member_plans
                    LEFT JOIN plans ON plans.id = member_plans.plan_id
                    WHERE member_plans.member_id = members.id AND plans.service_code = "'.$dataRequestLog->service_code.'" LIMIT 1) AS code_plan
            '),
            DB::raw('
                (Select plans.limit_rules FROM member_plans
                    LEFT JOIN plans ON plans.id = member_plans.plan_id
                    WHERE member_plans.member_id = members.id LIMIT 1) AS limit_rules
            '),
            DB::raw('
                "IDR" AS mata_uang
            '),
            'members.members_effective_date AS mulai',
            'members.members_expire_date AS akhir'
            )
        ->first();
        $data['namaKaryawan'] = '';
        if($dataMember->principal_id)
        {
            $dataNamaKaryawan =  DB::table('members')
            ->where('members.member_id', '=', $dataMember->principal_id)
            ->select('members.name')
            ->first();
            $data['namaKaryawan'] = $dataNamaKaryawan->name;
        }
        else{
            $data['namaKaryawan'] = $dataMember->name;
        }

        $data['dataMember'] = $dataMember;

        $data['request_logs'] = $dataRequestLog;

        $dataRumahSakit = DB::table('organizations')
        ->leftJoin('addresses', 'addresses.addressable_id', '=', 'organizations.id')
        ->where('organizations.id', '=', $dataRequestLog->organization_id)
        ->where('addresses.addressable_type', '=', 'App\Models\Organization')
        ->select('organizations.name AS nama_rumahsakit', 'addresses.text AS alamat_rumahsakit', 'organizations.corporate_id_partner')
        ->first();

        $data['rumahSakit'] = $dataRumahSakit;

        //get penjamin
        $data['penjamin'] = 'LinkSehat';
        if($dataRumahSakit->corporate_id_partner)
        {
            $corporate_id_partners = explode(',', $dataRumahSakit->corporate_id_partner);
            $valueToCheck = $dataMember->id_perusahaan;

            if (in_array($valueToCheck, $corporate_id_partners)) {
                $data['penjamin'] = $dataMember->nama_perusahaan;
            }
        }

        $logoPerusahaan = DB::table('files')
        ->leftJoin('corporate_employees', 'corporate_employees.corporate_id', '=', 'files.fileable_id')
        ->leftJoin('corporates', 'corporate_employees.corporate_id', '=', 'corporates.id')
        ->where('corporate_employees.member_id', '=', $dataMember->id)
        ->where('files.fileable_type', '=', 'App\Models\Corporate')
        ->select('files.path', 'corporates.code', 'corporates.name')
        ->orderBy('files.id', 'desc')
        ->first();

        $data['logoPerusahaan'] = $logoPerusahaan;

        $signatureDr = DB::table('signatures')
        ->leftJoin('corporate_manager', 'corporate_manager.user_id', '=', 'signatures.user_id')
        ->leftJoin('files', 'files.fileable_id', '=', 'signatures.id')
        ->where('files.fileable_type', '=', 'App\Models\Signature')
        ->where('signatures.type', '=', 1)
        ->where('corporate_manager.corporate_id', '=', $dataMember->id_perusahaan)
        ->select('files.path')
        ->first();

        $data['signatureDr'] = $signatureDr;

        $signatureAd = DB::table('signatures')
        ->leftJoin('files', 'files.fileable_id', '=', 'signatures.id')
        ->where('files.fileable_type', '=', 'App\Models\Signature')
        ->where('signatures.type', '=', 2)
        ->where('signatures.user_id', '=', $dataRequestLog->approved_by)
        ->select(
            'files.path',
            DB::raw('
                (Select persons.name FROM users
                    LEFT JOIN persons ON users.person_id = persons.id
                    WHERE users.id = "'.$dataRequestLog->approved_by.'" LIMIT 1) AS name_approve
            ')
        )
        ->first();

        $data['signatureAd'] = $signatureAd;

        $pdf = new Dompdf();

        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isPhpEnabled', true);
        $options->set(['isRemoteEnabled' => true]);
        $pdf->setOptions($options);

        $pdf->setPaper('A4', 'portrait');

        // Halaman 1
        $html1 = view('pdf.req_log_page_1', $data);

        // Halaman 2
        // $html2 = view('pdf.req_log_page_2', $data);

        // Gabung konten HTML dari dua tampilan
        // $htmlCombined = $html1 . $html2;
        $htmlCombined = $html1;

        $pdf->loadHtml($htmlCombined);
        $pdf->render();

        $headers = [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="file.pdf"',
        ];

        return response($pdf->output(), 200, $headers);
    }

    public function downlodFinalLog($request_log_id)
    {
        $dataRequestLog = DB::table('request_logs')
        ->where('request_logs.id', '=', $request_log_id)
        ->first();
        $data['dataRequestLog'] = $dataRequestLog;
        $dataMember = DB::table('members')
        ->where('members.id', '=', $dataRequestLog->member_id)
        ->select(
            'members.nric',
            'members.id',
            'members.principal_id',
            'members.name',
            'members.birth_date',
            'members.member_id',
            'members.gender',
            DB::raw('
                (Select persons.nik FROM persons WHERE persons.id = members.person_id LIMIT 1) AS nik
            '),
            // DB::raw('
            //     "LinkSehat" AS penjamin
            // '),
            DB::raw('
                (Select corporates.name FROM corporates
                    LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                    WHERE corporate_employees.member_id = members.id LIMIT 1) AS nama_perusahaan
            '),
            DB::raw('
                (Select corporates.id FROM corporates
                    LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                    WHERE corporate_employees.member_id = members.id LIMIT 1) AS id_perusahaan
            '),
            DB::raw('
                (Select corporates.code FROM corporates
                    LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                    WHERE corporate_employees.member_id = members.id LIMIT 1) AS code_perusahaan
            '),
            DB::raw('
                (Select services.name FROM services
                    WHERE services.code = "'.$dataRequestLog->service_code.'" LIMIT 1) AS jenis_perwatan
            '),
            DB::raw('
                (Select member_policies.policy_id FROM member_policies WHERE member_policies.member_id = members.member_id LIMIT 1) AS no_polis
            '),
            DB::raw('
            (Select member_policies.status FROM member_policies WHERE member_policies.member_id = members.member_id LIMIT 1) AS status_polis
            '),
            DB::raw('
                (Select plans.code FROM member_plans
                    LEFT JOIN plans ON plans.id = member_plans.plan_id
                    WHERE member_plans.member_id = members.id AND plans.service_code = "'.$dataRequestLog->service_code.'" LIMIT 1) AS code_plan
            '),
            DB::raw('
                (Select plans.limit_rules FROM member_plans
                    LEFT JOIN plans ON plans.id = member_plans.plan_id
                    WHERE member_plans.member_id = members.id LIMIT 1) AS limit_rules
            '),
            DB::raw('
                "IDR" AS mata_uang
            '),
            'members.members_effective_date AS mulai',
            'members.members_expire_date AS akhir'
            )
        ->first();
        $data['namaKaryawan'] = '';
        if($dataMember->principal_id)
        {
            $dataNamaKaryawan =  DB::table('members')
            ->where('members.member_id', '=', $dataMember->principal_id)
            ->select('members.name')
            ->limit(1)
            ->first();
            $data['namaKaryawan'] = $dataNamaKaryawan->name;
        }
        else{
            $data['namaKaryawan'] = $dataMember->name;
        }

        $data['dataMember'] = $dataMember;

        $data['request_logs'] = $dataRequestLog;

        $dataClaimLog =  DB::table('request_log_benefits')
        ->where('request_log_benefits.request_log_id', '=', $request_log_id)
        ->select(
            '*',
            DB::raw('
                (Select benefits.description FROM benefits
                    WHERE benefits.id = request_log_benefits.benefit_id LIMIT 1) AS benfit
            '),
            DB::raw('
                (Select benefits.code FROM benefits
                    WHERE benefits.id = request_log_benefits.benefit_id LIMIT 1) AS code
            ')
        )
        ->get();

        $data['dataClaimLog'] = $dataClaimLog;


        $dataRumahSakit = DB::table('organizations')
        ->leftJoin('addresses', 'addresses.addressable_id', '=', 'organizations.id')
        ->where('organizations.id', '=', $dataRequestLog->organization_id)
        ->where('addresses.addressable_type', '=', 'App\Models\Organization')
        ->select('organizations.name AS nama_rumahsakit', 'addresses.text AS alamat_rumahsakit', 'organizations.corporate_id_partner')
        ->first();

        $data['rumahSakit'] = $dataRumahSakit;

        //get penjamin
        $data['penjamin'] = 'LinkSehat';
        if($dataRumahSakit->corporate_id_partner)
        {
            $corporate_id_partners = explode(',', $dataRumahSakit->corporate_id_partner);
            $valueToCheck = $dataMember->id_perusahaan;

            if (in_array($valueToCheck, $corporate_id_partners)) {
                $data['penjamin'] = $dataMember->nama_perusahaan;
            }
        }

        $logoPerusahaan = DB::table('files')
        ->leftJoin('corporate_employees', 'corporate_employees.corporate_id', '=', 'files.fileable_id')
        ->leftJoin('corporates', 'corporate_employees.corporate_id', '=', 'corporates.id')
        ->where('corporate_employees.member_id', '=', $dataMember->id)
        ->where('files.fileable_type', '=', 'App\Models\Corporate')
        ->select('files.path', 'corporates.code', 'corporates.name')
        ->orderBy('files.id', 'desc')
        ->first();

        $data['logoPerusahaan'] = $logoPerusahaan;

        $signatureDr = DB::table('signatures')
        ->leftJoin('corporate_manager', 'corporate_manager.user_id', '=', 'signatures.user_id')
        ->leftJoin('files', 'files.fileable_id', '=', 'signatures.id')
        ->where('files.fileable_type', '=', 'App\Models\Signature')
        ->where('signatures.type', '=', 1)
        ->where('corporate_manager.corporate_id', '=', $dataMember->id_perusahaan)
        ->select('files.path')
        ->first();

        $data['signatureDr'] = $signatureDr;

        $signatureAd = DB::table('signatures')
        ->leftJoin('files', 'files.fileable_id', '=', 'signatures.id')
        ->where('files.fileable_type', '=', 'App\Models\Signature')
        ->where('signatures.type', '=', 2)
        ->where('signatures.user_id', '=', $dataRequestLog->approved_final_log_by)
        ->select(
            'files.path',
            DB::raw('
                (Select persons.name FROM users
                    LEFT JOIN persons ON users.person_id = persons.id
                    WHERE users.id = "'.$dataRequestLog->approved_final_log_by.'" LIMIT 1) AS name_approve
            ')
        )
        ->first();

        $data['signatureAd'] = $signatureAd;

        $dataDiagnosis = [];
        if($dataRequestLog->diagnosis)
        {
            $dataDiagnosiCodes = explode(',', $dataRequestLog->diagnosis);  
            foreach ($dataDiagnosiCodes as $diagnosisCode)
            {
                $diagnoisis = DB::table('icd')
                ->where('icd.code', '=', $diagnosisCode)
                ->select('icd.name', 'icd.code')
                ->first();
                array_push($dataDiagnosis, $diagnoisis);
            }
        }

        $data['dataDiagnosis'] = $dataDiagnosis; 
        

        $pdf = new Dompdf();

        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isPhpEnabled', true);
        $options->set(['isRemoteEnabled' => true]);
        $pdf->setOptions($options);

        // Halaman 1
        $html1 = view('pdf.final_log_page_1', $data);

        // Halaman 2
        $html2 = view('pdf.final_log_page_2', $data);

        // Gabung konten HTML dari dua tampilan
        $htmlCombined = $html1 . $html2;

        $pdf->loadHtml($htmlCombined);
        $pdf->render();

        $headers = [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="file.pdf"',
        ];

        return response($pdf->output(), 200, $headers);
    }
}
