<?php

namespace App\Services;

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

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

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

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

            $payment->sub_manager_commission = $subManagerCommission;

        }

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

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

            $payment->manager_commission = $packageCommission;

        }
        $payment->save();

    }

    public function calculateCommission($packagePrice, $packageCommission, $amountToCalculate) {

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


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


        $commission = ($packageCommission * $amountToCalculate) / $packagePrice;


        return number_format($commission, 2);
    }
}
