<?php
/**
 * Shortcodes dashboards premium / agence (accès restreint).
 *
 * @package Avision
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** Checkout Stripe (mode test) — Premium B2C ; surcharger via define avant chargement du plugin ou filtre `avi_pricing_url_premium`. */
if ( ! defined( 'AVISION_PRICING_STRIPE_URL_PREMIUM' ) ) {
	define( 'AVISION_PRICING_STRIPE_URL_PREMIUM', 'https://buy.stripe.com/test_00waEYbhr92b0xp8ue83C01' );
}
/** Checkout Stripe (mode test) — Agency B2B ; surcharger via define ou filtre `avi_pricing_url_agency`. */
if ( ! defined( 'AVISION_PRICING_STRIPE_URL_AGENCY' ) ) {
	define( 'AVISION_PRICING_STRIPE_URL_AGENCY', 'https://buy.stripe.com/test_3cI9AUbhr5PZ0xp5i283C00' );
}

/**
 * Nettoie une liste de classes CSS pour attribut HTML class.
 *
 * @param string $raw Chaîne brute (ex. "foo bar_baz").
 * @return string Classes séparées par un espace.
 */
function avision_dashboard_shortcode_sanitize_class_attr( $raw ) {
	$raw = trim( (string) $raw );
	if ( $raw === '' ) {
		return '';
	}
	$parts = preg_split( '/\s+/', $raw, -1, PREG_SPLIT_NO_EMPTY );
	if ( ! is_array( $parts ) ) {
		return '';
	}
	$out = array();
	foreach ( $parts as $p ) {
		$c = function_exists( 'sanitize_html_class' ) ? sanitize_html_class( (string) $p ) : preg_replace( '/[^A-Za-z0-9_-]/', '', (string) $p );
		if ( $c !== '' ) {
			$out[] = $c;
		}
	}
	return implode( ' ', array_unique( $out ) );
}

/**
 * Détecte un compte agence (B2B) à partir des métas utilisateur WordPress.
 *
 * @param int|null $user_id ID utilisateur ou null = utilisateur courant.
 * @return bool
 */
function avision_user_is_agency_account( $user_id = null ) {
	if ( ! function_exists( 'get_user_meta' ) ) {
		return false;
	}
	$uid = $user_id !== null ? (int) $user_id : (int) get_current_user_id();
	if ( $uid <= 0 ) {
		return false;
	}
	$is_agency = false;
	$type      = get_user_meta( $uid, 'avi_user_type', true );
	if ( is_string( $type ) && strtolower( $type ) === 'b2b' ) {
		$is_agency = true;
	}
	$master = get_user_meta( $uid, 'is_agency_master', true );
	if ( $master === '1' || $master === 1 || $master === true ) {
		$is_agency = true;
	}
	$acc = get_user_meta( $uid, 'avi_account_type', true );
	if ( is_string( $acc ) && strtolower( $acc ) === 'agency' ) {
		$is_agency = true;
	}
	/**
	 * Permet d’étendre la détection agence (ex. rôles personnalisés).
	 *
	 * @param bool $is_agency
	 * @param int  $uid
	 */
	return (bool) apply_filters( 'avision_user_is_agency_account', $is_agency, $uid );
}

/**
 * Accès au shortcode cockpit solo (premium / B2C).
 *
 * @return bool
 */
function avision_user_can_access_premium_dashboard_shortcode() {
	if ( ! function_exists( 'is_user_logged_in' ) || ! is_user_logged_in() ) {
		return false;
	}
	if ( function_exists( 'current_user_can' ) && current_user_can( 'administrator' ) ) {
		return true;
	}
	return ! avision_user_is_agency_account();
}

/**
 * Accès shortcode agence : aligné sur avision_user_can_access_agency_dashboard_route() (manage_options ou rôle avi_agency).
 *
 * @return bool
 */
function avision_user_can_access_agency_dashboard_admin_shortcode() {
	if ( function_exists( 'avision_user_can_access_agency_dashboard_route' ) ) {
		return avision_user_can_access_agency_dashboard_route();
	}
	return false;
}

/**
 * Message HTML : connexion requise.
 *
 * @param string $context premium|agency
 * @return string
 */
function avision_dashboard_shortcode_login_notice( $context ) {
	$redirect = '';
	if ( function_exists( 'get_permalink' ) && function_exists( 'get_queried_object_id' ) ) {
		$pid = (int) get_queried_object_id();
		if ( $pid > 0 ) {
			$redirect = get_permalink( $pid );
		}
	}
	if ( $redirect === '' && function_exists( 'home_url' ) ) {
		$redirect = home_url( '/' );
	}
	$login_url = function_exists( 'wp_login_url' ) ? wp_login_url( $redirect ) : '#';
	$label     = ( $context === 'agency' )
		? __( 'Connectez-vous pour accéder au cockpit agence.', 'avision-dashboard' )
		: __( 'Connectez-vous pour accéder au cockpit premium.', 'avision-dashboard' );

	return sprintf(
		'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--denied avision-dashboard-shortcode--%1$s" role="alert"><p>%2$s</p><p><a class="button" href="%3$s">%4$s</a></p></div>',
		esc_attr( $context ),
		esc_html( $label ),
		esc_url( $login_url ),
		esc_html__( 'Connexion', 'avision-dashboard' )
	);
}

/**
 * Message HTML : mauvais type de compte.
 *
 * @param string $expected premium|agency
 * @return string
 */
function avision_dashboard_shortcode_wrong_account_notice( $expected ) {
	if ( $expected === 'agency' ) {
		$text = __( 'Ce tableau de bord est réservé aux comptes agence. Utilisez le cockpit premium si vous êtes en solo.', 'avision-dashboard' );
	} else {
		$text = __( 'Ce tableau de bord est réservé aux comptes solo (premium). Utilisez le cockpit agence si vous gérez plusieurs fiches.', 'avision-dashboard' );
	}
	return sprintf(
		'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--denied" role="alert"><p>%s</p></div>',
		esc_html( $text )
	);
}

/**
 * UUID (PID) du profil SaaS pour un utilisateur WordPress (wor1515_avi_saas_profiles ou préfixe WP).
 *
 * @param int $wp_user_id ID WordPress.
 * @return string UUID normalisé ou chaîne vide.
 */
function avision_get_saas_profile_uuid_for_wp_user( $wp_user_id ) {
	global $wpdb;
	$wp_user_id = (int) $wp_user_id;
	if ( $wp_user_id <= 0 || ! isset( $wpdb ) || ! is_object( $wpdb ) ) {
		return '';
	}

	$table = ( defined( 'AVISION_SAAS_PROFILES_TABLE' ) && is_string( AVISION_SAAS_PROFILES_TABLE ) && AVISION_SAAS_PROFILES_TABLE !== '' )
		? AVISION_SAAS_PROFILES_TABLE
		: 'wor1515_avi_saas_profiles';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
		$table = $wpdb->prefix . 'avi_saas_profiles';
	}
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
		return '';
	}
	if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'uuid' ) ) !== 'uuid' ) {
		return '';
	}

	$order = ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'updated_at' ) ) === 'updated_at' )
		? '`updated_at` DESC'
		: '`id` DESC';

	$uuid = null;

	if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'wp_user_id' ) ) === 'wp_user_id' ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $order whitelist (updated_at DESC | id DESC).
		$uuid = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT uuid FROM `{$table}` WHERE wp_user_id = %d AND uuid IS NOT NULL AND TRIM(uuid) != '' ORDER BY {$order} LIMIT 1",
				$wp_user_id
			)
		);
	}

	if ( ( ! is_string( $uuid ) || ! preg_match( '/^[a-f0-9\-]{32,36}$/i', trim( $uuid ) ) )
		&& $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'email' ) ) === 'email'
		&& function_exists( 'get_userdata' ) && function_exists( 'is_email' ) ) {
		$user = get_userdata( $wp_user_id );
		$mail = ( $user && ! empty( $user->user_email ) && is_email( $user->user_email ) ) ? sanitize_email( $user->user_email ) : '';
		if ( $mail !== '' ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$uuid = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT uuid FROM `{$table}` WHERE email = %s AND uuid IS NOT NULL AND TRIM(uuid) != '' ORDER BY {$order} LIMIT 1",
					$mail
				)
			);
		}
	}

	if ( ( ! is_string( $uuid ) || ! preg_match( '/^[a-f0-9\-]{32,36}$/i', trim( $uuid ) ) )
		&& $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'user_id' ) ) === 'user_id' ) {
		$utbl = ( strpos( $table, 'wor1515_' ) === 0 ) ? 'wor1515_avi_saas_users' : $wpdb->prefix . 'avi_saas_users';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $utbl ) ) !== $utbl ) {
			$utbl = $wpdb->prefix . 'avi_saas_users';
		}
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $utbl ) ) === $utbl
			&& $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$utbl}` LIKE %s", 'email' ) ) === 'email'
			&& function_exists( 'get_userdata' )
			&& function_exists( 'is_email' ) ) {
			$user = get_userdata( $wp_user_id );
			$mail = ( $user && ! empty( $user->user_email ) && is_email( $user->user_email ) ) ? sanitize_email( $user->user_email ) : '';
			if ( $mail !== '' ) {
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				$uuid = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT p.uuid FROM `{$table}` p INNER JOIN `{$utbl}` u ON p.user_id = u.id WHERE u.email = %s AND p.uuid IS NOT NULL AND TRIM(p.uuid) != '' ORDER BY {$order} LIMIT 1",
						$mail
					)
				);
			}
		}
	}

	if ( ! is_string( $uuid ) || ! preg_match( '/^[a-f0-9\-]{32,36}$/i', trim( $uuid ) ) ) {
		return '';
	}

	return strtolower( trim( $uuid ) );
}

/**
 * Chemin du template page premium pour le shortcode (plugin templates/ puis thème).
 *
 * @return string Chemin absolu ou vide.
 */
function avision_resolve_premium_dashboard_shortcode_template() {
	$candidates = array();
	if ( defined( 'AVISION_PATH' ) && is_string( AVISION_PATH ) ) {
		$candidates[] = trailingslashit( AVISION_PATH ) . 'templates/page-premium-dashboard.php';
	}
	if ( function_exists( 'get_stylesheet_directory' ) ) {
		$candidates[] = trailingslashit( get_stylesheet_directory() ) . 'templates/page-premium-dashboard.php';
		$candidates[] = trailingslashit( get_stylesheet_directory() ) . 'page-premium-dashboard.php';
	}
	if ( function_exists( 'get_template_directory' ) ) {
		$candidates[] = trailingslashit( get_template_directory() ) . 'templates/page-premium-dashboard.php';
		$candidates[] = trailingslashit( get_template_directory() ) . 'page-premium-dashboard.php';
	}
	$resolved = '';
	foreach ( $candidates as $path ) {
		if ( is_string( $path ) && $path !== '' && is_readable( $path ) ) {
			$resolved = $path;
			break;
		}
	}
	/**
	 * Chemin du fichier PHP à inclure pour [avision_premium_dashboard] (partial sans document HTML complet).
	 *
	 * @param string $resolved Chemin détecté ou vide.
	 */
	return (string) apply_filters( 'avision_premium_dashboard_shortcode_template_path', $resolved );
}

/**
 * Chemin du template page agence pour le shortcode (plugin templates/ puis thème).
 *
 * @return string Chemin absolu ou vide.
 */
function avision_resolve_agency_dashboard_shortcode_template() {
	$candidates = array();
	if ( defined( 'AVISION_PATH' ) && is_string( AVISION_PATH ) ) {
		$candidates[] = trailingslashit( AVISION_PATH ) . 'templates/page-agency-dashboard.php';
	}
	if ( function_exists( 'get_stylesheet_directory' ) ) {
		$candidates[] = trailingslashit( get_stylesheet_directory() ) . 'templates/page-agency-dashboard.php';
		$candidates[] = trailingslashit( get_stylesheet_directory() ) . 'page-agency-dashboard.php';
	}
	if ( function_exists( 'get_template_directory' ) ) {
		$candidates[] = trailingslashit( get_template_directory() ) . 'templates/page-agency-dashboard.php';
		$candidates[] = trailingslashit( get_template_directory() ) . 'page-agency-dashboard.php';
	}
	$resolved = '';
	foreach ( $candidates as $path ) {
		if ( is_string( $path ) && $path !== '' && is_readable( $path ) ) {
			$resolved = $path;
			break;
		}
	}
	/**
	 * Chemin du fichier PHP à inclure pour [avision_agency_dashboard] (partial sans document HTML complet).
	 *
	 * @param string $resolved Chemin détecté ou vide.
	 */
	return (string) apply_filters( 'avision_agency_dashboard_shortcode_template_path', $resolved );
}

/**
 * Indique si le fichier ressemble à un document HTML complet (inclusion dans une page interdite).
 *
 * @param string $path Chemin fichier.
 * @return bool
 */
function avision_premium_dashboard_template_is_full_document( $path ) {
	if ( ! is_string( $path ) || $path === '' || ! is_readable( $path ) ) {
		return false;
	}
	$max = 524288;
	$len = @filesize( $path );
	if ( is_int( $len ) && $len > 0 && $len < $max ) {
		$max = $len;
	}
	$chunk = @file_get_contents( $path, false, null, 0, $max );
	if ( ! is_string( $chunk ) ) {
		return false;
	}
	return (bool) preg_match( '/<!DOCTYPE\s+html/i', $chunk );
}

/**
 * Shortcode [avision_premium_dashboard].
 *
 * @param array|string $atts Attributs shortcode.
 * @return string
 */
function avision_render_premium_dashboard_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'class' => '',
		),
		$atts,
		'avision_premium_dashboard'
	);

	// Pages pleines : garde + ?pid= gérés par template_redirect (évite boucle si le shortcode est sur la page cible).
	if ( function_exists( 'avision_is_premium_dashboard_query' ) && avision_is_premium_dashboard_query() ) {
		return '';
	}

	if ( ! function_exists( 'is_user_logged_in' ) || ! is_user_logged_in() ) {
		$login_url = function_exists( 'apply_filters' )
			? apply_filters( 'avision_premium_dashboard_login_redirect_url', trailingslashit( home_url( '/login/' ) ) )
			: trailingslashit( home_url( '/login/' ) );
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( $login_url );
			exit;
		}
		return sprintf(
			'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--denied" role="alert"><p><a href="%1$s">%2$s</a></p></div>',
			esc_url( $login_url ),
			esc_html__( 'Connexion requise — les en-têtes HTTP sont déjà envoyés, utilisez le lien.', 'avision-dashboard' )
		);
	}

	if ( ! avision_user_can_access_premium_dashboard_shortcode() ) {
		return avision_dashboard_shortcode_wrong_account_notice( 'premium' );
	}

	$wp_uid = (int) get_current_user_id();
	$uuid   = avision_get_saas_profile_uuid_for_wp_user( $wp_uid );

	if ( $uuid === '' ) {
		$audit_url = function_exists( 'apply_filters' )
			? apply_filters( 'avision_premium_dashboard_no_pid_redirect_url', trailingslashit( home_url( '/local-audit/' ) ) )
			: trailingslashit( home_url( '/local-audit/' ) );
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( $audit_url );
			exit;
		}
		return sprintf(
			'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--denied" role="alert"><p>%1$s</p><p><a class="button" href="%2$s">%3$s</a></p></div>',
			esc_html__( 'Aucun profil (PID) n’est rattaché à votre compte.', 'avision-dashboard' ),
			esc_url( $audit_url ),
			esc_html__( 'Lancer l’audit local', 'avision-dashboard' )
		);
	}

	$tpl = avision_resolve_premium_dashboard_shortcode_template();

	if ( $tpl !== '' && ! avision_premium_dashboard_template_is_full_document( $tpl ) ) {
		$extra_class = avision_dashboard_shortcode_sanitize_class_attr( (string) $atts['class'] );
		/**
		 * Avant inclusion partial premium.
		 *
		 * @param array  $atts Attributs shortcode.
		 * @param string $uuid PID profil.
		 */
		do_action( 'avision_premium_dashboard_shortcode_before', $atts, $uuid );

		$old_pid = null;
		if ( isset( $_GET['pid'] ) ) {
			$old_pid = function_exists( 'sanitize_text_field' ) && function_exists( 'wp_unslash' )
				? sanitize_text_field( wp_unslash( (string) $_GET['pid'] ) )
				: (string) $_GET['pid'];
		}
		$_GET['pid'] = $uuid;

		ob_start();
		// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- chemin résolu via allowlist interne + filtre.
		include $tpl;
		$inner = ob_get_clean();

		if ( $old_pid === null ) {
			unset( $_GET['pid'] );
		} else {
			$_GET['pid'] = $old_pid;
		}

		$html = apply_filters( 'avision_premium_dashboard_shortcode_html', '', $atts );
		$out  = ( is_string( $html ) && $html !== '' ) ? $html : $inner;

		/**
		 * Après rendu partial / filtre.
		 *
		 * @param array  $atts Attributs shortcode.
		 * @param string $uuid PID profil.
		 */
		do_action( 'avision_premium_dashboard_shortcode_after', $atts, $uuid );

		return '<div class="avision-dashboard-shortcode avision-dashboard-shortcode--premium' . ( $extra_class !== '' ? ' ' . esc_attr( $extra_class ) : '' ) . '" data-avision-dashboard="premium" data-pid="' . esc_attr( $uuid ) . '">'
			. $out // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML template / filtre.
			. '</div>';
	}

	$premium_base = function_exists( 'apply_filters' )
		? apply_filters( 'avision_premium_dashboard_canonical_url', trailingslashit( home_url( '/premium-dashboard/' ) ) )
		: trailingslashit( home_url( '/premium-dashboard/' ) );
	$target       = function_exists( 'add_query_arg' ) ? add_query_arg( 'pid', $uuid, $premium_base ) : $premium_base . '?pid=' . rawurlencode( $uuid );
	$target       = function_exists( 'apply_filters' )
		? apply_filters( 'avision_premium_dashboard_shortcode_redirect_url', $target, $uuid, $atts )
		: $target;

	return sprintf(
		'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--premium"><p><a class="button button-primary" href="%1$s">%2$s</a></p></div>',
		esc_url( $target ),
		esc_html__( 'Ouvrir le cockpit premium', 'avision-dashboard' )
	);
}

/**
 * Shortcode [avision_agency_dashboard].
 *
 * @param array|string $atts Attributs shortcode.
 * @return string
 */
function avision_render_agency_dashboard_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'class' => '',
		),
		$atts,
		'avision_agency_dashboard'
	);

	if ( function_exists( 'avision_is_agency_dashboard_query' ) && avision_is_agency_dashboard_query() ) {
		return '';
	}

	$premium_url = function_exists( 'apply_filters' )
		? apply_filters( 'avision_agency_dashboard_redirect_premium_url', trailingslashit( home_url( '/premium-dashboard/' ) ) )
		: trailingslashit( home_url( '/premium-dashboard/' ) );

	if ( ! avision_user_can_access_agency_dashboard_admin_shortcode() ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( $premium_url );
			exit;
		}
		return sprintf(
			'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--denied" role="alert"><p><a class="button button-primary" href="%1$s">%2$s</a></p></div>',
			esc_url( $premium_url ),
			esc_html__( 'Accès réservé — ouvrir le cockpit premium.', 'avision-dashboard' )
		);
	}

	$tpl = avision_resolve_agency_dashboard_shortcode_template();
	if ( $tpl === '' || ! is_readable( $tpl ) ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( $premium_url );
			exit;
		}
		return sprintf(
			'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--denied" role="alert"><p><a class="button button-primary" href="%1$s">%2$s</a></p></div>',
			esc_url( $premium_url ),
			esc_html__( 'Template agence introuvable — cockpit premium.', 'avision-dashboard' )
		);
	}

	if ( avision_premium_dashboard_template_is_full_document( $tpl ) ) {
		$agency_url = function_exists( 'apply_filters' )
			? apply_filters( 'avision_agency_dashboard_canonical_url', trailingslashit( home_url( '/agency-dashboard/' ) ) )
			: trailingslashit( home_url( '/agency-dashboard/' ) );
		return sprintf(
			'<div class="avision-dashboard-shortcode avision-dashboard-shortcode--agency"><p><a class="button button-primary" href="%1$s">%2$s</a></p></div>',
			esc_url( $agency_url ),
			esc_html__( 'Ouvrir la page cockpit agence', 'avision-dashboard' )
		);
	}

	$extra_class = avision_dashboard_shortcode_sanitize_class_attr( (string) $atts['class'] );

	do_action( 'avision_agency_dashboard_shortcode_before', $atts );

	ob_start();
	// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- chemin résolu via allowlist interne + filtre.
	include $tpl;
	$inner = ob_get_clean();

	$html = apply_filters( 'avision_agency_dashboard_shortcode_html', '', $atts );
	$out  = ( is_string( $html ) && $html !== '' ) ? $html : $inner;

	do_action( 'avision_agency_dashboard_shortcode_after', $atts );

	return '<div class="avision-dashboard-shortcode avision-dashboard-shortcode--agency' . ( $extra_class !== '' ? ' ' . esc_attr( $extra_class ) : '' ) . '" data-avision-dashboard="agency">'
		. $out // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML template / filtre.
		. '</div>';
}

/**
 * Le contenu de la page contient-il le shortcode AppSumo (classique ou bloc shortcode) ?
 *
 * @param \WP_Post|null $post Post courant.
 * @return bool
 */
function avision_appsumo_redeem_content_wants_assets( $post ) {
	if ( ! $post || ! isset( $post->post_content ) || ! is_string( $post->post_content ) ) {
		return false;
	}
	$c = $post->post_content;
	if ( function_exists( 'has_shortcode' ) && has_shortcode( $c, 'avision_appsumo_redeem' ) ) {
		return true;
	}
	return strpos( $c, '[avision_appsumo_redeem' ) !== false;
}

/**
 * Assets formulaire redeem AppSumo (nonce public).
 *
 * @return void
 */
function avision_appsumo_redeem_enqueue_assets() {
	if ( ! defined( 'AVISION_URL' ) || ! defined( 'AVISION_VERSION' ) || ! defined( 'AVISION_PATH' ) ) {
		return;
	}
	$css_rel = 'assets/css/appsumo-redeem.css';
	if ( file_exists( AVISION_PATH . $css_rel ) ) {
		$style_deps = array();
		if ( wp_style_is( 'avision-google-fonts', 'registered' ) || wp_style_is( 'avision-google-fonts', 'enqueued' ) ) {
			$style_deps[] = 'avision-google-fonts';
		}
		if ( wp_style_is( 'avision-base', 'registered' ) || wp_style_is( 'avision-base', 'enqueued' ) ) {
			$style_deps[] = 'avision-base';
		}
		wp_enqueue_style(
			'avision-appsumo-redeem',
			AVISION_URL . $css_rel,
			$style_deps,
			AVISION_VERSION
		);
	}
	$pk = function_exists( 'avi_appsumo_get_stripe_publishable_key' ) ? avi_appsumo_get_stripe_publishable_key() : '';
	$deps = array();
	if ( $pk !== '' ) {
		$stripe_handle = 'stripe-js-v3-appsumo';
		if ( ! wp_script_is( $stripe_handle, 'registered' ) ) {
			wp_register_script(
				$stripe_handle,
				'https://js.stripe.com/v3/',
				array(),
				null,
				true
			);
		}
		wp_enqueue_script( $stripe_handle );
		$deps[] = $stripe_handle;
	}

	wp_enqueue_script(
		'avi-appsumo-redeem',
		AVISION_URL . 'assets/js/avi-appsumo-redeem.js',
		$deps,
		AVISION_VERSION,
		true
	);

	$bundle = array(
		'ajaxurl'             => admin_url( 'admin-ajax.php' ),
		'nonce'               => wp_create_nonce( 'avision_appsumo_nonce' ),
		'stripePublicKey'     => $pk,
		'hasStripeElements'   => ( $pk !== '' ),
		'redirectSkipTrial'   => function_exists( 'avi_appsumo_skip_guardian_trial_redirect_url' )
			? avi_appsumo_skip_guardian_trial_redirect_url()
			: add_query_arg( 'appsumo_welcome', '1', trailingslashit( home_url( '/premium-dashboard/' ) ) ),
		'redirectAfterTrial'  => function_exists( 'avi_appsumo_after_guardian_trial_redirect_url' )
			? avi_appsumo_after_guardian_trial_redirect_url()
			: add_query_arg(
				array( 'appsumo_welcome' => '1', 'guardian' => '1' ),
				trailingslashit( home_url( '/premium-dashboard/' ) )
			),
		'redirectSkipAgency'  => function_exists( 'avi_appsumo_skip_guardian_trial_redirect_agency_url' )
			? avi_appsumo_skip_guardian_trial_redirect_agency_url()
			: add_query_arg( 'appsumo_welcome', '1', trailingslashit( home_url( '/agency-dashboard/' ) ) ),
		'redirectAfterAgency' => function_exists( 'avi_appsumo_after_guardian_trial_redirect_agency_url' )
			? avi_appsumo_after_guardian_trial_redirect_agency_url()
			: add_query_arg(
				array( 'appsumo_welcome' => '1', 'guardian' => '1' ),
				trailingslashit( home_url( '/agency-dashboard/' ) )
			),
		// EN par défaut : msgid = anglais, traduit via fichiers .mo si présents.
		'strInvalid'          => __( 'Please enter an email and a code.', 'avision-dashboard' ),
		'strOk'               => __( 'Account activated!', 'avision-dashboard' ),
		'strCodeInvalid'      => __( 'Invalid code.', 'avision-dashboard' ),
		'strCodeUsed'         => __( 'Invalid or already used code.', 'avision-dashboard' ),
		'strEmailInvalid'     => __( 'Please enter a valid email address.', 'avision-dashboard' ),
		'strNetwork'          => __( 'Network error. Please try again.', 'avision-dashboard' ),
		'strStripeMissing'    => __( 'Online payment is unavailable (Stripe key missing).', 'avision-dashboard' ),
		'strServerErr'        => __( 'An error occurred. Please try again.', 'avision-dashboard' ),
		'strPmMissing'        => __( 'Payment method not found.', 'avision-dashboard' ),
	);

	wp_localize_script( 'avi-appsumo-redeem', 'aviAppSumoRedeem', $bundle );
	wp_localize_script( 'avi-appsumo-redeem', 'aviAppsumoConfig', $bundle );
	wp_localize_script(
		'avi-appsumo-redeem',
		'aviAppsumoI18n',
		array(
			'error_invalid_code'  => __( 'Invalid or already used code.', 'avision-dashboard' ),
			'error_invalid_email' => __( 'Please enter a valid email address.', 'avision-dashboard' ),
			'error_network'       => __( 'Network error. Please try again.', 'avision-dashboard' ),
			'error_generic'       => __( 'An error occurred. Please try again.', 'avision-dashboard' ),
			'loading'             => __( 'Activating your access...', 'avision-dashboard' ),
			'success'             => __( 'Account activated! Redirecting...', 'avision-dashboard' ),
		)
	);
}

/**
 * Shortcode [avision_appsumo_redeem] — activation LTD AppSumo.
 *
 * @param array|string $atts Attributs shortcode.
 * @return string
 */
function avision_render_appsumo_redeem_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'class' => '',
		),
		$atts,
		'avision_appsumo_redeem'
	);
	avision_appsumo_redeem_enqueue_assets();
	$extra = avision_dashboard_shortcode_sanitize_class_attr( (string) $atts['class'] );
	ob_start();
	$tpl = defined( 'AVISION_PATH' ) ? AVISION_PATH . 'templates/appsumo-redeem-form.php' : '';
	if ( $tpl !== '' && file_exists( $tpl ) ) {
		// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- chemin interne fixe.
		include $tpl;
	} else {
		echo '<p>' . esc_html__( 'Formulaire AppSumo indisponible.', 'avision-dashboard' ) . '</p>';
	}
	$inner = ob_get_clean();
	return '<div class="avision-appsumo-redeem-shortcode' . ( $extra !== '' ? ' ' . esc_attr( $extra ) : '' ) . '">' . $inner . '</div>';
}

/**
 * Enqueue si page modèle AppSumo ou contenu avec shortcode (bloc classique).
 *
 * @return void
 */
function avision_maybe_enqueue_appsumo_redeem_assets() {
	if ( ! function_exists( 'is_singular' ) || ! is_singular() ) {
		return;
	}
	// Slug de page dédiée (recommandé : page FSE / éditeur avec uniquement le shortcode — pas de template PHP thème).
	if ( function_exists( 'is_page' ) && is_page( array( 'appsumo-redeem', 'appsumo' ) ) ) {
		avision_appsumo_redeem_enqueue_assets();
		return;
	}
	$post = get_post();
	if ( avision_appsumo_redeem_content_wants_assets( $post ) ) {
		avision_appsumo_redeem_enqueue_assets();
	}
}

/**
 * Enregistre les shortcodes et le hook d’assets.
 *
 * @return void
 */
function avision_register_secure_dashboard_shortcodes() {
	add_shortcode( 'avision_premium_dashboard', 'avision_render_premium_dashboard_shortcode' );
	add_shortcode( 'avision_agency_dashboard', 'avision_render_agency_dashboard_shortcode' );
	add_shortcode( 'avision_pricing_tables', 'avision_render_pricing_tables_shortcode' );
	add_shortcode( 'avision_btob_onboarding', 'avision_render_btob_onboarding_shortcode' );
	add_shortcode( 'avision_appsumo_redeem', 'avision_render_appsumo_redeem_shortcode' );
	add_action( 'wp_enqueue_scripts', 'avision_maybe_enqueue_dashboard_shortcode_assets', 20 );
	add_action( 'wp_enqueue_scripts', 'avision_maybe_enqueue_pricing_shortcode_assets', 20 );
	add_action( 'wp_enqueue_scripts', 'avision_maybe_enqueue_btob_onboarding_assets', 20 );
	add_action( 'wp_enqueue_scripts', 'avision_maybe_enqueue_appsumo_redeem_assets', 20 );
	add_action( 'template_redirect', 'avision_handle_btob_onboarding_post', 5 );
}

/**
 * Enqueue minimal si la page contient un des shortcodes (config niveaux pour thèmes qui s’appuient dessus).
 *
 * @return void
 */
function avision_maybe_enqueue_dashboard_shortcode_assets() {
	if ( ! function_exists( 'is_singular' ) || ! is_singular() ) {
		return;
	}
	$post = get_post();
	if ( ! $post || ! is_string( $post->post_content ) ) {
		return;
	}
	$content = $post->post_content;
	if ( ! has_shortcode( $content, 'avision_premium_dashboard' ) && ! has_shortcode( $content, 'avision_agency_dashboard' ) ) {
		return;
	}
	if ( function_exists( 'avision_enqueue_levels_config' ) ) {
		avision_enqueue_levels_config();
	}
}

/**
 * Shortcode [avision_pricing_tables] — grille tarifaire glassmorphism B2C / B2B.
 *
 * Filtres URL checkout (Stripe, etc.) :
 * - `avi_pricing_url_premium` (défaut : constante AVISION_PRICING_STRIPE_URL_PREMIUM, lien test Stripe)
 * - `avi_pricing_url_agency` (défaut : constante AVISION_PRICING_STRIPE_URL_AGENCY)
 *
 * @param array|string $atts Attributs (ex. class="ma-classe").
 * @return string
 */
function avision_render_pricing_tables_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'class' => '',
		),
		$atts,
		'avision_pricing_tables'
	);

	$avi_pricing_url_premium = (string) apply_filters( 'avi_pricing_url_premium', AVISION_PRICING_STRIPE_URL_PREMIUM );
	$avi_pricing_url_agency  = (string) apply_filters( 'avi_pricing_url_agency', AVISION_PRICING_STRIPE_URL_AGENCY );
	$avi_pricing_extra_class = avision_dashboard_shortcode_sanitize_class_attr( (string) $atts['class'] );

	ob_start();
	$tpl = defined( 'AVISION_PATH' ) ? AVISION_PATH . 'templates/shortcode-pricing-tables.php' : '';
	if ( $tpl !== '' && is_readable( $tpl ) ) {
		// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- chemin fixe sous le plugin.
		include $tpl;
	} else {
		echo '<p class="avi-pricing avi-pricing--error">' . esc_html__( 'Modèle tarifs introuvable.', 'avision-dashboard' ) . '</p>';
	}
	return ob_get_clean();
}

/**
 * Charge avision-pricing.css lorsque la page contient [avision_pricing_tables].
 *
 * @return void
 */
function avision_maybe_enqueue_pricing_shortcode_assets() {
	if ( ! function_exists( 'is_singular' ) || ! is_singular() ) {
		return;
	}
	$post = get_post();
	if ( ! $post || ! is_string( $post->post_content ) ) {
		return;
	}
	if ( ! function_exists( 'has_shortcode' ) || ! has_shortcode( $post->post_content, 'avision_pricing_tables' ) ) {
		return;
	}

	$plugin_file = dirname( __DIR__ ) . '/avision-dashboard.php';
	$base        = defined( 'AVISION_URL' ) ? AVISION_URL : plugin_dir_url( $plugin_file );
	wp_enqueue_style(
		'avision-pricing',
		$base . 'assets/css/avision-pricing.css',
		array(),
		defined( 'AVISION_VERSION' ) ? AVISION_VERSION : '9.0.3'
	);
}

/**
 * Table profils SaaS pour persistance nom d’agence (wor1515 ou préfixe WP).
 *
 * @return string Nom de table ou chaîne vide.
 */
function avision_btob_onboarding_profiles_table() {
	global $wpdb;
	if ( ! isset( $wpdb ) || ! is_object( $wpdb ) ) {
		return '';
	}
	$table = 'wor1515_avi_saas_profiles';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
		$table = $wpdb->prefix . 'avi_saas_profiles';
	}
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
		return '';
	}
	return $table;
}

/**
 * Lit business_name du premier profil lié à l’utilisateur WP.
 *
 * @param int $wp_user_id ID WordPress.
 * @return string
 */
function avision_btob_onboarding_get_profile_business_name( $wp_user_id ) {
	global $wpdb;
	$wp_user_id = (int) $wp_user_id;
	if ( $wp_user_id <= 0 ) {
		return '';
	}
	$meta = '';
	if ( function_exists( 'get_user_meta' ) ) {
		$wl = get_user_meta( $wp_user_id, 'avi_agency_whitelabel_name', true );
		$meta = ( is_string( $wl ) && trim( $wl ) !== '' ) ? $wl : get_user_meta( $wp_user_id, 'avi_agency_name', true );
	}
	if ( is_string( $meta ) && trim( $meta ) !== '' ) {
		return trim( $meta );
	}
	$table = avision_btob_onboarding_profiles_table();
	if ( $table === '' || ! isset( $wpdb ) || ! is_object( $wpdb ) ) {
		return '';
	}
	if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'business_name' ) ) !== 'business_name' ) {
		return '';
	}
	$row = null;
	if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'wp_user_id' ) ) === 'wp_user_id' ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- nom de table homologué.
		$row = $wpdb->get_var( $wpdb->prepare( "SELECT business_name FROM `{$table}` WHERE wp_user_id = %d ORDER BY id DESC LIMIT 1", $wp_user_id ) );
	}
	if ( ( ! is_string( $row ) || trim( $row ) === '' ) && $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'email' ) ) === 'email' ) {
		$user = function_exists( 'get_userdata' ) ? get_userdata( $wp_user_id ) : null;
		$em   = ( $user && is_email( $user->user_email ) ) ? $user->user_email : '';
		if ( $em !== '' ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$row = $wpdb->get_var( $wpdb->prepare( "SELECT business_name FROM `{$table}` WHERE email = %s ORDER BY id DESC LIMIT 1", $em ) );
		}
	}
	return is_string( $row ) ? trim( $row ) : '';
}

/**
 * Passeport onboarding B2B : business_name (+ is_agency_master profil si colonne), métas WP (nom, master, complétion).
 *
 * @param int    $wp_user_id  ID WordPress.
 * @param string $agency_name Nom affiché.
 * @return true|\WP_Error
 */
function avision_btob_onboarding_persist_agency_name( $wp_user_id, $agency_name ) {
	global $wpdb;
	$wp_user_id  = (int) $wp_user_id;
	$agency_name = is_string( $agency_name ) ? trim( sanitize_text_field( $agency_name ) ) : '';
	if ( $wp_user_id <= 0 || $agency_name === '' ) {
		return new \WP_Error( 'avision_btob_empty', __( 'Nom d’agence requis.', 'avision-dashboard' ) );
	}

	$table = avision_btob_onboarding_profiles_table();
	if ( $table !== '' && isset( $wpdb ) && is_object( $wpdb ) ) {
		$has_bn = ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'business_name' ) ) === 'business_name' );
		$has_am = ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'is_agency_master' ) ) === 'is_agency_master' );
		if ( $has_bn ) {
			$row_data   = array( 'business_name' => $agency_name );
			$row_format = array( '%s' );
			if ( $has_am ) {
				$row_data['is_agency_master'] = '1';
				$row_format[]                 = '%s';
			}
			if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'wp_user_id' ) ) === 'wp_user_id' ) {
				$wpdb->update(
					$table,
					$row_data,
					array( 'wp_user_id' => $wp_user_id ),
					$row_format,
					array( '%d' )
				);
			}
			if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'email' ) ) === 'email' ) {
				$user = function_exists( 'get_userdata' ) ? get_userdata( $wp_user_id ) : null;
				$em   = ( $user && is_email( $user->user_email ) ) ? $user->user_email : '';
				if ( $em !== '' ) {
					$wpdb->update(
						$table,
						$row_data,
						array( 'email' => $em ),
						$row_format,
						array( '%s' )
					);
				}
			}
		}
	}

	if ( function_exists( 'update_user_meta' ) ) {
		update_user_meta( $wp_user_id, 'avi_agency_name', $agency_name );
		update_user_meta( $wp_user_id, 'avi_agency_whitelabel_name', $agency_name );
		update_user_meta( $wp_user_id, 'is_agency_master', '1' );
		update_user_meta( $wp_user_id, 'avi_b2b_onboarding_completed', '1' );
		// ANTI-RÉGRESSION [03 juin 2026] — Mettre à jour nom agence dans avi_saas_agencies
		// Le webhook crée l'agence avec le login WP comme nom (company_name vide à ce stade)
		// L'onboarding est le seul moment où le vrai nom est connu
		global $wpdb;
		$agencies_table = $wpdb->prefix . 'avi_saas_agencies';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $agencies_table ) ) === $agencies_table ) {
			$existing = $wpdb->get_var( $wpdb->prepare(
				"SELECT id FROM `{$agencies_table}` WHERE admin_user_id = %d LIMIT 1",
				$wp_user_id
			) );
			if ( $existing ) {
				// Agence déjà créée par webhook → mettre à jour le nom
				$wpdb->update(
					$agencies_table,
					array( 'name' => $agency_name ),
					array( 'admin_user_id' => $wp_user_id ),
					array( '%s' ),
					array( '%d' )
				);
			} else {
				// Agence pas encore créée (onboarding avant webhook) → créer maintenant
				// Le webhook mettra à jour tier + uuid s'il arrive après
				$wpdb->insert(
					$agencies_table,
					array(
						'uuid'          => wp_generate_uuid4(),
						'name'          => $agency_name,
						'admin_user_id' => $wp_user_id,
						'tier'          => 1,
					),
					array( '%s', '%s', '%d', '%d' )
				);
			}
		}
	}

	return true;
}

/**
 * URL de la page d’onboarding B2B (permalink courant ou défaut).
 *
 * @return string
 */
function avision_btob_onboarding_form_action_url() {
	if ( function_exists( 'is_singular' ) && is_singular() && function_exists( 'get_permalink' ) ) {
		$url = get_permalink();
		if ( is_string( $url ) && $url !== '' ) {
			return $url;
		}
	}
	return trailingslashit( home_url( '/btob-onboarding/' ) );
}

/**
 * URL d’autorisation Google OAuth (contexte agence) — aligné sur le thème (avi_build_google_oauth_authorize_url).
 * Utilise wp_redirect côté appelant : URL externe (accounts.google.com), pas wp_safe_redirect.
 *
 * @param int $wp_user_id ID utilisateur (pour filtres).
 * @return string URL non vide, ou chaîne vide si impossible.
 */
function avision_btob_onboarding_resolve_google_oauth_url( $wp_user_id ) {
	$wp_user_id = (int) $wp_user_id;
	$redirect   = null;

	if ( function_exists( 'avi_build_google_oauth_authorize_url' ) ) {
		$built = avi_build_google_oauth_authorize_url( 'agency' );
		if ( is_wp_error( $built ) ) {
			if ( function_exists( 'error_log' ) ) {
				error_log( '[AVI B2B Onboarding] OAuth URL : ' . $built->get_error_message() );
			}
		} elseif ( is_string( $built ) && $built !== '' ) {
			$redirect = $built;
		}
	} elseif ( function_exists( 'avision_get_google_oauth_url' ) ) {
		$alt = avision_get_google_oauth_url( 'agency' );
		if ( is_string( $alt ) && $alt !== '' ) {
			$redirect = $alt;
		}
	}

	/**
	 * URL OAuth après sauvegarde du formulaire B2B. Doit pointer vers Google (ou proxy interne équivalent).
	 *
	 * @param string|null $redirect URL ou null.
	 * @param int         $wp_user_id ID utilisateur.
	 */
	$redirect = apply_filters( 'avision_btob_onboarding_after_save_redirect', $redirect, $wp_user_id );

	if ( ! is_string( $redirect ) || $redirect === '' ) {
		return '';
	}

	return $redirect;
}

/**
 * POST du formulaire [avision_btob_onboarding] : sauvegarde puis redirection obligatoire vers Google OAuth (pas le dashboard).
 *
 * @return void
 */
function avision_handle_btob_onboarding_post() {
	if ( ( isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( (string) $_SERVER['REQUEST_METHOD'] ) : '' ) !== 'POST' ) {
		return;
	}
	if ( empty( $_POST['avision_btob_onboarding_submit'] ) ) {
		return;
	}
	if ( function_exists( 'is_admin' ) && is_admin() ) {
		return;
	}
	if ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) {
		return;
	}
	if ( ! function_exists( 'is_user_logged_in' ) || ! is_user_logged_in() ) {
		return;
	}
	if ( ! function_exists( 'avision_is_btob_onboarding_query' ) || ! avision_is_btob_onboarding_query() ) {
		return;
	}

	$back = avision_btob_onboarding_form_action_url();
	$uid  = (int) get_current_user_id();
	$user = function_exists( 'get_userdata' ) ? get_userdata( $uid ) : null;
	if ( ! $user || ! $user->exists() ) {
		return;
	}
	$is_agency = in_array( 'avi_agency', (array) $user->roles, true );
	$is_admin  = function_exists( 'user_can' ) && user_can( $user, 'manage_options' );
	if ( ! $is_agency && ! $is_admin ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( add_query_arg( 'btob_err', 'forbidden', $back ) );
			exit;
		}
		return;
	}

	$nonce_ok = function_exists( 'wp_verify_nonce' )
		&& isset( $_POST['avision_btob_onboarding_nonce'] )
		&& wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST['avision_btob_onboarding_nonce'] ) ), 'avision_btob_onboarding_save' );
	if ( ! $nonce_ok ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( add_query_arg( 'btob_err', 'nonce', $back ) );
			exit;
		}
		return;
	}

	if ( empty( $_POST['avi_accept_terms'] ) ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( add_query_arg( 'btob_err', 'terms', $back ) );
			exit;
		}
		wp_die( 'You must accept the Terms & Conditions.' );
		return;
	}

	$name = isset( $_POST['avi_btob_agency_name'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['avi_btob_agency_name'] ) ) : '';
	if ( $name === '' ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( add_query_arg( 'btob_err', 'empty', $back ) );
			exit;
		}
		return;
	}

	$persist = avision_btob_onboarding_persist_agency_name( $uid, $name );
	if ( is_wp_error( $persist ) ) {
		if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
			wp_safe_redirect( add_query_arg( 'btob_err', 'empty', $back ) );
			exit;
		}
		return;
	}

	$oauth_url = function_exists( 'avision_btob_onboarding_resolve_google_oauth_url' )
		? avision_btob_onboarding_resolve_google_oauth_url( $uid )
		: '';

	if ( is_string( $oauth_url ) && $oauth_url !== '' && ! headers_sent() ) {
		// URL externe Google : wp_redirect (wp_safe_redirect refuse en général accounts.google.com).
		wp_redirect( esc_url_raw( $oauth_url ), 302 );
		exit;
	}

	if ( ! headers_sent() && function_exists( 'wp_safe_redirect' ) ) {
		wp_safe_redirect( add_query_arg( 'btob_err', 'oauth_config', $back ) );
		exit;
	}
}

/**
 * Shortcode [avision_btob_onboarding] — formulaire glass post-paiement B2B.
 *
 * @param array|string $atts Attributs.
 * @return string
 */
function avision_render_btob_onboarding_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'class' => '',
		),
		$atts,
		'avision_btob_onboarding'
	);

	if ( ! function_exists( 'is_user_logged_in' ) || ! is_user_logged_in() ) {
		$login = function_exists( 'apply_filters' )
			? apply_filters( 'avision_dashboard_guard_login_url', trailingslashit( home_url( '/login/' ) ) )
			: trailingslashit( home_url( '/login/' ) );
		$here  = function_exists( 'get_permalink' ) && is_singular() ? get_permalink() : trailingslashit( home_url( '/btob-onboarding/' ) );
		$here  = is_string( $here ) ? $here : trailingslashit( home_url( '/btob-onboarding/' ) );
		$login = function_exists( 'add_query_arg' ) ? add_query_arg( 'redirect_to', rawurlencode( $here ), $login ) : $login;

		return '<div class="avi-btob-onboarding"><p class="avi-btob-onboarding__login">'
			. esc_html__( 'Connexion requise pour poursuivre l’onboarding agence.', 'avision-dashboard' )
			. ' <a href="' . esc_url( $login ) . '">' . esc_html__( 'Se connecter', 'avision-dashboard' ) . '</a></p></div>';
	}

	$user = function_exists( 'wp_get_current_user' ) ? wp_get_current_user() : null;
	if ( $user && $user->exists() ) {
		$is_agency = in_array( 'avi_agency', (array) $user->roles, true );
		$is_admin  = function_exists( 'user_can' ) && user_can( $user, 'manage_options' );
		if ( ! $is_agency && ! $is_admin ) {
			$premium = function_exists( 'apply_filters' )
				? apply_filters( 'avision_premium_dashboard_canonical_url', trailingslashit( home_url( '/premium-dashboard/' ) ) )
				: trailingslashit( home_url( '/premium-dashboard/' ) );
			return '<div class="avi-btob-onboarding"><p class="avi-btob-onboarding__login">'
				. esc_html__( 'Cet espace est réservé aux comptes agence.', 'avision-dashboard' )
				. ' <a href="' . esc_url( $premium ) . '">' . esc_html__( 'Cockpit premium', 'avision-dashboard' ) . '</a></p></div>';
		}
	}

	$avision_btob_extra_class = avision_dashboard_shortcode_sanitize_class_attr( (string) $atts['class'] );
	$uid                      = (int) get_current_user_id();
	$avision_btob_agency_name_value = function_exists( 'avision_btob_onboarding_get_profile_business_name' )
		? avision_btob_onboarding_get_profile_business_name( $uid )
		: '';

	$avision_btob_error_message   = '';
	$avision_btob_success_message = '';
	if ( isset( $_GET['btob_err'] ) && is_string( $_GET['btob_err'] ) ) {
		$code = sanitize_key( wp_unslash( $_GET['btob_err'] ) );
		$map  = array(
			'empty'        => __( 'Veuillez saisir le nom de votre agence.', 'avision-dashboard' ),
			'nonce'        => __( 'Votre session a expiré. Merci de réessayer.', 'avision-dashboard' ),
			'forbidden'    => __( 'Accès réservé aux comptes agence.', 'avision-dashboard' ),
			'oauth_config' => __( 'Connexion Google indisponible : vérifiez la configuration OAuth (client ID / thème) ou contactez le support.', 'avision-dashboard' ),
			'terms'        => __( 'You must accept the Terms & Conditions.', 'avision-dashboard' ),
		);
		if ( isset( $map[ $code ] ) ) {
			$avision_btob_error_message = $map[ $code ];
		}
	}
	if ( isset( $_GET['btob_ok'] ) && sanitize_key( wp_unslash( (string) $_GET['btob_ok'] ) ) === '1' ) {
		$avision_btob_success_message = __( 'Profil enregistré. Vous pouvez continuer vers le cockpit agence.', 'avision-dashboard' );
	}

	ob_start();
	$tpl = defined( 'AVISION_PATH' ) ? AVISION_PATH . 'templates/shortcode-btob-onboarding.php' : '';
	if ( $tpl !== '' && is_readable( $tpl ) ) {
		// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
		include $tpl;
	} else {
		echo '<p class="avi-btob-onboarding">' . esc_html__( 'Modèle onboarding B2B introuvable.', 'avision-dashboard' ) . '</p>';
	}
	return ob_get_clean();
}

/**
 * Enqueue avision-btob-onboarding.css si le shortcode est présent.
 *
 * @return void
 */
function avision_maybe_enqueue_btob_onboarding_assets() {
	if ( ! function_exists( 'is_singular' ) || ! is_singular() ) {
		return;
	}
	$post = get_post();
	if ( ! $post || ! is_string( $post->post_content ) ) {
		return;
	}
	if ( ! function_exists( 'has_shortcode' ) || ! has_shortcode( $post->post_content, 'avision_btob_onboarding' ) ) {
		return;
	}

	$plugin_file = dirname( __DIR__ ) . '/avision-dashboard.php';
	$base        = defined( 'AVISION_URL' ) ? AVISION_URL : plugin_dir_url( $plugin_file );
	wp_enqueue_style(
		'avision-btob-onboarding',
		$base . 'assets/css/avision-btob-onboarding.css',
		array(),
		defined( 'AVISION_VERSION' ) ? AVISION_VERSION : '9.0.3'
	);
}
