<?php

namespace App\Services\Calculator;

use App\Models\TaxRule;
use App\Models\DepreciationRule;
use App\Models\ImportChargeSetting;

class BangladeshLandedCostCalculator
{
    /**
     * Calculate comprehensive Bangladesh Landed Cost for Japanese vehicle imports
     */
    public function calculate(array $params): array
    {
        $priceJpy = (float) ($params['price_jpy'] ?? 2000000);
        $engineCc = (int) ($params['engine_cc'] ?? 1500);
        $fuelType = $params['fuel_type'] ?? 'Hybrid';
        $isHybrid = (bool) ($params['is_hybrid'] ?? str_contains(strtolower($fuelType), 'hybrid'));
        $year = (int) ($params['year'] ?? (date('Y') - 2));

        // 1. Currency Exchange Rate
        $exchangeRate = (float) ($params['exchange_rate'] ?? $this->getSetting('jpy_to_bdt_rate', config('motosolution.currency.jpy_to_bdt_rate', 0.82)));

        // 2. Japan Standard Costs (JPY)
        $auctionFeeJpy = (float) $this->getSetting('auction_fee_jpy', config('motosolution.auction.standard_auction_fee_jpy', 25000));
        $inlandTransportJpy = (float) $this->getSetting('inland_transport_jpy', config('motosolution.auction.standard_inland_transport_jpy', 35000));
        $shippingJpy = (float) $this->getSetting('shipping_jpy', config('motosolution.auction.standard_shipping_jpy', 180000));
        
        $totalJapanJpy = $priceJpy + $auctionFeeJpy + $inlandTransportJpy + $shippingJpy;
        $totalJapanBdt = round($totalJapanJpy * $exchangeRate, 2);

        // Marine Insurance (BDT)
        $marineInsuranceBdt = (float) $this->getSetting('marine_insurance_bdt', config('motosolution.auction.standard_insurance_bdt', 25000));
        $cifValueBdt = $totalJapanBdt + $marineInsuranceBdt;

        // 3. Vehicle Age & NBR Depreciation
        $currentYear = (int) date('Y');
        $vehicleAge = max(0, $currentYear - $year);
        $depreciationPercent = $this->getDepreciationPercentage($vehicleAge);
        $assessableValueBdt = round($cifValueBdt * (1 - ($depreciationPercent / 100)), 2);

        // 4. Customs Duty Rates & Assessment (NBR Bangladesh)
        $taxRates = $this->resolveTaxRates($engineCc, $isHybrid, $fuelType);

        $customsDuty = round($assessableValueBdt * ($taxRates['cd'] / 100), 2);
        $regulatoryDuty = round($assessableValueBdt * ($taxRates['rd'] / 100), 2);
        
        $baseForSd = $assessableValueBdt + $customsDuty + $regulatoryDuty;
        $supplementaryDuty = round($baseForSd * ($taxRates['sd'] / 100), 2);

        $baseForVat = $baseForSd + $supplementaryDuty;
        $vat = round($baseForVat * ($taxRates['vat'] / 100), 2);

        $advanceIncomeTax = round($assessableValueBdt * ($taxRates['ait'] / 100), 2);
        $advanceTax = round($baseForVat * ($taxRates['at'] / 100), 2);

        $totalCustomsAndTaxesBdt = round($customsDuty + $regulatoryDuty + $supplementaryDuty + $vat + $advanceIncomeTax + $advanceTax, 2);

        // 5. Bangladesh Port, Clearing & Registration
        $portAndCfChargesBdt = (float) $this->getSetting('port_cf_bdt', config('motosolution.auction.standard_port_cf_bdt', 55000));
        $brtaRegistrationBdt = (float) $this->getSetting('brta_registration_bdt', config('motosolution.auction.standard_registration_bdt', 135000));
        $serviceFeeBdt = (float) $this->getSetting('service_charge_bdt', config('motosolution.auction.default_service_charge_bdt', 50000));
        $miscChargesBdt = 15000.00;

        $totalLocalChargesBdt = $portAndCfChargesBdt + $brtaRegistrationBdt + $serviceFeeBdt + $miscChargesBdt;

        // 6. Total Bangladesh Landed Cost
        $totalLandedCostBdt = round($cifValueBdt + $totalCustomsAndTaxesBdt + $totalLocalChargesBdt, 2);

        return [
            // Base input mirror
            'price_jpy' => $priceJpy,
            'price_bdt' => round($priceJpy * $exchangeRate, 2),
            'engine_cc' => $engineCc,
            'year' => $year,
            'vehicle_age' => $vehicleAge,
            'depreciation_percentage' => $depreciationPercent,
            'fuel_type' => $fuelType,
            'is_hybrid' => $isHybrid,
            'exchange_rate' => $exchangeRate,

            // Japan costs
            'auction_fee_jpy' => $auctionFeeJpy,
            'inland_transport_jpy' => $inlandTransportJpy,
            'shipping_jpy' => $shippingJpy,
            'total_japan_jpy' => $totalJapanJpy,
            'total_japan_bdt' => $totalJapanBdt,
            'marine_insurance_bdt' => $marineInsuranceBdt,
            'cif_value_bdt' => $cifValueBdt,
            'assessable_value_bdt' => $assessableValueBdt,

            // Duty breakdown
            'rates' => $taxRates,
            'customs_duty_bdt' => $customsDuty,
            'regulatory_duty_bdt' => $regulatoryDuty,
            'supplementary_duty_bdt' => $supplementaryDuty,
            'vat_bdt' => $vat,
            'advance_income_tax_bdt' => $advanceIncomeTax,
            'advance_tax_bdt' => $advanceTax,
            'total_customs_taxes_bdt' => $totalCustomsAndTaxesBdt,

            // Bangladesh local charges
            'port_and_cf_charges_bdt' => $portAndCfChargesBdt,
            'brta_registration_bdt' => $brtaRegistrationBdt,
            'service_fee_bdt' => $serviceFeeBdt,
            'misc_charges_bdt' => $miscChargesBdt,
            'total_local_charges_bdt' => $totalLocalChargesBdt,

            // Final total
            'total_landed_cost_bdt' => $totalLandedCostBdt,

            // Suggested payment milestones
            'payment_milestones' => [
                'booking_deposit_20' => round($totalLandedCostBdt * 0.20, -2),
                'japan_export_40' => round($totalLandedCostBdt * 0.40, -2),
                'customs_duty_30' => round($totalLandedCostBdt * 0.30, -2),
                'delivery_balance_10' => round($totalLandedCostBdt * 0.10, -2),
            ],

            'disclaimer' => 'Estimated cost only. Final customs and government charges may vary based on applicable Bangladesh regulations and actual NBR Chittagong customs assessment.',
        ];
    }

    protected function getDepreciationPercentage(int $age): float
    {
        return match (true) {
            $age >= 4 => 40.0,
            $age === 3 => 30.0,
            $age === 2 => 20.0,
            $age === 1 => 10.0,
            default => 0.0,
        };
    }

    protected function resolveTaxRates(int $cc, bool $isHybrid, string $fuelType): array
    {
        // Try database lookup first
        $dbRule = TaxRule::where('is_active', true)
            ->where('cc_min', '<=', $cc)
            ->where('cc_max', '>=', $cc)
            ->where('is_hybrid', $isHybrid)
            ->first();

        if ($dbRule) {
            return [
                'cd' => (float) $dbRule->customs_duty_rate,
                'rd' => (float) $dbRule->regulatory_duty_rate,
                'sd' => (float) $dbRule->supplementary_duty_rate,
                'vat' => (float) $dbRule->vat_rate,
                'ait' => (float) $dbRule->advance_income_tax_rate,
                'at' => (float) $dbRule->advance_tax_rate,
                'rule_name' => $dbRule->name,
            ];
        }

        // Authentic Bangladesh NBR tariff defaults
        $cd = 25.0; // Standard 25% Customs Duty
        $rd = 3.0;  // Standard 3% Regulatory Duty
        $vat = 15.0; // 15% VAT
        $ait = 5.0;  // 5% Advance Income Tax
        $at = 5.0;   // 5% Advance Tax

        // Supplementary Duty depends strongly on CC and Hybrid status
        $sd = match (true) {
            $cc <= 1000 => $isHybrid ? 0.0 : 0.0,
            $cc <= 1500 => $isHybrid ? 20.0 : 20.0,
            $cc <= 1600 => $isHybrid ? 30.0 : 45.0,
            $cc <= 1800 => $isHybrid ? 45.0 : 60.0,
            $cc <= 2000 => $isHybrid ? 60.0 : 100.0,
            $cc <= 2750 => $isHybrid ? 150.0 : 200.0,
            $cc <= 3000 => $isHybrid ? 250.0 : 350.0,
            default => $isHybrid ? 350.0 : 500.0,
        };

        return [
            'cd' => $cd,
            'rd' => $rd,
            'sd' => $sd,
            'vat' => $vat,
            'ait' => $ait,
            'at' => $at,
            'rule_name' => "Standard NBR Tariff ({$cc}cc " . ($isHybrid ? 'Hybrid' : 'Non-Hybrid') . ")",
        ];
    }

    protected function getSetting(string $key, mixed $default = null): mixed
    {
        $setting = ImportChargeSetting::where('charge_key', $key)->first();
        return $setting ? (float) $setting->amount : $default;
    }
}
