<?php
/**
 * Template onboarding — Tunnels B2C et B2B distincts.
 * B2C : Nom Entreprise, Ville, Pays, Quartier, Métier, Email Pro.
 * B2B : Nom Agence, Nom Contact, Email, Volume de fiches.
 * Données stockées en table wor1515_avi_pre_inscription (liée au PID après création profil).
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
$is_b2b_onboarding_page = function_exists( 'is_page_template' ) && is_page_template( 'template-b2b-onboarding.php' );
$lang = function_exists( 'avi_login_current_lang' ) ? avi_login_current_lang() : 'fr';
$lang = in_array( $lang, array( 'fr', 'en', 'es' ), true ) ? $lang : 'fr';
$i18n = array(
	'fr' => array(
		'title' => 'Inscription Agence',
		'tabs_label' => "Type d'inscription",
		'b2c_tab' => 'Professionnel (B2C)',
		'b2b_tab' => 'Agence (B2B)',
		'business_name' => "Nom de l'entreprise",
		'city' => 'Ville',
		'country' => 'Pays',
		'neighborhood' => 'Quartier',
		'category' => 'Métier',
		'pro_email' => 'Email professionnel',
		'submit' => 'Continuer vers mon Dashboard Agence',
		'agency_name' => "Nom de l'agence",
		'contact_name' => 'Nom du contact',
		'email' => 'Email',
		'password' => 'Mot de passe',
		'password_confirm' => 'Confirmer le mot de passe',
		'password_mismatch' => 'Les mots de passe ne correspondent pas.',
		'volume' => 'Volume de fiches (nombre)',
		'loading' => 'Enregistrement en cours…',
		'generic_error' => 'Une erreur est survenue.',
		'network_error' => 'Erreur réseau.',
		'save_error' => 'Erreur : réponse serveur incomplète ou réseau indisponible.',
	),
	'en' => array(
		'title' => 'Agency Signup',
		'tabs_label' => 'Signup type',
		'b2c_tab' => 'Professional (B2C)',
		'b2b_tab' => 'Agency (B2B)',
		'business_name' => 'Business name',
		'city' => 'City',
		'country' => 'Country',
		'neighborhood' => 'Neighborhood',
		'category' => 'Business category',
		'pro_email' => 'Business email',
		'submit' => 'Continue to my Agency Dashboard',
		'agency_name' => 'Agency name',
		'contact_name' => 'Contact name',
		'email' => 'Email',
		'password' => 'Password',
		'password_confirm' => 'Confirm password',
		'password_mismatch' => 'Passwords do not match.',
		'volume' => 'Number of listings',
		'loading' => 'Saving…',
		'generic_error' => 'An error occurred.',
		'network_error' => 'Network error.',
		'save_error' => 'Unable to save registration.',
	),
	'es' => array(
		'title' => 'Registro de Agencia',
		'tabs_label' => 'Tipo de registro',
		'b2c_tab' => 'Profesional (B2C)',
		'b2b_tab' => 'Agencia (B2B)',
		'business_name' => 'Nombre del negocio',
		'city' => 'Ciudad',
		'country' => 'País',
		'neighborhood' => 'Barrio',
		'category' => 'Actividad',
		'pro_email' => 'Correo profesional',
		'submit' => 'Continuar hacia mi Dashboard de Agencia',
		'agency_name' => 'Nombre de la agencia',
		'contact_name' => 'Nombre del contacto',
		'email' => 'Correo electrónico',
		'password' => 'Contraseña',
		'volume' => 'Volumen de fichas (cantidad)',
		'password_confirm' => 'Confirmar contraseña',
		'password_mismatch' => 'Las contraseñas no coinciden.',
		'loading' => 'Guardando…',
		'generic_error' => 'Ocurrió un error.',
		'network_error' => 'Error de red.',
		'save_error' => 'Error: respuesta del servidor incompleta o red no disponible.',
	),
);
$t = $i18n[ $lang ];
$onboarding_save_url = function_exists( 'rest_url' ) ? rest_url( 'avision/v1/onboarding-save' ) : home_url( '/wp-json/avision/v1/onboarding-save' );
?>
<div class="avision-onboarding-wrap" data-onboarding-save-url="<?php echo esc_attr( $onboarding_save_url ); ?>">
	<div class="avision-onboarding-inner" style="max-width: 620px; margin: 0 auto;">
		<?php if ( ! $is_b2b_onboarding_page ) : ?>
			<h1 class="avision-onboarding-title"><?php echo esc_html( $t['title'] ); ?></h1>
		<?php endif; ?>

		<div class="avision-onboarding-tabs" role="tablist" aria-label="<?php echo esc_attr( $t['tabs_label'] ); ?>">
			<button type="button" class="avision-onboarding-tab active" role="tab" aria-selected="true" data-tunnel="b2c" id="tab-b2c"><?php echo esc_html( $t['b2c_tab'] ); ?></button>
			<button type="button" class="avision-onboarding-tab" role="tab" aria-selected="false" data-tunnel="b2b" id="tab-b2b"><?php echo esc_html( $t['b2b_tab'] ); ?></button>
		</div>

		<!-- Tunnel B2C -->
		<form id="avision-onboarding-form-b2c" class="avision-onboarding-form" data-type="b2c" aria-labelledby="tab-b2c" style="display: block;">
			<input type="hidden" name="type" value="b2c" />
			<label class="avision-onboarding-label" for="b2c_business_name"><?php echo esc_html( $t['business_name'] ); ?> <span class="required">*</span></label>
			<input type="text" id="b2c_business_name" name="business_name" class="avision-onboarding-input" required placeholder="Ex: Cabinet Dupont" />

			<label class="avision-onboarding-label" for="b2c_city"><?php echo esc_html( $t['city'] ); ?> <span class="required">*</span></label>
			<input type="text" id="b2c_city" name="city" class="avision-onboarding-input" required placeholder="Ex: Lyon" />

			<label class="avision-onboarding-label" for="b2c_country"><?php echo esc_html( $t['country'] ); ?> <span class="required">*</span></label>
			<select id="b2c_country" name="country" class="avision-onboarding-input avision-onboarding-select" required>
				<option value="FR">France</option>
				<option value="GB">Royaume-Uni</option>
				<option value="US">États-Unis</option>
				<option value="ES">Espagne</option>
			</select>

			<label class="avision-onboarding-label" for="b2c_neighborhood"><?php echo esc_html( $t['neighborhood'] ); ?> <span class="required">*</span></label>
			<input type="text" id="b2c_neighborhood" name="neighborhood" class="avision-onboarding-input" required placeholder="Ex: 3e arr., Presqu'île" />

			<label class="avision-onboarding-label" for="b2c_category"><?php echo esc_html( $t['category'] ); ?> <span class="required">*</span></label>
			<input type="text" id="b2c_category" name="category" class="avision-onboarding-input" required placeholder="Ex: Dentiste, Plombier, Avocat..." />

			<label class="avision-onboarding-label" for="b2c_email"><?php echo esc_html( $t['pro_email'] ); ?> <span class="required">*</span></label>
			<input type="email" id="b2c_email" name="email" class="avision-onboarding-input" required placeholder="contact@votre-entreprise.com" />

			<label class="avision-onboarding-label" for="b2c_password"><?php echo esc_html( $t['password'] ); ?> <span class="required">*</span></label>
			<input type="password" id="b2c_password" name="password" class="avision-onboarding-input avi-b2c-password" required minlength="8" placeholder="********" autocomplete="new-password" />

			<label class="avision-onboarding-label" for="b2c_password_confirm"><?php echo esc_html( $t['password_confirm'] ); ?> <span class="required">*</span></label>
			<input type="password" id="b2c_password_confirm" name="password_confirm" class="avision-onboarding-input avi-b2c-password-confirm" required minlength="8" placeholder="********" autocomplete="new-password" onpaste="return false;" />

			<button type="submit" class="avision-onboarding-submit"><?php echo esc_html( $t['submit'] ); ?></button>
		</form>

		<!-- Tunnel B2B -->
		<form id="avision-onboarding-form-b2b" class="avision-onboarding-form" data-type="b2b" aria-labelledby="tab-b2b" style="display: none;">
			<input type="hidden" name="type" value="b2b" />
			<label class="avision-onboarding-label" for="b2b_agency_name"><?php echo esc_html( $t['agency_name'] ); ?> <span class="required">*</span></label>
			<input type="text" id="b2b_agency_name" name="agency_name" class="avision-onboarding-input" required placeholder="Ex: Agence Local Pro" />

			<label class="avision-onboarding-label" for="b2b_contact_name"><?php echo esc_html( $t['contact_name'] ); ?> <span class="required">*</span></label>
			<input type="text" id="b2b_contact_name" name="contact_name" class="avision-onboarding-input" required placeholder="Ex: Jean Martin" />

			<label class="avision-onboarding-label" for="b2b_email"><?php echo esc_html( $t['email'] ); ?> <span class="required">*</span></label>
			<input type="email" id="b2b_email" name="email" class="avision-onboarding-input" required placeholder="contact@agence.com" />

			<label class="avision-onboarding-label" for="b2b_password"><?php echo esc_html( $t['password'] ); ?> <span class="required">*</span></label>
			<input type="password" id="b2b_password" name="password" class="avision-onboarding-input avi-b2b-password" required minlength="8" placeholder="********" autocomplete="new-password" />

			<label class="avision-onboarding-label" for="b2b_password_confirm"><?php echo esc_html( $t['password_confirm'] ); ?> <span class="required">*</span></label>
			<input type="password" id="b2b_password_confirm" name="password_confirm" class="avision-onboarding-input avi-b2b-password-confirm" required minlength="8" placeholder="********" autocomplete="new-password" onpaste="return false;" />

			<label class="avision-onboarding-label" for="b2b_volume_fiches"><?php echo esc_html( $t['volume'] ); ?> <span class="required">*</span></label>
			<input type="number" id="b2b_volume_fiches" name="volume_fiches" class="avision-onboarding-input" required min="1" placeholder="Ex: 50" />

			<button type="submit" class="avision-onboarding-submit"><?php echo esc_html( $t['submit'] ); ?></button>
		</form>

		<div id="avision-onboarding-loading" class="avision-onboarding-loading" style="display: none;">
			<p><?php echo esc_html( $t['loading'] ); ?></p>
		</div>
		<div id="avision-onboarding-error" class="avision-onboarding-error" style="display: none;" role="alert"></div>
	</div>
</div>

<style>
.avision-onboarding-wrap { padding: 1.5rem; font-family: sans-serif; }
.avision-onboarding-title { margin-bottom: 0.25rem; font-size: 1.5rem; }
.avision-onboarding-subtitle { color: #555; margin-bottom: 1.25rem; }
.avision-onboarding-tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.avision-onboarding-tab { padding: 0.6rem 1rem; border: 1px solid #ccc; background: #f5f5f5; cursor: pointer; border-radius: 4px; }
.avision-onboarding-tab.active { background: #1a1a1a; color: #fff; border-color: #1a1a1a; }
.avision-onboarding-form label { display: block; margin-top: 0.75rem; margin-bottom: 0.25rem; font-weight: 600; }
.avision-onboarding-form .required { color: #c00; }
.avision-onboarding-input { width: 100%; padding: 0.5rem 0.75rem; margin-bottom: 0.5rem; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
.avision-onboarding-select { min-height: 2.5rem; }
.avision-onboarding-submit { margin-top: 1.25rem; padding: 0.65rem 1.5rem; background: #1a1a1a; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-weight: 600; }
.avision-onboarding-submit:hover { background: #333; }
.avision-onboarding-loading { margin-top: 1rem; color: #666; }
.avision-onboarding-error { margin-top: 1rem; padding: 0.75rem; background: #fee; color: #c00; border-radius: 4px; }
</style>

<script>
(function() {
	var wrap = document.querySelector('.avision-onboarding-wrap');
	if (!wrap) return;

	var tabB2c = wrap.querySelector('#tab-b2c');
	var tabB2b = wrap.querySelector('#tab-b2b');
	var formB2c = wrap.querySelector('#avision-onboarding-form-b2c');
	var formB2b = wrap.querySelector('#avision-onboarding-form-b2b');
	var loadingEl = wrap.querySelector('#avision-onboarding-loading');
	var errorEl = wrap.querySelector('#avision-onboarding-error');
	var saveUrl = wrap.dataset.onboardingSaveUrl || (window.location.origin + '/wp-json/avision/v1/onboarding-save');
	var pwdEl = formB2b ? formB2b.querySelector('#b2b_password') : null;
	var pwdConfirmEl = formB2b ? formB2b.querySelector('#b2b_password_confirm') : null;
	var pwdB2cEl = formB2c ? formB2c.querySelector('#b2c_password') : null;
	var pwdB2cConfirmEl = formB2c ? formB2c.querySelector('#b2c_password_confirm') : null;
	var mismatchMsg = <?php echo wp_json_encode( $t['password_mismatch'] ); ?>;

	function updateB2bPasswordMatchVisual() {
		if (!pwdEl || !pwdConfirmEl) return;
		pwdEl.classList.remove('avi-password-match', 'avi-password-mismatch');
		pwdConfirmEl.classList.remove('avi-password-match', 'avi-password-mismatch');
		var a = pwdEl.value;
		var b = pwdConfirmEl.value;
		if (b.length === 0) return;
		if (a.length >= 8 && b.length >= 8 && a === b) {
			pwdEl.classList.add('avi-password-match');
			pwdConfirmEl.classList.add('avi-password-match');
		} else if (b.length > 0) {
			pwdConfirmEl.classList.add('avi-password-mismatch');
			if (a.length > 0 && a !== b) pwdEl.classList.add('avi-password-mismatch');
		}
	}
	function updateB2cPasswordMatchVisual() {
		if (!pwdB2cEl || !pwdB2cConfirmEl) return;
		pwdB2cEl.classList.remove('avi-password-match', 'avi-password-mismatch');
		pwdB2cConfirmEl.classList.remove('avi-password-match', 'avi-password-mismatch');
		var a = pwdB2cEl.value;
		var b = pwdB2cConfirmEl.value;
		if (b.length === 0) return;
		if (a.length >= 8 && b.length >= 8 && a === b) {
			pwdB2cEl.classList.add('avi-password-match');
			pwdB2cConfirmEl.classList.add('avi-password-match');
		} else if (b.length > 0) {
			pwdB2cConfirmEl.classList.add('avi-password-mismatch');
			if (a.length > 0 && a !== b) pwdB2cEl.classList.add('avi-password-mismatch');
		}
	}
	if (pwdEl && pwdConfirmEl) {
		pwdEl.addEventListener('input', updateB2bPasswordMatchVisual);
		pwdConfirmEl.addEventListener('input', updateB2bPasswordMatchVisual);
	}
	if (pwdB2cEl && pwdB2cConfirmEl) {
		pwdB2cEl.addEventListener('input', updateB2cPasswordMatchVisual);
		pwdB2cConfirmEl.addEventListener('input', updateB2cPasswordMatchVisual);
	}

	function showError(msg) {
		errorEl.textContent = msg || <?php echo wp_json_encode( $t['generic_error'] ); ?>;
		errorEl.style.display = 'block';
	}
	function hideError() {
		errorEl.style.display = 'none';
	}

	// Tabs
	function setActiveTunnel(type) {
		tabB2c.classList.toggle('active', type === 'b2c');
		tabB2b.classList.toggle('active', type === 'b2b');
		tabB2c.setAttribute('aria-selected', type === 'b2c' ? 'true' : 'false');
		tabB2b.setAttribute('aria-selected', type === 'b2b' ? 'true' : 'false');
		formB2c.style.display = type === 'b2c' ? 'block' : 'none';
		formB2b.style.display = type === 'b2b' ? 'block' : 'none';
		hideError();
	}
	tabB2c.addEventListener('click', function() { setActiveTunnel('b2c'); });
	tabB2b.addEventListener('click', function() { setActiveTunnel('b2b'); });

	function submitForm(form) {
		hideError();
		var type = form.dataset.type;
		var payload = { type: type };
		var formData = new FormData(form);
		for (var p of formData.entries()) {
			if (p[0] === 'type') continue;
			if (p[1] !== undefined && p[1] !== '') payload[p[0]] = p[1];
		}
		if (type === 'b2b' && payload.volume_fiches !== undefined) {
			payload.volume_fiches = parseInt(payload.volume_fiches, 10) || null;
		}
		if (type === 'b2c') {
			var p1 = form.querySelector('[name="password"]');
			var p2 = form.querySelector('[name="password_confirm"]');
			if (p1 && p2 && p1.value !== p2.value) {
				showError(mismatchMsg);
				return;
			}
		}

		loadingEl.style.display = 'block';
		form.querySelector('button[type="submit"]').disabled = true;

		fetch(saveUrl, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify(payload)
		})
		.then(function(r) { return r.json().then(function(d) { return { ok: r.ok, data: d }; }); })
		.then(function(res) {
			loadingEl.style.display = 'none';
			form.querySelector('button[type="submit"]').disabled = false;
			if (res.ok && res.data && res.data.success && res.data.token) {
				// 1) Sans clé Stripe : redirect dashboard (mode test).
				if (res.data.redirect) {
					window.location.href = res.data.redirect;
					return;
				}
				// 2) Stripe : POST stripe-create-checkout-session puis redirection Hosted Checkout.
				if (res.data.stripe_checkout && res.data.checkout_create_url && res.data.pre_token) {
					loadingEl.style.display = 'block';
					form.querySelector('button[type="submit"]').disabled = true;
					fetch(res.data.checkout_create_url, {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({ pre_token: res.data.pre_token })
					})
						.then(function(r) { return r.json().then(function(d) { return { ok: r.ok, data: d }; }); })
						.then(function(sr) {
							loadingEl.style.display = 'none';
							form.querySelector('button[type="submit"]').disabled = false;
							if (sr.ok && sr.data && sr.data.success && sr.data.url) {
								window.location.href = sr.data.url;
								return;
							}
							var err = (sr.data && sr.data.error) ? String(sr.data.error) : 'stripe_error';
							showError(err);
						})
						.catch(function() {
							loadingEl.style.display = 'none';
							form.querySelector('button[type="submit"]').disabled = false;
							showError(<?php echo wp_json_encode( $t['network_error'] ); ?>);
						});
					return;
				}
				window.location.href = '/demo-dashboard?pre=' + encodeURIComponent(res.data.token);
				return;
			}
			var errText = (res.data && (res.data.error || res.data.message)) || <?php echo wp_json_encode( $t['save_error'] ); ?>;
			showError(errText);
		})
		.catch(function() {
			loadingEl.style.display = 'none';
			form.querySelector('button[type="submit"]').disabled = false;
			showError(<?php echo wp_json_encode( $t['network_error'] ); ?>);
		});
	}

	formB2c.addEventListener('submit', function(e) { e.preventDefault(); submitForm(formB2c); });
	formB2b.addEventListener('submit', function(e) { e.preventDefault(); submitForm(formB2b); });
})();
</script>
