<?php

namespace App\Http\Controllers;

use App\Models\EtimsConfig;
use App\Models\EtimsInvoice;
use App\Models\TaxConfig;
use Illuminate\Http\Request;

class TaxController extends Controller
{
    public function index()
    {
        $taxConfigs = TaxConfig::orderBy('is_default', 'desc')->orderBy('name')->get();

        return view('tax.index', compact('taxConfigs'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:tax_configs,code',
            'rate' => 'required|numeric|min:0|max:100',
            'type' => 'required|in:vat,service,excise,other',
            'description' => 'nullable|string',
        ]);

        $isDefault = $request->boolean('is_default');

        if ($isDefault) {
            TaxConfig::where('is_default', true)->update(['is_default' => false]);
        }

        TaxConfig::create([
            'name' => $request->name,
            'code' => $request->code,
            'rate' => $request->rate,
            'type' => $request->type,
            'is_active' => $request->boolean('is_active'),
            'is_default' => $isDefault,
            'description' => $request->description,
        ]);

        return redirect()->route('tax.index')->with('success', 'Tax configuration created successfully.');
    }

    public function update(Request $request, TaxConfig $taxConfig)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:tax_configs,code,'.$taxConfig->id,
            'rate' => 'required|numeric|min:0|max:100',
            'type' => 'required|in:vat,service,excise,other',
            'description' => 'nullable|string',
        ]);

        $isDefault = $request->boolean('is_default');

        if ($isDefault && ! $taxConfig->is_default) {
            TaxConfig::where('is_default', true)->update(['is_default' => false]);
        }

        $taxConfig->update([
            'name' => $request->name,
            'code' => $request->code,
            'rate' => $request->rate,
            'type' => $request->type,
            'is_active' => $request->boolean('is_active'),
            'is_default' => $isDefault,
            'description' => $request->description,
        ]);

        return redirect()->route('tax.index')->with('success', 'Tax configuration updated successfully.');
    }

    public function destroy(TaxConfig $taxConfig)
    {
        $taxConfig->delete();

        return redirect()->route('tax.index')->with('success', 'Tax configuration deleted successfully.');
    }

    public function toggle(TaxConfig $taxConfig)
    {
        $taxConfig->update(['is_active' => ! $taxConfig->is_active]);

        return redirect()->route('tax.index')->with('success', 'Tax status updated.');
    }

    public function etimsIndex()
    {
        $config = EtimsConfig::first() ?? new EtimsConfig;

        return view('tax.etims', compact('config'));
    }

    public function etimsStore(Request $request)
    {
        $request->validate([
            'company_name' => 'required|string|max:255',
            'company_npwp' => 'nullable|string|max:20',
            'company_nik' => 'nullable|string|max:20',
            'api_url' => 'nullable|url',
            'client_id' => 'nullable|string|max:255',
            'client_secret' => 'nullable|string|max:255',
            'machine_id' => 'required|string|max:50',
            'register_id' => 'required|string|max:50',
        ]);

        $config = EtimsConfig::first();

        if ($request->is_active && (! $config || ! $config->is_active)) {
            EtimsConfig::where('is_active', true)->update(['is_active' => false]);
        }

        $data = $request->except(['_token', '_method']);
        $data['is_active'] = $request->is_active ?? false;
        $data['is_production'] = $request->is_production ?? false;

        if ($config) {
            $config->update($data);
        } else {
            EtimsConfig::create($data);
        }

        return redirect()->route('tax.etims')->with('success', 'e-TIMS configuration saved successfully.');
    }

    public function etimsInvoices(Request $request)
    {
        $query = EtimsInvoice::with('order');

        if ($request->status) {
            $query->where('etims_status', $request->status);
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $invoices = $query->orderBy('created_at', 'desc')->paginate(20);

        return view('tax.invoices', compact('invoices'));
    }

    public function getTaxRates()
    {
        $taxes = TaxConfig::active()->get(['id', 'name', 'code', 'rate', 'type']);

        return response()->json($taxes);
    }

    public function calculateTax(Request $request)
    {
        $subtotal = $request->subtotal ?? 0;
        $taxConfigs = TaxConfig::active()->get();

        $result = TaxConfig::calculateTax($subtotal, $taxConfigs);

        return response()->json([
            'subtotal' => $subtotal,
            ...$result,
        ]);
    }
}
