<?php

namespace App\Http\Controllers;

use App\Models\Proveedor;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class ProveedorController extends Controller
{
    public function index(Request $request)
    {
        $query = Proveedor::with(['tenant', 'ejecutivos']);

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

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

        $proveedores = $query->orderBy('razon_social')->get();

        return Inertia::render('Catalogos/Proveedores', [
            'title' => 'Proveedores',
            'proveedores' => $proveedores,
            'aseguradoras' => Tenant::all(),
            'filters' => $request->only(['search', 'tipo']),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'tenant_id' => 'required|exists:tenants,id',
            'ruc' => 'required|string|max:13|unique:proveedores,ruc',
            'razon_social' => 'required|string|max:255',
            'tipo' => 'required|in:dealer,multimarca',
            'contacto' => 'nullable|string|max:255',
            'telefono' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'ejecutivos' => 'nullable|array',
            'ejecutivos.*.nombre' => 'required|string|max:255',
            'ejecutivos.*.cargo' => 'nullable|string|max:255',
            'ejecutivos.*.telefono' => 'nullable|string|max:50',
            'ejecutivos.*.email' => 'nullable|email|max:255',
        ]);

        $validated['codigo_sistema'] = 'PROV-'.strtoupper(Str::random(6));
        $validated['activo'] = true;

        $proveedor = Proveedor::create(collect($validated)->except('ejecutivos')->toArray());

        // Create associated executives (M11: multiple executives per company)
        if (! empty($validated['ejecutivos'])) {
            foreach ($validated['ejecutivos'] as $ejecutivo) {
                $proveedor->ejecutivos()->create($ejecutivo);
            }
        }

        return back()->with('message', 'Proveedor registrado correctamente');
    }

    public function update(Request $request, Proveedor $proveedor)
    {
        $validated = $request->validate([
            'tenant_id' => 'required|exists:tenants,id',
            'ruc' => 'required|string|max:13|unique:proveedores,ruc,'.$proveedor->id,
            'razon_social' => 'required|string|max:255',
            'tipo' => 'required|in:dealer,multimarca',
            'contacto' => 'nullable|string|max:255',
            'telefono' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'activo' => 'boolean',
            'ejecutivos' => 'nullable|array',
            'ejecutivos.*.id' => 'nullable|integer',
            'ejecutivos.*.nombre' => 'required|string|max:255',
            'ejecutivos.*.cargo' => 'nullable|string|max:255',
            'ejecutivos.*.telefono' => 'nullable|string|max:50',
            'ejecutivos.*.email' => 'nullable|email|max:255',
        ]);

        $proveedor->update(collect($validated)->except('ejecutivos')->toArray());

        // Sync executives: update existing, create new, delete removed
        if (isset($validated['ejecutivos'])) {
            $existingIds = [];
            foreach ($validated['ejecutivos'] as $ejData) {
                if (! empty($ejData['id'])) {
                    $proveedor->ejecutivos()->where('id', $ejData['id'])->update($ejData);
                    $existingIds[] = $ejData['id'];
                } else {
                    $newEj = $proveedor->ejecutivos()->create($ejData);
                    $existingIds[] = $newEj->id;
                }
            }
            // Remove executives not in the update
            $proveedor->ejecutivos()->whereNotIn('id', $existingIds)->delete();
        }

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

    public function destroy(Proveedor $proveedor)
    {
        if ($proveedor->cotizaciones()->count() > 0) {
            $proveedor->update(['activo' => false]);

            return back()->with('message', 'Proveedor desactivado (tiene cotizaciones asociadas)');
        }

        $proveedor->ejecutivos()->delete();
        $proveedor->delete();

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