<?php

namespace App\Http\Controllers\Admin\Ranch;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreMaterialExpenseRequest;
use App\Models\FatteningLot;
use App\Models\MaterialExpense;
use App\Models\MaterialType;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class MaterialExpensePageController extends Controller
{
    public function index(Request $request): Response
    {
        $query = MaterialExpense::query()
            ->with(['materialType', 'fatteningLot:id,name', 'user:id,name'])
            ->orderByDesc('expense_date');

        if ($request->filled('from') && $request->filled('to')) {
            $query->whereBetween('expense_date', [$request->date('from'), $request->date('to')]);
        }

        return Inertia::render('Ranch/Expenses/Index', [
            'expenses' => $query->paginate(25)->withQueryString(),
            'filters' => [
                'from' => $request->get('from', ''),
                'to' => $request->get('to', ''),
            ],
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Ranch/Expenses/Form', [
            'materialTypes' => MaterialType::active()->orderBy('category')->orderBy('name')->get(),
            'lots' => FatteningLot::query()->where('status', FatteningLot::STATUS_OPEN)->orderBy('name')->get(['id', 'name']),
            'categories' => config('ranch.material_categories'),
        ]);
    }

    public function store(StoreMaterialExpenseRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $qty = (float) $data['quantity'];
        $unit = (float) $data['unit_cost'];

        MaterialExpense::create([
            ...$data,
            'total_cost' => round($qty * $unit, 2),
            'user_id' => auth()->id(),
        ]);

        return redirect()
            ->route('admin.ranch.expenses.index')
            ->with('success', 'Gasto registrado.');
    }
}
