<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Exceptions\ImportRowException;
use App\Helpers\Helper;
use App\Imports\PlansImport;
use App\Models\Benefit;
use App\Models\Claim;
use App\Models\Corporate;
use App\Models\CorporateBenefit;
use App\Models\Plan;
use App\Models\Service;
use App\Models\User;
use App\Services\ImportService;
use DB;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use App\Models\File;
use Illuminate\Support\Facades\File as FacadesFile;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Modules\Internal\Services\CorporateService;
use App\Models\FilesDoc;

class CorporateController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $corporates = Corporate::query()
            ->when($request->search, function ($query, $search) {
                return $query->where('name', 'LIKE', '%' . $search . '%')
                    ->orWhere('code', 'LIKE', '%' . $search . '%');
            })
            ->with('currentPolicy', 'subCorporates')
            ->withCount([
                'employees',
                'corporateBenefits',
                'corporatePlans',

                // 'claims'
            ])
            ->where('type', 'corporate')
            ->paginate(10);

        return $corporates;
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        $corporateGroups = Corporate::whereNull('parent_id')->get()->map(function ($corporate) {
            return [
                'value' => $corporate->id,
                'label' => $corporate->name . ' (' . $corporate->code . ')',
            ];
        });

        return response()->json([
            'corporate_groups' => $corporateGroups
        ]);
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {

        $request->validate([
            'code' => 'required|regex:/^[a-zA-Z0-9_]+$/',
            'name' => 'required',
            'payor_id' => 'required',
            // 'logo' => 'required',
            'policy_code' => 'required_with:policy_id',
            'policy_total_premi' => 'required_with:policy_code',
            'policy_minimal_deposit_percentage' => 'required_with:policy_code',
            'policy_minimal_deposit_net' => 'required_with:policy_code',
            'policy_minimal_alert_percentage' => 'required_with:policy_code',
            'policy_minimal_alert_net' => 'required_with:policy_code',
            'policy_stop_service_percentage' => 'required_with:policy_code',
            'policy_stop_service_net' => 'required_with:policy_code',
        ]);
        try {
            DB::beginTransaction();
            $corporate_data = $request->all();
            $corporate_data['type'] = !empty($corporate_data['type']) ? $corporate_data['type'] : 'corporate';

            $newCorporate = Corporate::create($request->all());
            if ($request->has('policy_code') && !empty($request->policy_code)) {
                $newCorporate->policies()->create([
                    'code' => $request->policy_code ?? NULL,
                    'payor_id' => $request->payor_id ?? NULL,
                    'total_premi' => $request->policy_total_premi ?? NULL,
                    'minimal_deposit_percentage' => $request->policy_minimal_deposit_percentage ?? NULL,
                    'minimal_deposit_net' => $request->policy_minimal_deposit_net ?? NULL,
                    'minimal_alert_percentage' => $request->policy_minimal_alert_percentage ?? NULL,
                    'minimal_alert_net' => $request->policy_minimal_alert_net ?? NULL,
                    'minimal_stop_service_percentage' => $request->policy_stop_service_percentage ?? NULL,
                    'minimal_stop_service_net' => $request->policy_stop_service_net ?? NULL,
                    'start' => $request->policy_start ?? NULL,
                    'end' => $request->policy_end ?? NULL,
                    'active' => $request->policy_active ?? true,
                ]);
            }

            // Service
            $services = [
                [
                    'id' => 1,
                    'name' => 'Outpatient',
                    'code' => 'OP',
                    'description' => 'Outpatient',
                ],
                [
                    'id' => 2,
                    'name' => 'Inpatient',
                    'code' => 'IP',
                    'description' => 'Inpatient',
                ],
                [
                    'id' => 3,
                    'name' => 'Dental',
                    'code' => 'DE',
                    'description' => 'Dental',
                ],
                [
                    'id' => 4,
                    'name' => 'Maternal',
                    'code' => 'MA',
                    'description' => 'Maternal',
                ],
                [
                    'id' => 5,
                    'name' => 'Optical',
                    'code' => 'OPT',
                    'description' => 'Optical',
                ],
                [
                    'id' => 6,
                    'name' => 'Medical Check Up',
                    'code' => 'MCU',
                    'description' => 'Medical Check Up',
                ],
            ];

            foreach ($services as $service) {

                $corporateService = $newCorporate->corporateServices()->create([
                    'service_code' => $service['code'],
                    'status' => 'inactive'
                ]);

                $corporateService->configs()->insert([
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'gp_external_doctor_online',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'gp_external_doctor_offline',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'gp_internal_doctor_online',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'gp_internal_doctor_offline',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'sp_external_doctor_online',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'sp_external_doctor_offline',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'sp_internal_doctor_online',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'sp_internal_doctor_offline',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'vitamins',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'delivery_fee',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'general_practitioner_fee',
                        'value' => false,
                    ],
                    [
                        'corporate_service_id' => $corporateService->id,
                        'name' => 'specialist_practitioner_fee',
                        'value' => false,
                    ],
                ]);
            }

            // TODO Remove This
            // Assign Managed to Manager one
            $managerOne = User::where('email', 'manager+one@gmail.com')->first();
            $managerOne->managedCorporates()->attach($newCorporate);

            if ($request->hasFile('logo')) {
                $pathFileAvatar = File::storeFile('avatar', $newCorporate->id, $request->file('logo'));
                $newCorporate->files()->updateOrCreate([
                    'type' => 'avatar',
                    'name' => File::getFileName('avatar', $newCorporate->id, $request->file('logo')),
                    'extension' => $request->file('logo')->getClientOriginalExtension(),
                    'path' => $pathFileAvatar,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

        return $newCorporate;
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        $corporate = Corporate::query()
            ->with(['currentPolicy', 'plans'])
            ->withCount('corporatePlans')
            ->withCount('employees')
            // ->withCount('employees.claims')
            ->findOrFail($id);
        $plans = $corporate['plans']->map(function ($plan) {
            return [
                'id' => $plan['id'],
                'code' => $plan['code'],
                'corporate_id' => $plan['corporate_id'],
                'corporate_plan_id' => $plan['corporate_plan_id'],
            ];
        });

        unset($corporate['plans']);
        $corporate['plans'] = $plans;

        return response()->json($corporate);
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        $corporate = Corporate::findOrFail($id)->load('currentPolicy');

        return $corporate;
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'code' => 'required|regex:/^[a-zA-Z0-9_]+$/',
            'payor_id' => 'required',
            'name' => 'required',
            'policy_code' => 'required_with:policy_id',
            'policy_total_premi' => 'required_with:policy_code',
            'policy_minimal_deposit_percentage' => 'required_with:policy_code',
            'policy_minimal_deposit_net' => 'required_with:policy_code',
            'policy_minimal_alert_percentage' => 'required_with:policy_code',
            'policy_minimal_alert_net' => 'required_with:policy_code',
            'policy_stop_service_percentage' => 'required_with:policy_code',
            'policy_stop_service_net' => 'required_with:policy_code',
        ]);

        try {
            DB::beginTransaction();
            //karena pake formdata
            $linkingRules = $request->linking_rules;
            $linkingRules = explode(',', $linkingRules);

            $corporate = Corporate::findOrFail($id);
            $corporate->fill($request->all());
            $corporate->linking_rules = $linkingRules;
            $corporate->save();

            $corporate->policies()->updateOrCreate(
                ['id' => $request->policy_id],
                [
                    'code' => $request->policy_code ?? NULL,
                    'payor_id' => $request->payor_id ?? NULL,
                    'total_premi' => $request->policy_total_premi ?? NULL,
                    'minimal_deposit_percentage' => $request->policy_minimal_deposit_percentage ?? NULL,
                    'minimal_deposit_net' => $request->policy_minimal_deposit_net ?? NULL,
                    'minimal_alert_percentage' => $request->policy_minimal_alert_percentage ?? NULL,
                    'minimal_alert_net' => $request->policy_minimal_alert_net ?? NULL,
                    'minimal_stop_service_percentage' => $request->policy_stop_service_percentage ?? NULL,
                    'minimal_stop_service_net' => $request->policy_stop_service_net ?? NULL,
                    'start' => $request->policy_start ?? NULL,
                    'end' => $request->policy_end ?? NULL,
                    'active' => $request->policy_active ?? true,
                ]
            );

            if ($request->hasFile('logo')) {
                $pathFileAvatar = File::storeFile('avatar', $corporate->id, $request->file('logo'));

                $corporate->files()->updateOrCreate([
                    'type' => 'avatar',
                    'name' => File::getFileName('avatar', $corporate->id, $request->file('logo')),
                    'extension' => $request->file('logo')->getClientOriginalExtension(),
                    'path' => $pathFileAvatar,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

        return $corporate;
    }

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

    public function activation(Request $request, $corporate_id)
    {
        $request->validate([
            'active' => 'required',
            'reason' => 'required'
        ]);

        // abort(404);

        $corporate = Corporate::findOrFail($corporate_id);
        $corporate->active = $request->active == 0 ? 1 : 0;
        $corporate->reason = $request->reason;

        if ($corporate->save()) {
            return response()->json([
                'corporate' => $corporate,
                'message' => 'Status Updated Successfully'
            ]);
        }
    }

    public function importPlanBenefit(Request $request, $corporate_id)
    {
        $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);
        $corporate = Corporate::with(['plans'])->findOrFail($corporate_id);
        $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 (!in_array($sheet->getName(), ['Plan', 'Benefit'])) {
                continue;
            } else {
                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());
                }

                if ($sheet->getName() == 'Plan') {
                    $headers_map_to_table_fields = Plan::$doc_headers_to_field_map;
                } else if ($sheet->getName() == 'Benefit') {
                    $headers_map_to_table_fields = CorporateBenefit::$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->read($fileRead);
                // $import->write($fileWrite, 'xsls');
                $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
                        $corporateService = new CorporateService();
                        if ($sheet->getName() == 'Plan') {
                            $corporateService->handlePlanRow($corporate, $row_data);
                        } else if ($sheet->getName() == 'Benefit') {
                            $corporateService->handleBenefitRow($corporate, $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');
                        $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 deleteAllImportPlanBenefit(Request $request, $corporate_id){
        $deleteBenefit = CorporateBenefit::where('corporate_id', $corporate_id)->delete();
        $deletePlan = Plan::where('corporate_id', $corporate_id)->delete();
        if ( $deleteBenefit && $deletePlan ){
            return Helper::responseJson(data: [], message: 'Berhasil delete semua benefit');
        } else {
            return Helper::responseJson(data: [], message: 'Gagal delete semua benefit', statusCode:404);
        }

    }

    public function importDocumentExample($document_type)
    {
        switch ($document_type) {
            case 'plan-benefit':
                return Helper::responseJson([
                    'file_name' => "Corporate Plan & Benefit Import.xlsx",
                    "file_url" => url('files/Corporate Plan & Benefit Import.xlsx')
                ]);
                break;
            case 'member':
                return Helper::responseJson([
                    'file_name' => "Corporate Membership Import.xlsx",
                    "file_url" => url('files/Corporate Membership Import.xlsx')
                ]);
                break;
            case 'diagnosis-exclusion':
                return Helper::responseJson([
                    'file_name' => "Corporate Exclusion Import.xlsx",
                    "file_url" => url('files/Corporate Exclusion Import.xlsx')
                ]);
                break;
            case 'master-icd':
                return Helper::responseJson([
                    'file_name' => "Template - ICD.xlsx",
                    "file_url" => url('files/Template - ICD.xlsx')
                ]);
                break;
            case 'master-formularium':
                return Helper::responseJson([
                    'file_name' => "Template - Formularium.xlsx",
                    "file_url" => url('files/Template - Formularium.xlsx')
                ]);
                break;
            case 'master-formularium-corporate':
                return Helper::responseJson([
                    'file_name' => "Template - Formularium.xlsx",
                    "file_url" => url('files/Template - Formularium - Corporate.xlsx')
                ]);
                break;
            case 'claim-request':
                return Helper::responseJson([
                    'file_name' => "Template Format Claim.xlsx",
                    "file_url" => url('files/Template Format Claim.xlsx')
                ]);
                break;
            case 'request-log':
                return Helper::responseJson([
                    'file_name' => "Template Update Status Request LOG.xlsx",
                    "file_url" => url('files/Template Update Status Request LOG.xlsx')
                ]);
                break;
            case 'template-request-log':
                return Helper::responseJson([
                    'file_name' => "Template Import Request LOG.xlsx",
                    "file_url" => url('files/Template Import Request LOG.xlsx')
                ]);
                break;
            default:
                return Helper::responseJson([], 'error', 404);
                break;
        }
    }

    public function dataPlanBenefit(Request $request, $corporate_id){

        $file_name = 'Corporate Plan and Benefit';
        // Membuat penulis entitas Spout
        $writer = WriterEntityFactory::createXLSXWriter();
         // Membuka penulis untuk menulis ke file
        $writer->openToFile(public_path('files/CorporatePlan&BenefitImportData.xlsx'));

       // Sheet 1
        $writer->getCurrentSheet()->setName('Plans');
        $headers_map_to_table_fields = Plan::$listing_doc_headers;
        $headerRow = WriterEntityFactory::createRowFromArray($headers_map_to_table_fields);
        $writer->addRow($headerRow);

        $dataPlans = Plan::query()
            ->filter($request->all())
            ->where('corporate_id', $corporate_id)
            // ->whereHas('corporatePlan', function ($corporatePlan) use ($corporate_id) {
            //     $corporatePlan->where('corporate_id', $corporate_id);
            // })
            // ->with('corporatePlan')
            ->orderBy('corporate_plan_id', 'asc')
            ->get()->toArray();
        foreach ($dataPlans as $index => $row){
            $rowData = [
                $row['service_code'], // Service
                $row['corporate_plan_id'], // Plan
                $row['code'], // Customer plans
                $row['type'], // Plan Type
                $row['start'], // Start Date of Plan
                $row['end'], // End Date of Plan
                $row['require_referral'], // Referral
                $row['referral_source'], // Referral Source
                $row['referral_duration'], // Referral Duration
                $row['family_plan'], // Family Plan
                $row['family_plan_share_rules'], // Family Sharing Overflow
                $row['limit_rules'], // Plan Limit
                $row['layer'], // Layer ID
                $row['layer_conditions'], // Layer Condition
                $row['budget_type'], // Budget Type
                $row['budget_code'], // Budget Code
                $row['budget_conditions'], // Budget Condition
                $row['surgery_limit'], // Surgery
                $row['non_surgery_limit'], // Non Surgery
                $row['max_claim_limit'], // Max/Claim
                $row['max_claim_count'], // Max Count of Claim
                $row['area_limit'], // Area
                $row['limit_shared_plans'], // Shared Plan
                $row['limit_shared_plan_type'], // Shared Plan Type
                $row['cashless_percentage'], // Cashless(%)
                $row['reimbursement_percentage'], // Reimbursement(%)
                $row['digital_percentage'], // Digital(%)
                $row['co_share_m_percentage'], // CoShareM(%)
                $row['co_share_s_percentage'], // CoShareS(%)
                $row['co_share_c_percentage'], // CoShareC(%)
                $row['cashless_deductible'], // Cashless Deductible
                $row['cashless_deductible'], // Reimbursement Deductible
                $row['digital_deductible'], // Digital Deductible
                $row['co_share_m_deductible'], // DeductibleM
                $row['co_share_s_deductible'], // DeductibleS
                $row['co_share_c_deductible'], // DeductibleC
                $row['co_share_deductible_condition'], // Co-share & Deductible Condition
                $row['msc'], // MSC
                $row['genders'], // Gender
                $row['min_age'], // Min Age
                $row['max_age'], // Max Age
                $row['rule_of_excess'], // Rule of Excess
                $row['max_excess_covered'], // Max Excess Covered
                $row['prorate_type'], // Prorate Type
                $row['prorate_lookup'], // Prorate Lookup
                $row['currency'], // Currency
                $row['max_surgery_reinstatement_days'], // Reinstatement days for Surgery NonSurgery
                $row['max_surgery_periode_days'], // Max Periode of Surgery Non Surgery
            ];
            $row = WriterEntityFactory::createRowFromArray($rowData);
            $writer->addRow($row);
        }

        // Menutup penulis

        // Sheet 2
        $writer->addNewSheetAndMakeItCurrent();
        $writer->getCurrentSheet()->setName('Benefit');
        $headers_map_to_table_fields = CorporateBenefit::$listing_doc_headers;
        $headerRow = WriterEntityFactory::createRowFromArray($headers_map_to_table_fields);
        $writer->addRow($headerRow);

        $dataBenfit = CorporateBenefit::query()
            ->where('corporate_id', $corporate_id)
            ->with('benefit', 'plan')
            ->orderBy('plan_id', 'asc')
            ->get()->toArray();
        // dd($dataBenfit);
        foreach($dataBenfit as $index => $row){
            $rowData = [
                $row['benefit']['service_code'] ?? NULL, // "Service",
                $row['plan']['type'] ?? NULL, // "Plan",
                $row['benefit']['code'] ?? NULL, // "Benefit Code",
                $row['benefit']['code'] ?? NULL, // "Customer Benefit Code",
                $row['benefit']['description'] ?? NULL, // "Detail Benefit",
                $row['budget'], // "ASO/Budget",
                $row['budget_conditions'], // "Budget Condition",
                $row['budget_code'], // "Budget Code",
                $row['primary_benefit_code'], // "Primary benefit",
                $row['benefit_mode'], // "Benefit Mode",
                $row['room_class_coverage'], // "Room Class",
                $row['max_bed_coverage'], // "Max Bed",
                $row['tolerance_parameter'], //  "Tolerance Paramater",
                $row['max_room_class'], // "Max. Room Class",
                $row['limit_amount'], // "Limit Value",
                $row['area_limit'], // "Area",
                $row['shared_benefit'], // "Shared Benefit With",
                $row['shared_benefit_type'], // "Shared Benefit Type",
                $row['msc'], // "MSC",
                $row['genders'], // "Gender",
                $row['min_age'], // "Min Age",
                $row['max_age'], // "Max Age",
                $row['max_frequency_period'], // "Freq. Period",
                $row['daily_frequency'], // "Daily Frequency",
                $row['weekly_frequency'], // "Weekly Frequency",
                $row['monthly_frequency'], // "Monthly Frequency",
                $row['yearly_frequency'], // "Yearly Frequency",
                $row['custom_frequency_days'], // "Custom Duration",
                $row['custom_duration_value'], // "Custom Duration Value",
                NULL, //                 "Cashless, Reimbursement",
                $row['high_plan_factor'], // "High Plan Factor",
                $row['pre_post_treatment'], // "Pre Post Treatment",
                $row['pre_treatment_days'], // "Pre Treatment",
                $row['post_treatment_days'], // "Post Treatment",
                $row['layer_type_1'], // "Layer Type 1",
                $row['layer_value_1'], // "Layer Value 1",
                $row['layer_type_2'], // "Layer Type 2",
                $row['layer_value_2'], // "Layer Value 2",
                $row['cashless_percentage'], // "Cashless (%)",
                $row['reimbursement_percentage'], // "Reimburse (%)",
                $row['digital_percentage'], // "Digital (%)",
                $row['co_share_m_percentage'], // "CoShareM (%)",
                $row['co_share_s_percentage'], // "CoShareS (%)",
                $row['co_share_c_deductible'], // "CoShareC (%)",
                $row['cashless_deductible'], // "Cashless Deductible",
                $row['reimbursement_deductible'], // "Reimbursement Deductible",
                $row['digital_deductible'], // "Digital Deductible",
                $row['co_share_m_deductible'], // "DeductibleM",
                $row['co_share_s_deductible'], // "DeductibleS",
                $row['co_share_c_deductible'], // "DeductibleC",
                $row['prorate_type'], // "Prorate Type",
                $row['prorate_lookup'], // "Prorate Lookup",
                $row['max_days_for_disability'], // "Max Days for Disability",
                $row['max_period_for_disability'], // "Max Periode of Disability",
                $row['limit_free_tc'], // "Currency",
                $row['currency'], // "Currency",
                $row['show_benefit_item'], // "Show Benefit Item",
                $row['show_benefit_value'], // "Show Benefit Value",
            ];
            $row = WriterEntityFactory::createRowFromArray($rowData);
            $writer->addRow($row);
        }

        $writer->close();

        return Helper::responseJson([
            'file_name' => "Data Corporate Plan & Benefit List " . date('Y-m-d h:i:s'),
            "file_url" => url('files/CorporatePlan&BenefitImportData.xlsx')
        ]);
    }

    public function corporateCode(Request $request){
        $corporates = Corporate::query()
            ->when($request->search, function ($query, $search) {
                return $query->where('name', 'LIKE', '%' . $search . '%')
                    ->orWhere('code', 'LIKE', '%' . $search . '%');
            })
            ->with('currentPolicy', 'subCorporates')
            ->withCount([
                'employees',
                'corporateBenefits',
                'corporatePlans',

                // 'claims'
            ])
            ->where('active', 1)
            ->get()
            ->pluck('code');

        return $corporates;
    }

    public function addFilesDoc(Request $request)
    {
        $request->validate([
            'corporate_id' => 'required'
        ]);
        if ($request->hasFile('result_files')) {
            $pathFile = File::storeFile('docs', $request->corporate_id, $request->result_files);
            $data = [
                'corporate_id' => $request->corporate_id,
                'original_name' => $request->result_files->getClientOriginalName(),
                'path' => $pathFile,
                'created_by' => auth()->user()->id,
                'updated_by' => auth()->user()->id
            ];
            FilesDoc::create($data);
            return Helper::responseJson(data: $request->toArray(), message: 'Berhasil tambah file '.$data['original_name']);
        }
        else
        {
            return Helper::responseJson(data: $request->toArray(), message: 'Tidak ada file yang ditambahkan');
        }

    }

    public function getFilesDoc(Request $request)
    {
        $request->validate([
            'corporate_id' => 'required'
        ]);
        $datas = FilesDoc::where('corporate_id', $request->corporate_id)
        ->select('original_name', \DB::raw("CONCAT('" . env('APP_URL') . "/storage/', path) as path"), 'status_download')
        ->orderBy('id', 'desc')
        //->limit(1)
        ->get();
        if ($datas->isEmpty()) {
            return Helper::responseJson(data: [], message: 'Tidak ada data');
        }
        return Helper::responseJson(data: $datas, message: 'Berhasil mendapatkan data');
    }

    public function updateStatusFilesDoc(Request $request)
    {
        $request->validate([
            'status_download' => 'required',
            'corporate_id' => 'required'
        ]);

        $data_requests = [
            'status_download' => $request->status_download
        ];

        FilesDoc::where('corporate_id', $request->corporate_id)
        ->update($data_requests);

        $datas = FilesDoc::where('corporate_id', $request->corporate_id)
        ->select('status_download')
        ->orderBy('id', 'desc')
        ->limit(1)
        ->get();

        return Helper::responseJson(data: $datas, message: 'Berhasil update status download menjadi '.($request->status_download == 0 ? 'Inactive' : 'Active'));

    }

}
