<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TaxRule;
use App\Models\ImportChargeSetting;
use App\Models\AuditLog;
use Illuminate\Http\Request;

class CalculatorAdminController extends Controller
{
    public function index()
    {
        $taxRules = TaxRule::orderBy('cc_min', 'asc')->get();
        $charges = ImportChargeSetting::all();

        return view('admin.calculator.index', compact('taxRules', 'charges'));
    }

    public function updateCharge(Request $request, string $id)
    {
        $charge = ImportChargeSetting::findOrFail($id);

        $validated = $request->validate([
            'amount' => 'required|numeric|min:0',
        ]);

        $oldAmount = $charge->amount;
        $charge->update(['amount' => $validated['amount']]);

        AuditLog::record('admin_updated_import_charge', $charge, ['amount' => $oldAmount], ['amount' => $validated['amount']]);

        return back()->with('success', "Charge {$charge->name} updated to {$charge->amount}.");
    }

    public function updateTaxRule(Request $request, string $id)
    {
        $rule = TaxRule::findOrFail($id);

        $validated = $request->validate([
            'customs_duty_rate' => 'required|numeric|min:0|max:100',
            'regulatory_duty_rate' => 'required|numeric|min:0|max:100',
            'supplementary_duty_rate' => 'required|numeric|min:0|max:1000',
            'vat_rate' => 'required|numeric|min:0|max:100',
            'advance_income_tax_rate' => 'required|numeric|min:0|max:100',
            'advance_tax_rate' => 'required|numeric|min:0|max:100',
            'is_active' => 'nullable|boolean',
        ]);

        $rule->update(array_merge($validated, [
            'is_active' => $request->boolean('is_active'),
        ]));

        AuditLog::record('admin_updated_tax_rule', $rule);

        return back()->with('success', "Tax rule {$rule->name} updated successfully.");
    }
}
