<?php

namespace App\Http\Controllers\Admin\Ranch;

use App\Http\Controllers\Controller;
use App\Models\Pasture;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;

class PasturePageController extends Controller
{
    public function index(): Response
    {
        $pastures = Pasture::query()
            ->withCount(['cattle as active_cattle_count' => function ($q) {
                $q->where('status', 'active');
            }])
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return Inertia::render('Ranch/Pastures/Index', [
            'pastures' => $pastures,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120', 'unique:pastures,name'],
            'code' => ['nullable', 'string', 'max:40', 'unique:pastures,code'],
            'notes' => ['nullable', 'string'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        Pasture::create($validated + ['active' => true]);

        return back()->with('success', 'Potrero creado.');
    }

    public function update(Request $request, Pasture $pasture): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['sometimes', 'string', 'max:120', Rule::unique('pastures', 'name')->ignore($pasture->id)],
            'code' => ['nullable', 'string', 'max:40', Rule::unique('pastures', 'code')->ignore($pasture->id)],
            'active' => ['sometimes', 'boolean'],
            'notes' => ['nullable', 'string'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $oldName = $pasture->name;
        $pasture->update($validated);

        if (isset($validated['name']) && $validated['name'] !== $oldName) {
            $pasture->cattle()->update(['pasture_location' => $pasture->name]);
        }

        return back()->with('success', 'Potrero actualizado.');
    }
}
