<?php

namespace App\Http\Controllers;

use App\Models\Proveedor;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ProveedorController extends Controller
{
    public function index(): View
    {
        $empresaId = tenant_empresa_id();
        abort_if(! $empresaId, 403, 'No hay empresa activa.');

        $proveedores = Proveedor::query()
            ->where('empresa_id', $empresaId)
            ->orderBy('nombre')
            ->paginate(20);

        return view('modules.proveedores.index', [
            'proveedores' => $proveedores,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $empresaId = tenant_empresa_id();
        abort_if(! $empresaId, 403, 'No hay empresa activa.');

        $validated = $request->validate([
            'nombre' => ['required', 'string', 'max:180'],
            'documento' => ['nullable', 'string', 'max:80'],
            'email' => ['nullable', 'email', 'max:180'],
            'telefono' => ['nullable', 'string', 'max:60'],
            'direccion' => ['nullable', 'string', 'max:255'],
            'activo' => ['nullable', 'boolean'],
        ]);

        Proveedor::query()->create([
            'empresa_id' => $empresaId,
            'nombre' => $validated['nombre'],
            'documento' => $validated['documento'] ?? null,
            'email' => $validated['email'] ?? null,
            'telefono' => $validated['telefono'] ?? null,
            'direccion' => $validated['direccion'] ?? null,
            'activo' => $request->boolean('activo', true),
        ]);

        return redirect()->route('proveedores.index')
            ->with('status', 'Proveedor creado correctamente.');
    }
}
