<?php

namespace App\Services;

use App\Models\Service;
use App\Models\ServiceFeeComponent;
use App\Models\ServicePriceOverride;

class FeeEngineService
{
    public function calculateServiceFees(Service $service, array $context = []): array
    {
        $tenantId = $service->tenant_id;
        $priority = $context['priority'] ?? 'normal';
        $companyId = $context['company_id'] ?? null;
        $branchId = $context['branch_id'] ?? null;

        // 1. Check Corporate Contract Override or Branch Override
        if ($companyId) {
            $corpOverride = ServicePriceOverride::where('tenant_id', $tenantId)
                ->where('service_id', $service->id)
                ->where('override_type', 'corporate_contract')
                ->where('target_id', $companyId)
                ->first();

            if ($corpOverride) {
                $overridePrice = (float) $corpOverride->override_price;

                return [
                    'gov_fee' => 0,
                    'typing_fee' => $overridePrice,
                    'service_charge' => 0,
                    'vat_amount' => round($overridePrice * 0.05, 2),
                    'total_price' => round($overridePrice * 1.05, 2),
                    'applied_price_source' => 'corporate_contract_override',
                    'fee_components' => [],
                ];
            }
        }

        // 2. Component-based Fee Calculation
        $components = ServiceFeeComponent::where('tenant_id', $tenantId)
            ->where('service_id', $service->id)
            ->orderBy('display_order')
            ->get();

        if ($components->isEmpty()) {
            // Fallback to Service Master pricing
            $govFee = (float) $service->gov_fee;
            $typingFee = (float) $service->typing_fee;
            $serviceCharge = (float) $service->service_charge;

            // Apply priority surcharge
            if ($priority === 'urgent') {
                $serviceCharge += 50.00;
            } elseif ($priority === 'vip') {
                $serviceCharge += 150.00;
            }

            $vat = $service->vat_applicable ? round(($typingFee + $serviceCharge) * 0.05, 2) : 0;
            $total = $govFee + $typingFee + $serviceCharge + $vat;

            return [
                'gov_fee' => $govFee,
                'typing_fee' => $typingFee,
                'service_charge' => $serviceCharge,
                'vat_amount' => $vat,
                'total_price' => $total,
                'applied_price_source' => 'service_master_default',
                'fee_components' => [],
            ];
        }

        $govFeeSum = 0;
        $typingFeeSum = 0;
        $serviceChargeSum = 0;
        $vatSum = 0;

        foreach ($components as $comp) {
            $amt = (float) $comp->amount;
            if ($comp->component_type === 'gov_fee' || $comp->component_type === 'gov_portal_fee') {
                $govFeeSum += $amt;
            } elseif ($comp->component_type === 'typing_fee') {
                $typingFeeSum += $amt;
            } else {
                $serviceChargeSum += $amt;
            }

            if ($comp->tax_behavior === 'taxable') {
                $vatSum += round($amt * 0.05, 2);
            }
        }

        // Priority surcharge
        if ($priority === 'urgent') {
            $serviceChargeSum += 50.00;
            $vatSum += round(50.00 * 0.05, 2);
        } elseif ($priority === 'vip') {
            $serviceChargeSum += 150.00;
            $vatSum += round(150.00 * 0.05, 2);
        }

        $totalPrice = $govFeeSum + $typingFeeSum + $serviceChargeSum + $vatSum;

        return [
            'gov_fee' => $govFeeSum,
            'typing_fee' => $typingFeeSum,
            'service_charge' => $serviceChargeSum,
            'vat_amount' => $vatSum,
            'total_price' => $totalPrice,
            'applied_price_source' => 'fee_components_engine',
            'fee_components' => $components->toArray(),
        ];
    }
}
