<?php

namespace App\Http\Controllers\Catalogos;

use App\Http\Controllers\Controller;
use App\Models\Broker;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Inertia\Inertia;

class BrokerController extends Controller
{
    /**
     * Display a listing of the brokers.
     */
    public function index(Request $request)
    {
        $query = Broker::query();

        if ($request->has('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('razon_social', 'like', "%{$search}%")
                    ->orWhere('ruc', 'like', "%{$search}%")
                    ->orWhere('contacto', 'like', "%{$search}%");
            });
        }

        $brokers = $query->orderBy('razon_social')->paginate(10)->withQueryString();

        return Inertia::render('Catalogos/Brokers/Index', [
            'brokers' => $brokers,
            'filters' => $request->only(['search']),
        ]);
    }

    /**
     * Store a newly created broker in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'ruc' => 'required|string|max:20|unique:brokers,ruc',
            'razon_social' => 'required|string|max:255',
            'telefono' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'contacto' => 'nullable|string|max:255',
            'activo' => 'boolean',
        ]);

        $tenantId = auth()->user()->tenant_id;
        if (! $tenantId) {
            $firstTenant = Tenant::first();
            $tenantId = $firstTenant ? $firstTenant->id : 1;
        }

        $validated['tenant_id'] = $tenantId;
        $validated['activo'] = $request->boolean('activo', true);

        Broker::create($validated);

        return redirect()->route('brokers.index')
            ->with('message', 'Broker creado exitosamente.');
    }

    /**
     * Update the specified broker in storage.
     */
    public function update(Request $request, Broker $broker)
    {
        $validated = $request->validate([
            'ruc' => 'required|string|max:20|unique:brokers,ruc,'.$broker->id,
            'razon_social' => 'required|string|max:255',
            'telefono' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'contacto' => 'nullable|string|max:255',
            'activo' => 'boolean',
        ]);

        $validated['activo'] = $request->boolean('activo');

        $broker->update($validated);

        return redirect()->route('brokers.index')
            ->with('message', 'Broker actualizado exitosamente.');
    }

    /**
     * Remove the specified broker from storage.
     */
    public function destroy(Broker $broker)
    {
        // Add a check to prevent deletion if there are cases tied to it?
        // Typically handled by DB foreign keys, but we can do it softly here.
        if ($broker->casos()->count() > 0) {
            return redirect()->route('brokers.index')
                ->with('error', 'No se puede eliminar el broker porque tiene casos asociados.');
        }

        $broker->delete();

        return redirect()->route('brokers.index')
            ->with('message', 'Broker eliminado exitosamente.');
    }
}
