<?php

namespace App\Http\Controllers;

use App\Models\Area;
use Illuminate\Http\Request;

class AreaController extends Controller
{
    public function index(Request $r)
    {
        $q = Area::query()->withCount(['sistemas','equipos']);
        if ($busqueda = trim((string)$r->get('q', ''))) {
            $q->where(fn($w) => $w->where('codigo','like',"%$busqueda%")->orWhere('nombre','like',"%$busqueda%"));
        }
        $registros = $q->orderBy('codigo')->paginate(25)->withQueryString();
        return view('catalogos.areas_index', compact('registros','busqueda'));
    }

    public function create() { return view('catalogos.areas_form', ['registro' => new Area(['activo' => true])]); }

    public function store(Request $r)
    {
        $datos = $this->validar($r);
        Area::create($datos);
        return redirect()->route('areas.index')->with('exito','Área creada.');
    }

    public function edit(Area $area) { return view('catalogos.areas_form', ['registro' => $area]); }

    public function update(Request $r, Area $area)
    {
        $datos = $this->validar($r, $area->id);
        $area->update($datos);
        return redirect()->route('areas.index')->with('exito','Área actualizada.');
    }

    public function destroy(Area $area)
    {
        try { $area->delete(); return back()->with('exito','Eliminada.'); }
        catch (\Throwable $e) { return back()->with('error','No se puede eliminar: tiene registros relacionados.'); }
    }

    private function validar(Request $r, ?int $id = null): array
    {
        return $r->validate([
            'codigo' => 'required|string|max:20|unique:areas,codigo' . ($id ? ",$id" : ''),
            'nombre' => 'required|string|max:150',
            'descripcion' => 'nullable|string',
            'color' => 'nullable|string|max:10',
            'activo' => 'sometimes|boolean',
        ]) + ['activo' => $r->boolean('activo')];
    }
}
