<?php

namespace App\Services;

use App\Models\Billpayment;
use App\Models\Payment;
use App\Models\Reseller;

class CommissionCalculationService
{
    public function setCommissionToBillPayment($billPaymentId){
        $payment = Billpayment::with('clients.packages','clients.subpack','clients.pop')->find($billPaymentId);

        // Get VAT rate from reseller if both settings are enabled
        $vatRate = 0;
        if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable' && isset($payment->clients->pop->reseller_id)) {
            $reseller = Reseller::find($payment->clients->pop->reseller_id);
            $vatRate = $reseller->vat ?? 0;
        }

        if($payment->clients->subpack){

            $subManagerCommission = $this->calculateCommission($payment->clients->subpack->rate,$payment->clients->subpack->commission,$payment->paid_amount, $vatRate);

            $payment->sub_manager_commission = $subManagerCommission;

        }

        if($payment->clients->packages){

            $packageCommission  = $this->calculateCommission($payment->clients->packages->package_rate,$payment->clients->packages->commission,$payment->paid_amount, $vatRate);

            $payment->manager_commission = $packageCommission;

        }
        $payment->save();

    }

    public function calculateCommission($packagePrice, $packageCommission, $amountToCalculate, $vatRate = 0) {

        $packagePrice = $packagePrice ?? 0;
        $packageCommission = $packageCommission ?? 0;
        $amountToCalculate = $amountToCalculate ?? 0;


        if ($packagePrice == 0) {
            return 0;
        }

        // If both settings are enabled and VAT rate is provided, deduct VAT before calculating commission
        if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable' && $vatRate > 0) {
            // Calculate package rate without VAT (rounded)
            $packagePriceWithoutVat = round($packagePrice / (1 + ($vatRate / 100)));

            // Calculate payment amount without VAT (rounded)
            $amountWithoutVat = round($amountToCalculate / (1 + ($vatRate / 100)));

            // Calculate commission on amount without VAT
            // Formula: [{package_rate_without_vat * (commission_percentage/100)} * payment_amount_without_vat] / package_rate_without_vat
            // = {(500*50%)*500}/500 = {(500*0.5)*500}/500 = {250*500}/500 = 250
            $commission = (($packagePriceWithoutVat * ($packageCommission / 100)) * $amountWithoutVat) / $packagePriceWithoutVat;
        } else {
            // Original calculation when VAT deduction is disabled
            $commission = ($packageCommission * $amountToCalculate) / $packagePrice;
        }

        return round($commission, 2);
        
    }
}
