<?php

namespace App\Modules\Finance\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Finance\Models\UtilityFee;
use App\Modules\Finance\Contracts\FinanceServiceInterface;
use Illuminate\Http\Request;
use Inertia\Inertia;

class UtilityFeeController extends Controller
{
    protected $financeService;

    public function __construct(FinanceServiceInterface $financeService)
    {
        $this->financeService = $financeService;
    }

    public function index(Request $request)
    {
        $filters = $request->only(['search', 'category', 'date_start', 'date_end', 'sort_field', 'sort_direction', 'per_page']);
        
        $fees = $this->financeService->getUtilityFees($filters)->withQueryString();
        $availableCategories = $this->financeService->getUniqueCategories();

        return Inertia::render('UtilityFee/Index', [
            'fees' => $fees,
            'availableCategories' => $availableCategories,
            'filters' => $filters,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'transaction_date' => 'required|date',
            'category' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
            'invoice_number' => 'nullable|string|max:255',
            'description' => 'nullable|string',
        ]);

        $fee = UtilityFee::create($validated);

        activity()
            ->performedOn($fee)
            ->causedBy(auth()->user())
            ->event('created')
            ->log('created');

        return redirect()->back();
    }

    public function update(Request $request, UtilityFee $utility_fee)
    {
        $validated = $request->validate([
            'transaction_date' => 'required|date',
            'category' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
            'invoice_number' => 'nullable|string|max:255',
            'description' => 'nullable|string',
        ]);

        $utility_fee->update($validated);

        activity()
            ->performedOn($utility_fee)
            ->causedBy(auth()->user())
            ->event('updated')
            ->log('updated');

        return redirect()->back();
    }

    public function destroy(UtilityFee $utility_fee)
    {
        activity()
            ->performedOn($utility_fee)
            ->causedBy(auth()->user())
            ->event('deleted')
            ->log('deleted');

        $utility_fee->delete();
        
        return redirect()->back();
    }
}
