<?php
$availablePlans = is_array($plans ?? null) ? $plans : [];
$selectedPlanId = (int) old('plan_id', 0);
$selectedPlan = null;
foreach ($availablePlans as $planItem) {
    if ((int) ($planItem['id'] ?? 0) === $selectedPlanId) {
        $selectedPlan = $planItem;
        break;
    }
}

$selectedPlanName = $selectedPlan !== null
    ? (string) ($selectedPlan['nombre'] ?? 'Plan seleccionado')
    : 'Selecciona un plan';
$selectedPlanPrice = $selectedPlan !== null
    ? (money((float) ($selectedPlan['precio_mensual'] ?? 0)) . '/mes')
    : 'Sin plan seleccionado';

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

<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>

                    <?php if (!(bool) ($wompi_configured ?? false)): ?>
                        <div class="alert alert-warning">
                            El checkout de Wompi no está configurado aún. Puedes avanzar con el formulario mientras soporte habilita las llaves.
                        </div>
                    <?php endif; ?>

                    <form action="<?= e(url('registro-empresa')) ?>" method="post" class="vx-register-form" id="vxRegisterForm">
                        <?= csrf_field() ?>

                        <section class="vx-register-section mb-3">
                            <div class="vx-register-section-head">
                                <span class="vx-register-step">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="<?= e(old('nombre', '')) ?>" autocomplete="organization" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Slug acceso</label>
                                    <input
                                        class="form-control"
                                        id="vxRegisterSlug"
                                        name="slug"
                                        placeholder="miempresa"
                                        value="<?= e($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">
                                        URL de acceso: <code><?= e(rtrim(url(''), '/')) ?>/</code><code id="vxRegisterSlugPreview"><?= e($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="<?= e(old('email', '')) ?>" autocomplete="email">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">NIT</label>
                                    <input class="form-control" name="nit" value="<?= e(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="<?= e(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>
                                        <?php foreach ($availablePlans as $plan): ?>
                                            <?php
                                            $planName = (string) ($plan['nombre'] ?? '');
                                            $planPrice = money((float) ($plan['precio_mensual'] ?? 0)) . '/mes';
                                            ?>
                                            <option
                                                value="<?= e((string) $plan['id']) ?>"
                                                data-plan-name="<?= e($planName) ?>"
                                                data-plan-price="<?= e($planPrice) ?>"
                                                <?= $selectedPlanId === (int) $plan['id'] ? 'selected' : '' ?>
                                            >
                                                <?= e($planName) ?> - <?= e($planPrice) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Dirección</label>
                                    <input class="form-control" name="direccion" value="<?= e(old('direccion', '')) ?>" autocomplete="street-address">
                                </div>
                            </div>
                        </section>

                        <section class="vx-register-section">
                            <div class="vx-register-section-head">
                                <span class="vx-register-step">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="<?= e(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="<?= e(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>
                                </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>
                                </div>
                            </div>
                        </section>

                        <div class="d-grid gap-2 d-sm-flex justify-content-sm-between align-items-center mt-4">
                            <a href="<?= e(url('login')) ?>" class="btn btn-outline-secondary vx-register-back">
                                Volver al login
                            </a>
                            <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">
                <aside class="vx-register-aside">
                    <div>
                        <p class="vx-register-kicker 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">
                        <small class="text-muted d-block mb-1">Plan seleccionado</small>
                        <strong id="vxRegisterPlanName"><?= e($selectedPlanName) ?></strong>
                        <div class="vx-register-plan-price" id="vxRegisterPlanPrice"><?= e($selectedPlanPrice) ?></div>
                    </div>

                    <ul class="vx-register-checklist list-unstyled mb-0">
                        <li><i class="bx bx-check-circle"></i> Activación multiempresa</li>
                        <li><i class="bx bx-check-circle"></i> Usuario admin inicial</li>
                        <li><i class="bx bx-check-circle"></i> Acceso por URL personalizada</li>
                        <li><i class="bx bx-check-circle"></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) => {
            const normalized = String(value || '')
                .toLowerCase()
                .replace(/[^a-z0-9]+/g, '-')
                .replace(/^-+|-+$/g, '');
            return normalized;
        };

        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>
