<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TaxRate;
use App\Models\TaxRecord;
use Illuminate\Http\Request;

class TaxController extends Controller
{
    public function index(Request $request)
    {
        $rates = TaxRate::when($request->search, fn ($q, $s) => $q->where('name', 'like', "%{$s}%"))->orderBy('name')->paginate(15);
        $records = TaxRecord::latest('due_date')->paginate(10);

        return view('admin.tax.index', compact('rates', 'records'));
    }

    public function storeRate(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string',
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
        ]);
        TaxRate::create($validated);

        return back()->with('success', 'Tax rate created.');
    }

    public function storeRecord(Request $request)
    {
        $validated = $request->validate([
            'type' => 'required|string',
            'period' => 'required|string',
            'amount' => 'required|numeric|min:0',
            'due_date' => 'required|date',
            'notes' => 'nullable|string',
        ]);
        TaxRecord::create(array_merge($validated, ['status' => 'PENDING', 'created_by' => auth()->id()]));

        return back()->with('success', 'Tax record created.');
    }
}
