<?php

namespace App\Http\Controllers;

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

class SistemaController extends Controller
{
    public function index(Request $r)
    {
        $q = Sistema::with('area')->withCount('equipos');
        if ($busqueda = trim((string)$r->get('q', ''))) {
            $q->where(fn($w) => $w->where('codigo','like',"%$busqueda%")->orWhere('nombre','like',"%$busqueda%"));
        }
        if ($area_id = $r->integer('area_id')) $q->where('area_id', $area_id);
        $registros = $q->orderBy('codigo')->paginate(25)->withQueryString();
        $areas = Area::where('activo',1)->orderBy('nombre')->get();
        return view('catalogos.sistemas_index', compact('registros','busqueda','areas','area_id'));
    }

    public function create()
    {
        return view('catalogos.sistemas_form', [
            'registro' => new Sistema(['activo' => true]),
            'areas' => Area::where('activo',1)->orderBy('nombre')->get(),
        ]);
    }

    public function store(Request $r)
    {
        Sistema::create($this->validar($r));
        return redirect()->route('sistemas.index')->with('exito','Sistema creado.');
    }

    public function edit(Sistema $sistema)
    {
        return view('catalogos.sistemas_form', [
            'registro' => $sistema,
            'areas' => Area::where('activo',1)->orderBy('nombre')->get(),
        ]);
    }

    public function update(Request $r, Sistema $sistema)
    {
        $sistema->update($this->validar($r, $sistema->id));
        return redirect()->route('sistemas.index')->with('exito','Sistema actualizado.');
    }

    public function destroy(Sistema $sistema)
    {
        try { $sistema->delete(); return back()->with('exito','Eliminado.'); }
        catch (\Throwable $e) { return back()->with('error','En uso.'); }
    }

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