<?php

namespace App\Services;

use App\Models\Claim;
use App\Models\Icd;
use App\Models\Member;
use Carbon\Carbon;
use DB;
use Str;

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();

        // dd($benefit->toArray());
        // dd(compact(['plan', 'policy', 'corporate', 'benefit']));
        $limits = [
            'total_limit' => $benefit->limit_amount,
            'frequency_limit_name' => $benefit->max_frequency_period_name,
            'frequency_limit' => $benefit->max_frequency,
            'total_claim' => 0,
            'remaining_limit' => $benefit->limit_amount,
            'usage_daily' => null,
            'usage_weekly' => null,
            'usage_monthly' => null,
            'usage_yearly' => null
        ];
        
        switch ($benefit->max_frequency_period) {
            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'] = $benefit->limit_amount - $limits['total_claim'];

        return $limits;
    }

    public static function storeClaim($member, $diagnosis, $totalClaim, $benefit, $status)
    {
        try {
            DB::beginTransaction();

            $claimData = [
                'member_id' => $member->id,
                'diagnosis_id' => $diagnosis->id ?? null,
                'total_claim' => $totalClaim,
                'currency' => 'IDR',
                'plan_id' => $member->currentPlan->id,
                'benefit_id' => $benefit->id,
                'status' => $status
            ];
            $claimData[$status.'_at'] = now();
            $claimData[$status.'_by'] = auth()->user()->id ?? null;
            
            $claim = Claim::create($claimData);

            $policy = $member->currentPolicy;
            $policy->limitJournals()->create([
                'previous_balance' => $policy->limit_balance,
                'total_credit' => $totalClaim,
                'type' => 'credit',
                'balance' => bcsub($policy->limit_balance, $totalClaim),
                'description' => 'Log for Claim #'. $claim->code,
            ]);

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

            throw new \Exception($error);
        }
    }
}