<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\SeoMeta;
use App\Models\TaxRule;
use App\Models\ImportChargeSetting;
use App\Services\Calculator\BangladeshLandedCostCalculator;
use Illuminate\Http\Request;

class CalculatorController extends Controller
{
    protected BangladeshLandedCostCalculator $calculator;

    public function __construct(BangladeshLandedCostCalculator $calculator)
    {
        $this->calculator = $calculator;
    }

    public function index()
    {
        $seo = SeoMeta::where('url_path', '/calculator')->first();
        $taxRules = TaxRule::where('is_active', true)->get();
        $settings = ImportChargeSetting::all()->pluck('amount', 'charge_key');

        // Initial default calculation (Toyota Corolla Cross Hybrid 2022 at ¥2,500,000)
        $defaultCalc = $this->calculator->calculate([
            'price_jpy' => 2500000,
            'engine_cc' => 1797,
            'fuel_type' => 'Hybrid',
            'is_hybrid' => true,
            'year' => date('Y') - 2,
        ]);

        return view('public.calculator', compact('seo', 'taxRules', 'settings', 'defaultCalc'));
    }

    public function calculate(Request $request)
    {
        $validated = $request->validate([
            'price_jpy' => 'required|numeric|min:100000',
            'engine_cc' => 'required|integer|min:500|max:6000',
            'fuel_type' => 'required|string',
            'is_hybrid' => 'nullable|boolean',
            'year' => 'required|integer|min:' . (date('Y') - 5) . '|max:' . date('Y'),
            'exchange_rate' => 'nullable|numeric|min:0.1|max:5',
        ]);

        $result = $this->calculator->calculate($validated);

        return response()->json([
            'success' => true,
            'data' => $result,
        ]);
    }
}
