<?php

namespace App\Services;

use App\Models\Claim;
use App\Models\Member;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class ClaimService
{

    public static function getMemberTotalUsage(Member $member, $startDate = null, $endDate = null)
    {
        $startDate = empty($startDate) ? Carbon::now()->startOfMonth() : $startDate;
        $endDate = empty($endDate) ? Carbon::now()->startOfMonth() : $endDate;

        $claims = $member->claims()
            ->used($startDate, $endDate)
            ->get();
        $total = $claims->sum(function ($claim) {
            return $claim->total_claim;
        });

        return $total;
    }

    public static function checkMemberEligibility($member, $benefit, $diagnosis, $totalClaim = 0)
    {
        $currentPlan = $member->currentPlan;
        $policy = $member->currentPolicy;
        $corporate = $policy->corporate;


        $isEligible = true;
        $validationErrors = [];

        // Eligibility Validation

        if (!in_array($member->marital_status, explode(',', $benefit->msc))) {
            $validationErrors[] = [
                'error' => 'msc',
                'message' => 'Only ' . $benefit->msc
            ];
            $isEligible = false;
        }

        if (!in_array($member->gender_code, explode(',', $benefit->genders))) {
            $validationErrors[] = [
                'error' => 'genders',
                'message' => 'Only ' . $benefit->genders
            ];
            $isEligible = false;
        }

        if (!empty($benefit->min_age) && $member->age < $benefit->min_age) {
            $validationErrors[] = [
                'error' => 'min_age',
                'message' => 'Minimum Age is ' . $benefit->min_age
            ];
            $isEligible = false;
        }

        if (!empty($benefit->max_age) && $member->age > $benefit->max_age) {
            $validationErrors[] = [
                'error' => 'max_age',
                'message' => 'Maximum Age is ' . $benefit->min_age
            ];
            $isEligible = false;
        }

        // TODO complete validations

        // Limit Validation
        if ($totalClaim > 0) {
            if (bcsub($corporate->limit_balance, $totalClaim) < 0) {
                $validationErrors[] = [
                    'error' => 'corporate_limit',
                    'message' => 'Corporate Limit cannot cover this'
                ];
                $isEligible = false;
            }

            if (bcsub($benefit->limit_amount, $totalClaim) < 0) {
                $validationErrors[] = [
                    'error' => 'benefit_limit',
                    'message' => 'Benefit Limit cannot cover this'
                ];
                $isEligible = false;
            }

            // TODO complete validations

        }

        return [
            'isEligible' => $isEligible,
            'errors' => $validationErrors
        ];
    }

    public static function getMemberUsageByBenefitLimit($member, $benefit)
    {
    }

    public static function showMemberBenefitLimit($member, $benefit_code)
    {
        // $plan = $member->currentPlan;
        // $policy = $member->currentPolicy;
        // $corporate = $member->currentCorporate;
        $benefit = $member->currentPlan->benefits()->where('code', $benefit_code)->first();
        $corporateBenefit = $member->currentPlan
            ->corporateBenefits()
            ->where('benefit_id', $benefit->id ?? null)
            ->where('plan_id', $member->currentPlan->id)
            ->active()
            ->first();

        $limits = [
            'total_limit' => $corporateBenefit ? $corporateBenefit->limit_amount : 0,
            'frequency_limit_name' => $corporateBenefit ? $corporateBenefit->max_frequency_period_name : null,
            'frequency_limit' => $corporateBenefit ? $corporateBenefit->max_frequency : 0,
            'total_claim' => 0,
            'remaining_limit' => $corporateBenefit ? $corporateBenefit->limit_amount : 0,
            'usage_daily' => null,
            'usage_weekly' => null,
            'usage_monthly' => null,
            'usage_yearly' => null
        ];

        switch ($corporateBenefit->max_frequency_period ?? 0) {
            case (0):
                $limits['usage_yearly'] = $member->claims()->used(Carbon::now()->firstOfYear(), now())->count();
                $limits['total_claim'] = $member->claims()->used(Carbon::now()->firstOfYear(), now())->sum('total_claim');
                break;
            case (1):
                $limits['usage_daily'] = $member->claims()->used(now()->format('Y-m-d'), now()->addDay(1)->format('Y-m-d'))->count();
                $limits['total_claim'] = $member->claims()->used(now()->format('Y-m-d'), now()->addDay(1)->format('Y-m-d'))->sum('total_claim');
                break;
            case (2):
                $limits['usage_weekly'] = $member->claims()->used(Carbon::parse('Previous Sunday'), now())->count();
                $limits['total_claim'] = $member->claims()->used(Carbon::parse('Previous Sunday'), now())->sum('total_claim');
                break;
            case (3):
                $limits['usage_monthly'] = $member->claims()->used(Carbon::now()->firstOfMonth(), now())->count();
                $limits['total_claim'] = $member->claims()->used(Carbon::now()->firstOfMonth(), now())->sum('total_claim');
                break;
            case (4):
                $limits['usage_yearly'] = $member->claims()->used(Carbon::now()->firstOfYear(), now())->count();
                $limits['total_claim'] = $member->claims()->used(Carbon::now()->firstOfYear(), now())->sum('total_claim');
                break;
            default:
                // return null;
                break;
        }
        $limits['remaining_limit'] = ($corporateBenefit->limit_amount ?? 0) - $limits['total_claim'];

        return $limits;
    }

    public static function storeClaim($member, $diagnosis = null, $totalClaim = null, $benefit = null, $status = 'requested', $claimRequest = null)
    {
        DB::beginTransaction();
        try {

            $claimData = [
                'member_id' => $member->id,
                'claim_request_id' => $claimRequest->id ?? null,
                'diagnosis_id' => $diagnosis->id ?? null,
                'total_claim' => $totalClaim ?? null,
                'currency' => 'IDR',
                'plan_id' => $member->currentPlan->id ?? null,
                'benefit_id' => $benefit->id ?? null,
                'status' => $status
            ];

            $claim = Claim::create($claimData);

            DB::commit();
            return $claim;
        } catch (\Exception $error) {
            DB::rollBack();

            throw new \Exception($error);
        }
    }

    // public static function claimApprove(Claim $claim)
    // {
    //     if (!in_array($claim->status, ['approved', 'paid', 'declined'])) {

    //         // Only Update Claim is not approved yet
    //         if (empty($claim->approved_at)) {
    //             $claim->approved_at = now();
    //             $claim->status = 'approved';

    //             $claim->save();

    //             ClaimApproved::dispatch($claim);
    //         }

    //     }

    //     return false;
    // }

    public function getCountClaimRequestPerStatus(int $corporateId)
    {
        $members = Member::query()
            ->joinClaimRequests('right')
            ->joinCorporateEmployees('left')
            ->where('corporate_employees.corporate_id', $corporateId)
            ->get([DB::raw("COUNT(claim_requests.status = 'approved') AS count_approval")]);


        // ->withCount([
        //     'claimRequests as count_requested' => function (Builder $query) {
        //         $query->where('status', 'requested');
        //     },
        //     'claimRequests as count_approval' => function (Builder $query) {
        //         $query->where('status', 'approved');
        //     },
        //     // 'claimRequests as count_disbrushment' => function (Builder $query) {
        //     //     $query->where('status', 'requested');
        //     // },
        //     'claimRequests as count_rejected' => function (Builder $query) {
        //         $query->where('status', 'declined');
        //     }
        // ]);

        dd($members);

        // $data = [
        //     'count_requested' => $claimRequest->query()->where('status', 'requested')->count(),
        //     'count_approval' => $claimRequest->query()->where('status', 'approved')->count(),
        //     'count_disbrushment' => 0,
        //     'count_rejected' => $claimRequest->query()->where('status', 'declined')->count(),
        // ];

        // return $data;
    }
}
