<?php

namespace App\Http\Controllers;

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

class TallerController extends Controller
{
    public function index(Request $request)
    {
        $query = Taller::query();

        if ($request->search) {
            $query->where('razon_social', 'like', "%{$request->search}%")
                ->orWhere('ruc', 'like', "%{$request->search}%");
        }

        if ($request->tipo) {
            $query->where('tipo', $request->tipo);
        }

        $talleres = $query->orderBy('razon_social')->paginate(20);

        return inertia('Catalogos/Talleres', [
            'title' => 'Talleres',
            'talleres' => $talleres,
            'tipos' => ['dealer', 'multimarca_dealer', 'multimarca', 'taller_asegurado'],
            'filtros' => $request->only(['search', 'tipo']),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'ruc' => 'required|unique:talleres,ruc',
            'razon_social' => 'required|string',
            'tipo' => 'required|in:dealer,multimarca_dealer,multimarca,taller_asegurado',
        ]);

        Taller::create([
            'ruc' => $request->ruc,
            'razon_social' => $request->razon_social,
            'ciudad' => $request->ciudad,
            'contacto' => $request->contacto,
            'telefono' => $request->telefono,
            'email' => $request->email,
            'tipo' => $request->tipo,
            'codigo_sistema' => 'TAL-'.strtoupper(substr($request->ruc, 0, 8)),
        ]);

        return back()->with('message', 'Taller creado');
    }

    public function update(Request $request, Taller $taller)
    {
        $request->validate([
            'ruc' => 'required|unique:talleres,ruc,'.$taller->id,
            'razon_social' => 'required|string',
            'tipo' => 'required|in:dealer,multimarca_dealer,multimarca,taller_asegurado',
        ]);

        $taller->update($request->all());

        return back()->with('message', 'Taller actualizado');
    }

    public function destroy(Taller $taller)
    {
        $taller->delete();

        return back()->with('message', 'Taller eliminado');
    }
}
