<?php

namespace App\Http\Controllers;

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

class PersonalZurichController extends Controller
{
    public function index(Request $request)
    {
        $query = PersonalZurich::with('tenant');

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

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

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

        $personal = $query->orderBy('nombre')->get();

        return Inertia::render('Catalogos/Personal', [
            'title' => 'Personal Zurich',
            'personal' => $personal,
            'aseguradoras' => Tenant::all(),
            'filters' => $request->only(['search', 'cargo', 'rol']),
            'roles' => ['ejecutivo', 'director', 'reinspector', 'gerente', 'coordinador'],
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'tenant_id' => 'required|exists:tenants,id',
            'nombre' => 'required|string|max:255',
            'cargo' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'telefono' => 'nullable|string|max:50',
            'rol' => 'required|in:ejecutivo,director,reinspector,gerente,coordinador',
        ]);

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

        PersonalZurich::create($validated);

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

    public function update(Request $request, PersonalZurich $personal)
    {
        $validated = $request->validate([
            'tenant_id' => 'required|exists:tenants,id',
            'nombre' => 'required|string|max:255',
            'cargo' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'telefono' => 'nullable|string|max:50',
            'rol' => 'required|in:ejecutivo,director,reinspector,gerente,coordinador',
            'activo' => 'boolean',
        ]);

        $personal->update($validated);

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

    public function destroy(PersonalZurich $personal)
    {
        // Check if used in any active case
        $casoCount = $personal->casosComoEjecutivo()->count()
            + $personal->casosComoDirector()->count()
            + $personal->casosComoReinspector()->count();

        if ($casoCount > 0) {
            $personal->update(['activo' => false]);

            return back()->with('message', 'Personal desactivado (tiene casos asociados)');
        }

        $personal->delete();

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