<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Template pour le shortcode formulaire d'audit (avision_local_audit_form / avision_audit_london_test).
 * Pré-inscription B2C uniquement (wor1515_avi_pre_inscription) — pas de création de compte avant paiement.
 * Mot de passe hashé côté serveur dans la colonne data (password_hash).
 */
$onboarding_save_url = function_exists( 'rest_url' ) ? rest_url( 'avision/v1/onboarding-save' ) : ( home_url( '/wp-json/avision/v1/onboarding-save' ) );
?>
<!-- AVI: formulaire shortcode [avision_local_audit_form] - templates/shortcode-local-audit-form.php -->
<div class="avision-local-audit-form-wrap" data-onboarding-save-url="<?php echo esc_attr( $onboarding_save_url ); ?>" data-wp-rest-nonce="<?php echo esc_attr( wp_create_nonce( 'wp_rest' ) ); ?>">
    <div class="av-form-container" style="max-width:600px; margin:0 auto;">
        <div class="av-lang-switcher" id="avision-audit-lang-switcher" style="text-align:center; margin-bottom:20px;">
            <button type="button" class="av-lang-btn active" data-lang="en" aria-label="English">🇺🇸</button>
            <button type="button" class="av-lang-btn" data-lang="fr" aria-label="Français">🇫🇷</button>
            <button type="button" class="av-lang-btn" data-lang="es" aria-label="Español">🇪🇸</button>
        </div>
        <div class="av-form-card">
            <h2 class="av-title" data-i18n="title">Local Visibility Diagnosis</h2>
            <p class="av-subtitle" data-i18n="subtitle">Discover what is blocking your inbound calls in 60 seconds.</p>
            <div id="avision-audit-loading" class="av-loading" style="display:none;">
                <div class="av-spinner"></div>
                <p class="av-loading-text" data-i18n="generating">Avi is analyzing your profile...</p>
                <p class="av-loading-sub" data-i18n="please_wait">I am comparing your positioning with competitors...</p>
            </div>
            <form method="post" id="avision-audit-form" class="av-form" style="text-align:left;" autocomplete="off">
                <label class="av-label" data-i18n="business_name">Business Name (exactly as on your Google Profile)</label>
                <input type="text" name="avision_business_name" class="av-input" required data-i18n-placeholder="business_placeholder" placeholder="Ex: Smith Dental Clinic - NYC">
                <label class="av-label" data-i18n="city">City</label>
                <input type="text" name="avision_city" class="av-input" required data-i18n-placeholder="city_placeholder" placeholder="Ex: New York">
                <label class="av-label" data-i18n="country">Country</label>
                <select name="avision_country" class="av-input av-select" required style="display:block; width:100%; min-height:2.5em; margin-bottom:1em;">
                    <option value="FR">France</option>
                    <option value="GB">United Kingdom</option>
                    <option value="US">USA</option>
                    <option value="ES">Spain</option>
                </select>
                <label class="av-label" data-i18n="neighborhood">Neighborhood / District</label>
                <input type="text" name="avision_neighborhood" class="av-input" required data-i18n-placeholder="neighborhood_placeholder" placeholder="Ex: Manhattan, Downtown">
                <?php
                $avi_category_use_i18n_attrs = true;
                $avi_category_label_class    = 'av-label';
                $avi_category_input_class    = 'av-input av-select av-form-select';
                $avi_category_lang           = function_exists( 'avision_detect_language_by_ip' ) ? avision_detect_language_by_ip() : 'en';
                include __DIR__ . '/partials/local-audit-category-select.php';
                ?>
                <label class="av-label" data-i18n="email_label">Your Professional Email (to receive the report)</label>
                <input type="email" name="avision_email" class="av-input" required data-i18n-placeholder="email_placeholder" placeholder="contact@company.com" autocomplete="email">
                <label class="av-label" data-i18n="password_label">Password (min. 8 characters)</label>
                <input type="password" name="avision_password" id="avision_audit_password" class="av-input" required minlength="8" placeholder="********" autocomplete="new-password">
                <label class="av-label" data-i18n="password_confirm_label">Confirm password</label>
                <input type="password" name="avision_password_confirm" id="avision_audit_password_confirm" class="av-input" required minlength="8" placeholder="********" autocomplete="new-password" onpaste="return false;">
                <?php
                $avi_terms_mode = 'standard';
                include __DIR__ . '/partials/avi-terms-checkbox.php';
                ?>
                <button type="submit" class="av-submit-btn" data-i18n="submit_btn">Start Free Analysis →</button>
                <div class="av-trust-box">
                    <span class="av-trust-title" data-i18n="trust_title">It's free and no obligation.</span>
                    <ul class="av-trust-list">
                        <li>✅ <span data-i18n="trust_1">Real-time analysis (no outdated databases).</span></li>
                        <li>🔒 <span data-i18n="trust_2">Your data remains 100% confidential.</span></li>
                        <li>📧 <span data-i18n="trust_3">No spam, just your report.</span></li>
                    </ul>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
(function() {
    // ANTI-RÉGRESSION — DOMContentLoaded obligatoire :
    // Sans lui, wrap = null si script exécuté avant le DOM
    // → if (!wrap) return → listener jamais attaché → soumission native
    // → neighborhood/city/category jamais envoyés à onboarding-save.
    // NE JAMAIS exécuter ce script sans DOMContentLoaded.
    function init() {
    var wrap = document.querySelector('.avision-local-audit-form-wrap');
    if (!wrap) return;
    var translations = {
        en: { title: 'Local Visibility Diagnosis', subtitle: 'Discover what is blocking your inbound calls in 60 seconds.', business_name: 'Business Name (exactly as on your Google Profile)', business_placeholder: 'Ex: Smith Dental Clinic - NYC', city: 'City', city_placeholder: 'Ex: New York', country: 'Country', neighborhood: 'Neighborhood / District', neighborhood_placeholder: 'Ex: Manhattan, Downtown', category_select_label: 'Your business type', category_search_placeholder: 'Search business type...', category_select_placeholder: '— Select your business type —', email_label: 'Your Professional Email (to receive the report)', email_placeholder: 'contact@company.com', password_label: 'Password (min. 8 characters)', password_confirm_label: 'Confirm password', password_mismatch: 'Passwords do not match.', submit_btn: 'Start Free Analysis →', generating: 'Avi is analyzing your profile...', please_wait: 'I am comparing your positioning with competitors...', trust_title: "It's free and no obligation.", trust_1: 'Real-time analysis (no outdated databases).', trust_2: 'Your data remains 100% confidential.', trust_3: 'No spam, just your report.' },
        fr: { title: 'Diagnostic de Visibilité Locale', subtitle: 'Découvrez ce qui bloque vos appels entrants en 60 secondes.', business_name: "Nom de votre entreprise (tel qu'écrit sur votre fiche Google)", business_placeholder: 'Ex: Cabinet Dentaire Dupont - Lyon Centre', city: 'Ville', city_placeholder: 'Ex: Lyon', country: 'Pays', neighborhood: 'Quartier / Arrondissement', neighborhood_placeholder: "Ex: 3e arr., Presqu'île", category_select_label: "Votre type d'activité", category_search_placeholder: "Rechercher un type d'activité...", category_select_placeholder: '— Sélectionnez votre activité —', email_label: 'Votre Email Pro (pour recevoir le rapport)', email_placeholder: 'contact@votre-entreprise.com', password_label: 'Mot de passe (min. 8 caractères)', password_confirm_label: 'Confirmer le mot de passe', password_mismatch: 'Les mots de passe ne correspondent pas.', submit_btn: "Lancer l'analyse gratuite →", generating: 'Avi analyse votre fiche...', please_wait: 'Je compare votre positionnement avec vos concurrents...', trust_title: "C'est gratuit et sans engagement.", trust_1: 'Analyse en temps réel (pas de base obsolète).', trust_2: 'Vos données restent confidentielles.', trust_3: 'Pas de spam, juste votre rapport.' },
        es: { title: 'Diagnóstico de Visibilidad Local', subtitle: 'Descubra qué está bloqueando sus llamadas entrantes en 60 segundos.', business_name: 'Nombre del negocio (tal como aparece en su perfil de Google)', business_placeholder: 'Ej: Clínica Dental Pérez - Madrid', city: 'Ciudad', city_placeholder: 'Ej: Madrid', country: 'País', neighborhood: 'Barrio / Distrito', neighborhood_placeholder: 'Ej: Centro, Chamberí', category_select_label: 'Tipo de negocio', category_search_placeholder: 'Buscar tipo de negocio...', category_select_placeholder: '— Seleccione su tipo de negocio —', email_label: 'Tu Email (para recibir el informe)', email_placeholder: 'contacto@empresa.com', password_label: 'Contraseña (mín. 8 caracteres)', password_confirm_label: 'Confirmar contraseña', password_mismatch: 'Las contraseñas no coinciden.', submit_btn: 'Iniciar Análisis Gratuito →', generating: 'Avi está analizando su perfil...', please_wait: 'Estoy comparando su posicionamiento con la competencia...', trust_title: 'Es gratis y sin compromiso.', trust_1: 'Análisis en tiempo real (sin bases obsoletas).', trust_2: 'Sus datos permanecen confidenciales.', trust_3: 'Sin spam, solo su informe.' }
    };
    var currentLang = 'en';
    function setLang(lang) {
        currentLang = lang;
        var t = translations[lang];
        wrap.querySelectorAll('[data-i18n]').forEach(function(el) { var k = el.getAttribute('data-i18n'); if (t[k]) el.textContent = t[k]; });
        wrap.querySelectorAll('[data-i18n-placeholder]').forEach(function(el) { var k = el.getAttribute('data-i18n-placeholder'); if (t[k]) el.placeholder = t[k]; });
        var catSel = wrap.querySelector('#avision_category');
        if (catSel && t.category_select_placeholder) {
            var phOpt = catSel.querySelector('option[value=""]');
            if (phOpt) phOpt.textContent = t.category_select_placeholder;
        }
        wrap.querySelectorAll('.av-lang-btn').forEach(function(btn) { btn.classList.toggle('active', btn.dataset.lang === lang); });
        try { localStorage.setItem('avision_lang', lang); } catch(e) {}
    }
    wrap.querySelectorAll('.av-lang-btn').forEach(function(btn) {
        btn.addEventListener('click', function() { setLang(btn.dataset.lang); });
    });
    var urlLang = (typeof URLSearchParams !== 'undefined' && new URLSearchParams(window.location.search).get('lang')) || (typeof URLSearchParams !== 'undefined' && new URLSearchParams(window.location.search).get('avision_lang'));
    var savedLang = (typeof localStorage !== 'undefined' && localStorage.getItem('avision_lang')) || '';
    var lang = (urlLang || savedLang || 'en');
    if (['en','fr','es'].indexOf(lang) === -1) lang = 'en';
    setLang(lang);
    function aviFilterCategorySelect(root) {
        var search = root.querySelector('#avision_category_search');
        var sel = root.querySelector('#avision_category');
        if (!search || !sel) return;
        search.addEventListener('input', function() {
            var q = search.value.trim().toLowerCase();
            sel.querySelectorAll('optgroup').forEach(function(og) {
                var visible = 0;
                og.querySelectorAll('option').forEach(function(opt) {
                    if (!opt.value) return;
                    var match = !q || opt.textContent.toLowerCase().indexOf(q) !== -1;
                    opt.hidden = !match;
                    opt.disabled = !match;
                    if (match) visible++;
                });
                og.hidden = visible === 0;
                og.disabled = visible === 0;
            });
        });
    }
    aviFilterCategorySelect(wrap);
    var form = wrap.querySelector('#avision-audit-form');
    var loadingEl = wrap.querySelector('#avision-audit-loading');
    var saveUrl = wrap.dataset.onboardingSaveUrl || (window.location.origin + '/wp-json/avision/v1/onboarding-save');
    if (form && loadingEl) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            var company = (form.querySelector('input[name="avision_business_name"]') || {}).value.trim();
            var city = (form.querySelector('input[name="avision_city"]') || {}).value.trim();
            var country = (form.querySelector('select[name="avision_country"]') || {}).value || 'FR';
            if (typeof country === 'string') country = country.trim() || 'FR';
            var neighborhood = (form.querySelector('input[name="avision_neighborhood"]') || {}).value.trim();
            var category = (form.querySelector('select[name="avision_category"]') || {}).value.trim();
            var email = (form.querySelector('input[name="avision_email"]') || {}).value.trim();
            var pwd = (form.querySelector('#avision_audit_password') || {}).value || '';
            var pwd2 = (form.querySelector('#avision_audit_password_confirm') || {}).value || '';
            var t = translations[currentLang] || translations.en;
            if (!neighborhood) {
                alert(currentLang === 'fr' ? 'Le quartier / arrondissement est obligatoire.' : currentLang === 'es' ? 'El barrio / distrito es obligatorio.' : 'Neighborhood / District is required.');
                return;
            }
            if (pwd !== pwd2) {
                alert(t.password_mismatch || 'Passwords do not match.');
                return;
            }
            if (pwd.length < 8) {
                alert(currentLang === 'fr' ? 'Le mot de passe doit contenir au moins 8 caractères.' : currentLang === 'es' ? 'La contraseña debe tener al menos 8 caracteres.' : 'Password must be at least 8 characters.');
                return;
            }
            function showError(msg) { alert(msg); }
            if (!document.getElementById('avi_accept_terms') || !document.getElementById('avi_accept_terms').checked) {
                showError(currentLang === 'fr' ? 'Veuillez accepter les CGU pour continuer.' : currentLang === 'es' ? 'Por favor acepta los Términos y Condiciones para continuar.' : 'Please accept the Terms & Conditions to continue.');
                return;
            }
            var btn = form.querySelector('button[type="submit"]');
            if (btn) { btn.disabled = true; btn.style.opacity = '0.7'; btn.textContent = currentLang === 'fr' ? 'Enregistrement...' : currentLang === 'es' ? 'Guardando...' : 'Saving...'; }
            form.style.display = 'none';
            loadingEl.style.display = 'block';
            var score = Math.floor(Math.random() * 30) + 25;
            var payload = {
                type: 'b2c',
                email: email,
                business_name: company,
                city: city,
                country: country,
                neighborhood: neighborhood,
                category: category,
                password: pwd,
                password_confirm: pwd2,
                language: currentLang,
                score: score
            };
            fetch(saveUrl, { method: 'POST', headers: aviShortcodeJsonHeaders(), credentials: 'include', body: JSON.stringify(payload) })
                .then(function(r) { return r.json().then(function(d) { return { ok: r.ok, data: d }; }); })
                .then(function(res) {
                    if (res.ok && res.data && res.data.success && res.data.token) {
                        if (res.data.redirect) {
                            setTimeout(function() { window.location.href = res.data.redirect; }, 800);
                            return;
                        }
                        if (res.data.stripe_checkout && res.data.checkout_create_url && res.data.pre_token) {
                            var checkoutStripeBody = { pre_token: res.data.pre_token };
                            var spStripe = new URLSearchParams(window.location.search || '');
                            checkoutStripeBody.lang = spStripe.get('lang') || (document.documentElement && document.documentElement.lang) || currentLang || 'en';
                            if (spStripe.has('country')) {
                                checkoutStripeBody.country = spStripe.get('country');
                            } else if (country) {
                                checkoutStripeBody.country = country;
                            }
                            if (company) checkoutStripeBody.business_name = company;
                            if (city) checkoutStripeBody.city = city;
                            if (neighborhood) checkoutStripeBody.neighborhood = neighborhood;
                            if (category) checkoutStripeBody.category = category;
                            if (email && String(email).indexOf('@') !== -1) checkoutStripeBody.email = String(email).trim();
                            var stripeScDefaults = { lang: 'en', country: '', business_name: '', city: '', neighborhood: '', category: '', email: '' };
                            var bodyData = Object.assign({}, stripeScDefaults, checkoutStripeBody);
                            console.log('Payload Stripe:', bodyData);
                            console.log('[STRIPE PAYLOAD DEBUG]', JSON.stringify(bodyData));
                            fetch(res.data.checkout_create_url, {
                                method: 'POST',
                                headers: aviShortcodeJsonHeaders(),
                                credentials: 'include',
                                body: JSON.stringify(bodyData)
                            })
                                .then(function(r) { return r.json().then(function(d) { return { ok: r.ok, data: d }; }); })
                                .then(function(sr) {
                                    if (sr.ok && sr.data && sr.data.success && sr.data.url) {
                                        window.location.href = sr.data.url;
                                        return;
                                    }
                                    loadingEl.style.display = 'none';
                                    form.style.display = 'block';
                                    if (btn) { btn.disabled = false; btn.style.opacity = '1'; btn.textContent = (translations[currentLang] && translations[currentLang].submit_btn) ? translations[currentLang].submit_btn : 'OK'; }
                                    alert((sr.data && sr.data.error) ? String(sr.data.error) : 'Stripe error');
                                })
                                .catch(function() {
                                    loadingEl.style.display = 'none';
                                    form.style.display = 'block';
                                    if (btn) { btn.disabled = false; btn.style.opacity = '1'; }
                                    alert('Network error');
                                });
                            return;
                        }
                        var params = new URLSearchParams({ company: company, city: city, country: country, neighborhood: neighborhood, category: category, email: email, lang: currentLang, score: score, pre: res.data.token });
                        setTimeout(function() { window.location.href = '/demo-dashboard?' + params.toString(); }, 800);
                        return;
                    }
                    loadingEl.style.display = 'none';
                    form.style.display = 'block';
                    if (btn) { btn.disabled = false; btn.style.opacity = '1'; btn.textContent = (translations[currentLang] && translations[currentLang].submit_btn) ? translations[currentLang].submit_btn : 'OK'; }
                    var err = (res.data && (res.data.message || res.data.error)) ? (res.data.message || res.data.error) : 'Error';
                    alert(err);
                })
                .catch(function() {
                    loadingEl.style.display = 'none';
                    form.style.display = 'block';
                    if (btn) { btn.disabled = false; btn.style.opacity = '1'; }
                    alert('Network error');
                });
        });
    }
    } // fin init
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
</script>
