@extends('layouts.app')

@section('content')
<div class="bg-body-light">
    <div class="content content-full">
        <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2">
            <div class="flex-grow-1">
                <h1 class="h3 fw-bold mb-2">
                    <i class="fa fa-user-plus text-primary me-2"></i>Nuevo {{ $tipo === 'vendedores' ? 'Vendedor' : 'Cobrador' }}
                </h1>
                <h2 class="fs-base lh-base fw-medium text-muted mb-0">
                    Registre un nuevo agente en la categoría <span class="nav-main-link-badge badge bg-primary">{{ ucfirst($tipo) }}</span>.
                </h2>
            </div>
            <div class="flex-shrink-0 mt-3 mt-sm-0 ms-sm-3">
                <a href="{{ route('cobradores-vendedores.index', ['tipo' => $tipo]) }}" class="btn btn-alt-secondary">
                    <i class="fa fa-arrow-left me-1"></i> Volver al listado
                </a>
            </div>
        </div>
    </div>
</div>

<div class="content">
    <div class="row justify-content-center">
        <div class="col-md-10 col-lg-8">
            {{-- Manejo de Errores --}}
            @if($errors->any() || session('error'))
                <div class="alert alert-danger d-flex align-items-center mb-4" role="alert">
                    <div class="flex-shrink-0">
                        <i class="fa fa-fw fa-exclamation-triangle"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <p class="mb-0 fw-semibold">{{ session('error') ?? 'Existen errores en el formulario:' }}</p>
                        @if($errors->any())
                        <ul class="mb-0 fs-sm">
                            @foreach($errors->all() as $e) <li>{{ $e }}</li> @endforeach
                        </ul>
                        @endif
                    </div>
                </div>
            @endif

            <div class="block block-rounded block-bordered shadow-sm">
                <div class="block-header block-header-default">
                    <h3 class="block-title">Formulario de Registro</h3>
                    <div class="block-options">
                        <span class="nav-main-link-badge badge bg-info-light text-info">
                            <i class="fa fa-keyboard me-1"></i> Modo Ingreso
                        </span>
                    </div>
                </div>
                <div class="block-content block-content-full">
                    <form method="POST" action="{{ route('cobradores-vendedores.store') }}">
                        @csrf
                        
                        {{-- Configuración Inicial --}}
                        <div class="row mb-4 bg-body-light p-3 rounded-3 mx-0">
                            {{-- Selección de Tipo --}}
                            <div class="col-sm-6 mb-3 mb-sm-0">
                                <label class="form-label fs-xs text-uppercase text-muted fw-bold mb-2">Asignar Categoría</label>
                                <div class="d-flex gap-4 align-items-center pt-1">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="tipo" id="tipoVen" value="vendedores" {{ $tipo === 'vendedores' ? 'checked' : '' }}>
                                        <label class="form-check-label fs-sm" for="tipoVen">Vendedor</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="tipo" id="tipoCob" value="cobradores" {{ $tipo === 'cobradores' ? 'checked' : '' }}>
                                        <label class="form-check-label fs-sm" for="tipoCob">Cobrador</label>
                                    </div>
                                </div>
                            </div>
                            {{-- Fecha (Automática) --}}
                            <div class="col-sm-6">
                                <label class="form-label fs-xs text-uppercase text-muted fw-bold mb-2">Fecha de Registro</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white border-0"><i class="fa fa-calendar-check text-success"></i></span>
                                    <input type="text" class="form-control form-control-alt border-0 fw-bold" name="fecha" value="{{ $hoy }}" readonly>
                                </div>
                            </div>
                        </div>

                        {{-- Inclusión de campos comunes --}}
                        @include('cobradores_vendedores._form')

                        <div class="block-content block-content-full block-content-sm bg-body-light mx-n4 mb-n4 mt-4 text-end border-top">
                            <a href="{{ route('cobradores-vendedores.index', ['tipo' => $tipo]) }}" class="btn btn-alt-secondary">
                                Cancelar
                            </a>
                            <button type="submit" class="btn btn-primary px-4" onclick="return confirm('¿Desea guardar el nuevo registro?')">
                                <i class="fa fa-save me-1"></i> Guardar Registro
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
// Validación dinámica de CI para evitar duplicados
document.getElementById('ci').addEventListener('blur', async function () {
    const ciInput = this;
    const ciValue = ciInput.value.trim();
    const tipo = document.querySelector('input[name="tipo"]:checked')?.value;
    
    if (!ciValue || !tipo) return;

    try {
        const response = await fetch(`{{ route('cobradores-vendedores.comprobar-ci') }}?ci=${ciValue}&tipo=${tipo}`);
        const data = await response.json();
        
        if (data.existe) {
            Swal.fire({
                title: 'CI Duplicado',
                text: `El CI ${ciValue} ya pertenece a: ${data.nombre}`,
                icon: 'warning',
                confirmButtonText: 'Entendido'
            });
            ciInput.value = '';
            ciInput.focus();
        }
    } catch (error) {
        console.error("Error al validar CI:", error);
    }
});
</script>
@endpush