<?php

namespace App\Http\Controllers\Admin;

use App\Data\CountriesData;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\TaxRule;
use Illuminate\Http\Request;

class TaxController extends Controller
{
    // Tax-specific settings keys and their defaults
    private const DEFAULTS = [
        'tax_enabled'           => '1',
        'tax_calculation_type'  => 'exclusive',
        'tax_id_label'          => 'Tax ID/VAT/GST',
        'tax_discount_logic'    => 'tax_after_discount',
        'tax_home_country'      => 'India',
        'tax_exempt_countries'  => '',
        'tax_exempt_if_tax_id'  => '0',
        'tax_vat_gst_mode'      => '0',
        'tax_domains'           => '1',
        'tax_billable'          => '1',
        'tax_late_fees'         => '1',
    ];

    public function index()
    {
        $rules    = TaxRule::orderBy('country')->orderBy('state')->orderBy('level')->get();
        $settings = [];
        foreach (self::DEFAULTS as $key => $default) {
            $settings[$key] = Setting::get($key, $default);
        }

        $stats = [
            'total'     => $rules->count(),
            'countries' => $rules->pluck('country')->unique()->count(),
            'regions'   => $rules->whereNotNull('state')->pluck('state')->unique()->count(),
        ];

        $countries     = CountriesData::names();
        $countriesData = CountriesData::all();   // passed as JSON to JS

        return view('admin.tax.index', compact('rules', 'settings', 'stats', 'countries', 'countriesData'));
    }

    public function saveSettings(Request $request)
    {
        $booleans = ['tax_enabled','tax_exempt_if_tax_id','tax_vat_gst_mode','tax_domains','tax_billable','tax_late_fees'];
        $data     = $request->except(['_token','_method']);

        foreach (self::DEFAULTS as $key => $default) {
            $value = in_array($key, $booleans)
                ? (isset($data[$key]) && $data[$key] === '1' ? '1' : '0')
                : ($data[$key] ?? $default);
            Setting::set($key, $value);
        }

        return back()->with('success', 'Tax settings saved successfully.');
    }

    public function storeRule(Request $request)
    {
        $data = $request->validate([
            'name'    => 'required|string|max:100',
            'country' => 'required|string|max:80',
            'state'   => 'nullable|string|max:80',
            'level'   => 'required|string|max:20',
            'rate'    => 'required|numeric|min:0|max:100',
        ]);

        $data['state']     = $data['state'] ?: null;
        $data['is_active'] = true;

        TaxRule::create($data);

        return back()->with('success', "Tax rule \"{$data['name']}\" added.");
    }

    public function updateRule(Request $request, TaxRule $rule)
    {
        $data = $request->validate([
            'rate' => 'required|numeric|min:0|max:100',
        ]);

        $rule->update($data);

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

    public function duplicateRule(TaxRule $rule)
    {
        TaxRule::create([
            'name'      => $rule->name . ' (copy)',
            'country'   => $rule->country,
            'state'     => $rule->state,
            'level'     => $rule->level,
            'rate'      => $rule->rate,
            'is_active' => $rule->is_active,
        ]);

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

    public function destroyRule(TaxRule $rule)
    {
        $name = $rule->name;
        $rule->delete();

        return back()->with('success', "{$name} deleted.");
    }

    public function simulate(Request $request)
    {
        $request->validate([
            'sim_amount'  => 'required|numeric|min:0',
            'sim_country' => 'required|string',
            'sim_state'   => 'nullable|string',
        ]);

        $result = TaxRule::calculate(
            (float) $request->sim_amount,
            $request->sim_country,
            $request->sim_state ?: null
        );

        return back()->with('sim_result', $result)->with('sim_amount', $request->sim_amount);
    }
}
