<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Member;
use App\Models\Claim;
use App\Models\ClaimRequest;
use App\Models\RequestLog;
use App\Services\CorporateMemberService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Client\Transformers\ClaimReport\MemberResources as ClaimReportMemberResources;
use Modules\Client\Transformers\AlarmCenter\DataListClaimMemberResource;
use Modules\Client\Transformers\AlarmCenter\DataServiceMonitoring;
use Modules\Client\Transformers\Dashboard\MemberResources as ClaimSubmitMemberResources;
use Modules\Client\Transformers\Dashboard\MemberResources as DashboardMemberResources;
use Modules\Client\Transformers\Dashboard\MemberAlarmCenterResources as DashboardMemberAlarmResources;
use Modules\Client\Transformers\Dashboard\MemberEmployeeDataResources as DashboardMemberEmployeeDataResources;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Modules\Client\Transformers\EmployeeData\UserProfile\DataMemberResource as EmployeeDataProfileMemberResource;
use Modules\Internal\Services\MemberEnrollmentService;

class CorporateMemberController extends Controller
{
    public $memberEnrollmentService;

    public function __construct(public CorporateMemberService $corporateMemberService, MemberEnrollmentService $memberEnrollmentService)
    {
        $this->memberEnrollmentService = $memberEnrollmentService;
    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $corporate_id)
    {
        switch ($request->input('type')) {
            case 'employee-data':
                $members = $this->corporateMemberService->getAllMemberEmployeeData($corporate_id, $request);
                return response()->json(Helper::paginateResources(DashboardMemberEmployeeDataResources::collection($members)));
            case 'claim-report':
                $members = $this->corporateMemberService->getAllMemberClaimReports($corporate_id, $request);
                return response()->json(Helper::paginateResources(ClaimReportMemberResources::collection($members)));
            case 'claim-submit':
                $members = $this->corporateMemberService->getAllMemberClaimSubmits($corporate_id, $request);
                return response()->json(Helper::paginateResources(ClaimSubmitMemberResources::collection($members)));
            case 'alarm-center':
                $members = $this->corporateMemberService->getAllMemberAlarmCenter($corporate_id, $request);
                return response()->json(Helper::paginateResources(DashboardMemberAlarmResources::collection($members)));
            case 'service-monitoring':
                $members = $this->corporateMemberService->getAllEncounter($corporate_id, $request);
                return response()->json(Helper::paginateResources(DashboardMemberAlarmResources::collection($members)));
            default:
                $members = $this->corporateMemberService->getAllMemberDashboards($corporate_id, $request);
                return response()->json(Helper::paginateResources(DashboardMemberResources::collection($members)));
        }
    }

    public function show($corporate_id, $person_id)
    {
        $data = Member::query()
            ->with(['person'])
            ->where('person_id', $person_id)
            ->whereHas('currentCorporate', function ($query) use ($corporate_id) {
                $query->where('corporate_id', $corporate_id);
            })
            ->firstOrFail();

        // Get Families
        $data->families = Member::query()
            ->with(['person'])
            ->where('principal_id', $data->member_id)
            ->get();

        return response()->json(EmployeeDataProfileMemberResource::make($data));
    }

    public function generateMemberList($corporate_id)
    {
        // Mendapatkan data yang akan diekspor (misalnya, dari database)
        $data = Member::with(['currentPlan', 'currentCorporate', 'division', 'employeds', 'currentPolicy'])
            // ->filter($request->all())
            // ->where('corporate_id', $corporate_id)
            ->whereHas('employeds', function ($employeds) use ($corporate_id) {
                $employeds->where('corporate_id', $corporate_id);
            })->get()->toArray();
        // Membuat penulis entitas Spout
        $writer = WriterEntityFactory::createXLSXWriter();

        // Membuka penulis untuk menulis ke file
        $writer->openToFile(public_path('files/CorporateMembershipList.xlsx'));
        // Menulis header kolom
        $headers_map_to_table_fields = $this->memberEnrollmentService->listing_doc_headers;
        $headerRow = WriterEntityFactory::createRowFromArray($headers_map_to_table_fields);

        $writer->addRow($headerRow);

        // Menulis data
        if (!empty($data)) {
            foreach ($data as $item) {
                $rowData = [
                    $item['record_mode'], // Recode Mode
                    $item['record_type'], // Recode Type
                    $item['payor_id'], // Payor ID
                    $item['member_id'], // Member ID
                    $item['principal_id'], // Mapping ID
                    NULL, // Link Medis Member ID
                    $item['current_corporate']['code'] ?? null, // Corporate ID
                    $item['employeds'][0]['nik'] ?? null, // NIK
                    $item['division']['code'] ?? null, // Devision
                    $item['employeds'][0]['branch_code'] ?? null, // Branch Code
                    $item['bank_info'], // Bank Info
                    $item['language'], // Language
                    null, // Type of Work
                    $item['race'], // Race
                    $item['current_policy']['code'] ?? null, // Policy Number
                    $item['marital_status'], // Marital Status
                    $item['relation_with_principal'], // Relationship
                    str_replace('-', '', $item['members_effective_date']), // Member effective date
                    str_replace('-', '', $item['members_expire_date']), // Member expiry date
                    NULL, // Faskes FKTP  (First Level Provider) or Individual preferred provider
                    NULL, // Faskes FKRTL (Next Level Provider) or Individual group preferred provider
                    $item['bpjs_class'], // The Right Classes Room of  BPJS Participants
                    NULL, // Name of Faskes
                    NULL, // Rule BPJSK
                    NULL, // Internal Use
                    $item['full_name'], // Member Name
                    $item['address1'], // Address1
                    $item['address2'], // Address2
                    $item['address3'], // Address3
                    $item['address4'], // Address4
                    $item['city'], // City
                    NULL, // State
                    $item['postal_code'], // Post Code
                    NULL, // Telephone - Mobile
                    NULL, // Telephone - Res
                    NULL, // Telephone - Office
                    $item['nric'], // NRIC
                    $item['passport_no'], // Passport No
                    $item['passport_country'], // Passport Country
                    $item['email'], // Email
                    $item['identification_code'], // Identification Code
                    $item['birth_date'], // Date of Birth
                    $item['gender_code'], // Sex
                    NULL, // Internal Use
                    $item['current_plan']['code'] ?? null, // Plan-ID
                    NULL, // Employment-Status
                    NULL, // Internal Use
                    NULL, // Internal Use
                    NULL, // Internal Use
                    str_replace('-', '', $item['terminated_date']), // Date Terminated
                    $item['pre_existing'], // Pre Existing
                    $item['bpjs_id'], // BPJS ID
                    $item['endorsement_date'], // Endorsement Date
                    $item['remarks'], // Remarks
                    NULL, // Internal Use
                    NULL, // Member Since
                    NULL, // Internal Use
                    $item['policy_in_force'], // Policy Inforce
                    NULL, // Member Suspended
                    str_replace('-', '', $item['activation_date']), // Activation Date
                    NULL, // Internal Use
                    $item['start_no_claim'], // StartNoClaim
                    $item['end_no_claim'], // EndNoClaim
                    NULL, // Option Mode
                ];
                $row = WriterEntityFactory::createRowFromArray($rowData);
                $writer->addRow($row);
            }
        }

        // Menutup penulis
        $writer->close();
        // dd('test');
        // Mengembalikan response untuk mengunduh file
        $filePath = public_path('files/CorporateMembershipList.xlsx');
        // dd($filePath);
        // Mengembalikan response untuk mengunduh file
        return Helper::responseJson([
            'file_name' => "Corporate Plan & Benefit List " . date('Y-m-d h:i:s'),
            "file_url" => url('files/CorporateMembershipList.xlsx')
        ]);
    }

    public function showPerMember(Request $request, $corporate_id, $member_id)
    {
        $per_page = $request->has('per_page') ? $request->input('per_page') : 10;

        $data = Member::query()
            ->with(['requestLogs'])
            ->whereHas('currentCorporate', function ($query) use ($corporate_id) {
                $query->where('corporate_id', $corporate_id);
            })
            ->find($member_id);

        return response()->json(['full_name' => $data->full_name ?? null, 'paginations' => Helper::paginateResources(DataListClaimMemberResource::collection($data->requestLogs()->paginate($per_page)))]);
    }

    public function serviceMonitoring(int $corporate_id, int $request_log_id)
    {
        $data = RequestLog::query()
            ->with([
                'member:id,member_id,person_id,birth_date,email,name_prefix,name,name_suffix' => [
                    'currentCorporate',
                    'person:id,email,name_prefix,name,name_suffix,phone'
                ],
                'organization:id,name',
                'requestLogBenefits:id,request_log_id,benefit_id,amount_incurred,amount_approved,amount_not_approved,excess_paid,keterangan' => [
                    'benefit'
                ],
                'requestLogDailyMonitorings:id,request_log_id,created_at,subject,body_temperature,sistole,diastole,respiration_rate,analysis,lab_date,provider,examination' => [
                    'requestLogMedicalPlans:request_log_daily_monitoring_id,plan,type'
                ],
                'service:code,name',
            ])
            ->find($request_log_id, ['id', 'submission_date', 'discharge_date', 'member_id', 'service_code', 'organization_id']);

        $dataBenefit = [];
        if (count($data->requestLogBenefits) > 0) {
            $totalIncurred = 0;
            $totalApprove = 0;
            $totalNotApporve = 0;
            $totalExcess = 0;

            foreach ($data->requestLogBenefits as $itemBenefit) {
                $totalIncurred += $itemBenefit->amount_incurred;
                $totalApprove += $itemBenefit->amount_approved;
                $totalNotApporve += $itemBenefit->amount_not_approved;
                $totalExcess += $itemBenefit->excess_paid;
            }

            $dataBenefit['totalIncurred'] = $totalIncurred;
            $dataBenefit['totalApprove'] = $totalApprove;
            $dataBenefit['totalNotApprove'] = $totalNotApporve;
            $dataBenefit['totalExcess'] = $totalExcess;
        }

        $data->benefitTotal = $dataBenefit;

        return Helper::responseJson(DataServiceMonitoring::make($data));
    }
}
