<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\Client;
use App\Models\Packages;
use App\Models\BillGenerate;
use App\Models\BillGeneratesArchive;
use App\Services\ExpireCheck;
use App\Models\CustomerAccount;
use App\Models\Pop;
use App\Models\Reseller;
use App\Models\ResellerCommissionReference;
use App\Models\SubResellerCommissionReference;
use App\Services\PriceCalculate;
use Illuminate\Support\Facades\DB;

class CommissionService
{
    public function reseller_commission($amount, $actions, $reseller_id, $commission, $package_price, $client_id, $bill_or_payment = null, $bill_or_payment_id = null)
    {
        // dd($commission);
        if ($commission > 0 || globalPermission('commission_from_manager_pop')) {
            if (globalPermission('commission_from_manager_pop')) {
                $thisResellerCommission = Reseller::find($reseller_id);
                $commission = $thisResellerCommission->commission_percentage;
                $package_price = 100;
            }

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

            // Calculate commission amount once so we can store it and,
            // when needed, append commission/VAT info into actions text.
            $received_amount = $this->calculateCommission($commission, $package_price, $amount, $reseller_id, $vatRate);

            // When both settings are enabled, show commission and VAT amount in actions.
            // If disabled, actions text remains as previously set (default behavior).
            if (globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable' && $vatRate > 0) {
                $amount_without_vat = round($amount / (1 + ($vatRate / 100)));
                $vat_amount = $amount - $amount_without_vat;

                $actions .= ' (Commission: ' . number_format($received_amount, 2) . ', VAT: ' . number_format($vat_amount, 2) . ')';
            }

            if ($bill_or_payment == "bill") {
                ResellerCommissionReference::create([
                    'received_amount' => $received_amount,
                    'actions' => $actions,
                    'user_id' => auth()->user()->id ?? 1,
                    'reseller_id' => $reseller_id,
                    'client_id' => $client_id,
                    'bill_generate_id' => $bill_or_payment_id,
                ]);
            } else if ($bill_or_payment == "payment") {
                ResellerCommissionReference::create([
                    'received_amount' => $received_amount,
                    'actions' => $actions,
                    'user_id' => auth()->user()->id ?? 1,
                    'reseller_id' => $reseller_id,
                    'client_id' => $client_id,
                    'bill_payment_id' => $bill_or_payment_id,

                ]);
            } else {

                ResellerCommissionReference::create([
                    'received_amount' => $received_amount,
                    'actions' => $actions,
                    'user_id' => auth()->user()->id ?? 1,
                    'reseller_id' => $reseller_id,
                    'client_id' => $client_id

                ]);
            }
        }
    }

    public function subreseller_commission($amount, $actions, $pop_id, $commission, $package_price, $client_id, $bill_or_payment = null, $bill_or_payment_id = null)
    {
        if ($commission > 0 || globalPermission('commission_from_manager_pop')) {
            if (globalPermission('commission_from_manager_pop')) {
                $thisSubResellerCommission = Pop::find($pop_id);
                $commission = $thisSubResellerCommission->commission_percentage;
                $package_price = 100;
            }

            if ($bill_or_payment == "bill") {
                SubResellerCommissionReference::create([
                    'received_amount' => $this->calculateCommission($commission, $package_price, $amount),
                    'actions' => $actions,
                    'user_id' => auth()->user()->id ?? 1,
                    'pop_id' => $pop_id,
                    'client_id' => $client_id,
                    'bill_generate_id' => $bill_or_payment_id
                ]);
            } else if ($bill_or_payment == "payment") {
                SubResellerCommissionReference::create([
                    'received_amount' => $this->calculateCommission($commission, $package_price, $amount),
                    'actions' => $actions,
                    'user_id' => auth()->user()->id ?? 1,
                    'pop_id' => $pop_id,
                    'client_id' => $client_id,
                    'payment_id' => $bill_or_payment_id
                ]);
            } else {

                SubResellerCommissionReference::create([
                    'received_amount' => $this->calculateCommission($commission, $package_price, $amount),
                    'actions' => $actions,
                    'user_id' => auth()->user()->id ?? 1,
                    'pop_id' => $pop_id,
                    'client_id' => $client_id
                ]);
            }
        }
    }

    public function calculateCommission($commission, $package_price, $amount, $reseller_id = null, $vatRate = 0)
    {
        // Get VAT rate if not provided but both settings are enabled
        if ($vatRate == 0 && $reseller_id && globalPermission('commission_from_manager_pop') && checkSettings('vat_deduct_from_payment_for_commission_calculation') === 'enable') {
            $reseller = Reseller::find($reseller_id);
            $vatRate = $reseller->vat ?? 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
            $package_price_without_vat = round($package_price / (1 + ($vatRate / 100)));

            // Calculate payment amount without VAT
            $amount_without_vat = round($amount / (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_amount = (($package_price_without_vat * ($commission / 100)) * $amount_without_vat) / $package_price_without_vat;
            return round($commission_amount, 2);
        }

        // Original calculation when VAT deduction is disabled
        return round((($commission * $amount) / $package_price), 2);
    }
}
