<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\RequestLog;
use App\Models\RequestLogBenefit;
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\ReportLogResource;
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 ReportLogController extends Controller
{


    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(ReportLogResource::collection($requestLog));
    }

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

    /**
     * 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));
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('internal::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {

    }

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

    }


    /**
     * Generate Export Excel Request LOG
     */

    public function generateDataRequestLogExcel(){
        Helper::setCustomPHPIniSettings();
        $file_name = 'Data Request LOG';
        // Membuat penulis entitas Spout
        $writer = WriterEntityFactory::createXLSXWriter();
         // Membuka penulis untuk menulis ke file
        $writer->openToFile(public_path('files/Report-Request-Final-LOG.xlsx'));
        $headerArray = [
            'Code',
            'Member Name',
            'Member Code',
            'GL Create Time',
            'GL Submit Time',
            'GL Create By',
            'FGL Create Time',
            'FGL Submit Time',
            'FGL Created By',
            'Service',
            'Provider',
            'Document Qty',
            'Duration GL',
            'Duration FGL',
            'Status GL',
            'Status Final GL',
            'Import By Excel'
        ];
       // Sheet 1
        $writer->getCurrentSheet()->setName('Data');
        $headers_map_to_table_fields = $headerArray;
        $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();

        foreach ($dataRequestLog as $index => $row){
            $serviceName = Helper::serviceName($row['service_code']);
            $provider = Organization::where('id', $row['organization_id'])->first();
            $documentQty = File::where(['fileable_type' => 'App\Models\RequestLog', 'fileable_id' => $row['id']])->get()->toArray();
            $parsedDateTime = Carbon::parse($row['created_at']);
            // $parsedDateTime->tz = 'Asia/Makassar';
            $formattedDateTime = $parsedDateTime->format('Y-m-d H:i:s');

            $timeInsertBenefit = RequestLogBenefit::where('request_log_id', $row['id'])->first();

            if ($timeInsertBenefit){
                $created_final_at = Carbon::parse($timeInsertBenefit->created_at);
                $created_final_at = $created_final_at->format('Y-m-d H:i:s');

                $durationFinalGl = Helper::differenceTime($timeInsertBenefit->created_at, $row['approved_final_log_at']);
            } else {
                $durationFinalGl = 0;
                $created_final_at = false;
            }

            if ($row['approved_at']){
                $durationGl = Helper::differenceTime($formattedDateTime, $row['approved_at']);
            } else {
                $durationGl = 0;
            }

            $approveByFgl = '-';
            if ($row['import_system']) {
                $approveByFgl = 'Import By Excel';
            } else if ($row['final_log'] == 1 &&  $row['status_final_log'] == 'requested'){
                $approveByFgl = '-';
            } else if ($row['final_log'] == 1) {
                $approveByFgl = Helper::userName($row['approved_final_log_by']);
            }


            $rowData = [
                $row['code'], // code
                $row['member'] ? $row['member']['name'] : '', // name
                $row['member'] ? $row['member']['member_id'] : '', // member id
                $formattedDateTime ? $formattedDateTime : "-" , // created at
                $row['approved_at'] ? $row['approved_at'] : '-', // submission date
                $row['approved_by'] ? Helper::userName($row['approved_by']) : '-', // created by
                $created_final_at ? $created_final_at : "-", // fgl create time
                $row['approved_final_log_at'] ? $row['approved_final_log_at'] : "", // fgl submit time
                $approveByFgl, // fgl create by
                $serviceName, // service
                $provider ? $provider->name : '-', // provider
                count($documentQty), // dokument qty
                $durationGl, // duration gl
                $row['final_log'] == 1 ? $durationFinalGl : '-', // duration fgl
                $row['status'] ?? '-', // status gl
                $row['status_final_log'] ?? '-', // status fgl
                $row['import_system'] == 1 ? 'True' : 'False', // status fgl
            ];
            $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/Report-Request-Final-LOG.xlsx')
        ]);
    }

}
