@extends('layouts.guest')

@section('title', 'Registrar empresa | Veltrix v2')

@section('content')
@php
    $availablePlans = isset($plans) ? $plans : collect();
    $selectedPlanId = (int) old('plan_id', 0);
    $selectedPlan = null;
    foreach ($availablePlans as $planItem) {
        if ((int) ($planItem->id ?? 0) === $selectedPlanId) {
            $selectedPlan = $planItem;
            break;
        }
    }

    $moneyFormat = static function (float $value): string {
        return '$' . number_format($value, 0, ',', '.');
    };

    $selectedPlanName = $selectedPlan ? (string) ($selectedPlan->nombre ?? 'Plan seleccionado') : 'Selecciona un plan';
    $selectedPlanPrice = $selectedPlan
        ? ($moneyFormat((float) ($selectedPlan->precio_mensual ?? 0)) . '/mes')
        : 'Sin plan seleccionado';

    $slugSource = trim((string) old('nombre', ''));
    $slugValue = strtolower($slugSource);
    $slugValue = preg_replace('/[^a-z0-9-]/', '-', $slugValue) ?: '';
    $slugValue = trim($slugValue, '-');
    $slugPreviewValue = $slugValue !== '' ? $slugValue : 'miempresa';
    $baseUrl = rtrim(url(''), '/');
@endphp

<div class="card shadow-sm border-0 vx-auth-card vx-register-card">
    <div class="card-body p-0">
        <div class="row g-0">
            <div class="col-lg-8">
                <div class="p-4 p-lg-5 vx-register-pane">
                    <div class="d-flex align-items-start gap-3 mb-4">
                        <span class="vx-auth-icon vx-register-main-icon"><i class="bx bxs-building-house"></i></span>
                        <div>
                            <h2 class="h4 mb-1">Crea tu empresa en minutos</h2>
                            <p class="vx-register-subtitle mb-0">
                                Completa el formulario, elige tu plan y continúa al checkout seguro.
                            </p>
                        </div>
                    </div>

                    @if ($errors->any())
                        <div class="alert alert-danger py-2">
                            {{ $errors->first() }}
                        </div>
                    @endif

                    @if (session('error'))
                        <div class="alert alert-danger py-2">{{ session('error') }}</div>
                    @endif

                    <form action="{{ url('registro-empresa') }}" method="post" class="vx-register-form" id="vxRegisterForm" novalidate>
                        @csrf

                        <section class="vx-register-section mb-3">
                            <div class="vx-register-section-head d-flex align-items-center gap-2 mb-3">
                                <span class="vx-register-step badge rounded-circle bg-info text-white d-inline-flex align-items-center justify-content-center" style="width: 28px; height: 28px;">1</span>
                                <div>
                                    <h3 class="h6 mb-0">Datos de empresa</h3>
                                    <small class="text-muted">Información básica del negocio</small>
                                </div>
                            </div>
                            <div class="row g-3">
                                <div class="col-md-8">
                                    <label class="form-label">Nombre empresa</label>
                                    <input class="form-control" id="vxRegisterCompanyName" name="nombre" value="{{ old('nombre', '') }}" autocomplete="organization" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Slug acceso</label>
                                    <input
                                        class="form-control"
                                        id="vxRegisterSlug"
                                        placeholder="miempresa"
                                        value="{{ $slugValue }}"
                                        pattern="[a-z0-9-]+"
                                        autocomplete="off"
                                        disabled
                                        readonly
                                        aria-readonly="true"
                                        title="Se genera automáticamente desde el nombre de empresa"
                                    >
                                </div>
                                <div class="col-12">
                                    <small class="vx-register-help text-muted">
                                        URL de acceso: <code>{{ $baseUrl }}/</code><code id="vxRegisterSlugPreview">{{ $slugPreviewValue }}</code>
                                    </small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Email empresa</label>
                                    <input type="email" class="form-control" name="email" value="{{ old('email', '') }}" autocomplete="email">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">NIT</label>
                                    <input class="form-control" name="nit" value="{{ old('nit', '') }}" autocomplete="off">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Teléfono empresa</label>
                                    <input type="tel" class="form-control" name="telefono" value="{{ old('telefono', '') }}" autocomplete="tel">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Plan</label>
                                    <select class="form-select" id="vxRegisterPlan" name="plan_id" required>
                                        <option value="">Seleccione...</option>
                                        @foreach ($availablePlans as $plan)
                                            @php
                                                $planName = (string) ($plan->nombre ?? '');
                                                $planPrice = $moneyFormat((float) ($plan->precio_mensual ?? 0)) . '/mes';
                                            @endphp
                                            <option
                                                value="{{ (int) $plan->id }}"
                                                data-plan-name="{{ $planName }}"
                                                data-plan-price="{{ $planPrice }}"
                                                @selected($selectedPlanId === (int) $plan->id)
                                            >
                                                {{ $planName }} - {{ $planPrice }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Dirección</label>
                                    <input class="form-control" name="direccion" value="{{ old('direccion', '') }}" autocomplete="street-address">
                                </div>
                            </div>
                        </section>

                        <section class="vx-register-section">
                            <div class="vx-register-section-head d-flex align-items-center gap-2 mb-3">
                                <span class="vx-register-step badge rounded-circle bg-info text-white d-inline-flex align-items-center justify-content-center" style="width: 28px; height: 28px;">2</span>
                                <div>
                                    <h3 class="h6 mb-0">Administrador principal</h3>
                                    <small class="text-muted">Usuario con acceso total inicial</small>
                                </div>
                            </div>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Nombre</label>
                                    <input class="form-control" name="admin_nombre" value="{{ old('admin_nombre', '') }}" autocomplete="name" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Correo</label>
                                    <input type="email" class="form-control" name="admin_email" value="{{ old('admin_email', '') }}" autocomplete="email" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Contraseña</label>
                                    <input type="password" class="form-control" name="admin_password" autocomplete="new-password" required minlength="8">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Confirmar contraseña</label>
                                    <input type="password" class="form-control" name="admin_password_confirm" autocomplete="new-password" required minlength="8">
                                </div>
                            </div>
                        </section>

                        <div class="d-grid gap-2 d-sm-flex justify-content-sm-between align-items-center mt-4">
                            <div class="d-flex gap-2 align-items-center">
                                <a href="{{ route('login') }}" class="btn btn-outline-secondary vx-register-back">
                                    Volver al login
                                </a>
                                <a href="{{ route('precios') }}" class="btn btn-link" style="font-size:.82rem;color:#4f46e5" target="_blank">
                                    <i class="bx bx-layer me-1"></i>Ver planes
                                </a>
                            </div>
                            <button class="btn btn-primary px-4" type="submit">Continuar al pago</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-lg-4 vx-register-aside-wrap bg-light">
                <aside class="vx-register-aside p-4 p-lg-5 d-flex flex-column gap-4 h-100">
                    <div>
                        <p class="vx-register-kicker text-uppercase small fw-semibold text-info mb-1">Proceso guiado</p>
                        <h3 class="h6 mb-2">Registro SaaS listo para producción</h3>
                        <p class="small text-muted mb-0">
                            Al confirmar el pago, el sistema aprovisiona automáticamente empresa, suscripción y usuario administrador.
                        </p>
                    </div>

                    <div class="vx-register-plan p-3 rounded-3 bg-white border">
                        <small class="text-muted d-block mb-1">Plan seleccionado</small>
                        <strong id="vxRegisterPlanName">{{ $selectedPlanName }}</strong>
                        <div class="vx-register-plan-price text-info small" id="vxRegisterPlanPrice">{{ $selectedPlanPrice }}</div>
                    </div>

                    <ul class="vx-register-checklist list-unstyled mb-0">
                        <li class="mb-2"><i class="bx bx-check-circle text-info me-1"></i> Activación multiempresa</li>
                        <li class="mb-2"><i class="bx bx-check-circle text-info me-1"></i> Usuario admin inicial</li>
                        <li class="mb-2"><i class="bx bx-check-circle text-info me-1"></i> Acceso por URL personalizada</li>
                        <li class="mb-2"><i class="bx bx-check-circle text-info me-1"></i> Facturación y control SaaS</li>
                    </ul>
                </aside>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        const companyNameInput = document.getElementById('vxRegisterCompanyName');
        const slugInput = document.getElementById('vxRegisterSlug');
        const slugPreview = document.getElementById('vxRegisterSlugPreview');
        const planSelect = document.getElementById('vxRegisterPlan');
        const planName = document.getElementById('vxRegisterPlanName');
        const planPrice = document.getElementById('vxRegisterPlanPrice');

        const sanitizeSlug = (value) => String(value || '')
            .toLowerCase()
            .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');

        const updateSlugPreview = () => {
            if (!slugInput || !slugPreview) return;
            const source = companyNameInput ? companyNameInput.value : slugInput.value;
            const sanitized = sanitizeSlug(source);
            slugInput.value = sanitized;
            slugPreview.textContent = sanitized !== '' ? sanitized : 'miempresa';
        };

        const updatePlanSummary = () => {
            if (!planSelect || !planName || !planPrice) return;
            const option = planSelect.options[planSelect.selectedIndex];
            const currentName = option ? String(option.dataset.planName || '') : '';
            const currentPrice = option ? String(option.dataset.planPrice || '') : '';
            planName.textContent = currentName !== '' ? currentName : 'Selecciona un plan';
            planPrice.textContent = currentPrice !== '' ? currentPrice : 'Sin plan seleccionado';
        };

        companyNameInput?.addEventListener('input', updateSlugPreview);
        companyNameInput?.addEventListener('change', updateSlugPreview);
        planSelect?.addEventListener('change', updatePlanSummary);

        updateSlugPreview();
        updatePlanSummary();
    })();
</script>
@endsection
