<?php
/**
 * Navigation header marketing : source de vérité = option WP `avi_header_nav_items`.
 * Édition : wp-admin → AVISION → Navigation (admin.php?page=avi-nav-admin).
 *
 * @package Avision
 */

defined( 'ABSPATH' ) || exit;

if ( ! defined( 'AVI_HEADER_NAV_OPTION' ) ) {
	define( 'AVI_HEADER_NAV_OPTION', 'avi_header_nav_items' );
}

/**
 * Structure par défaut (identique à l’ancien header.php en dur).
 *
 * @return array<int, array{match:string,path:string,labels:array<string,string>}>
 */
function avi_header_nav_get_defaults() {
	return array(
		array(
			'match'  => '#^$#',
			'path'   => '',
			'labels' => array(
				'en' => 'Agencies',
				'fr' => 'Agences',
				'es' => 'Agencias',
			),
		),
		array(
			'match'  => '#local-business#',
			'path'   => 'local-business',
			'labels' => array(
				'en' => 'Local Business',
				'fr' => 'Entreprises locales',
				'es' => 'Negocios locales',
			),
		),
		array(
			'match'  => '#how-it-works#',
			'path'   => 'how-it-works',
			'labels' => array(
				'en' => 'How it works',
				'fr' => 'Comment ça marche',
				'es' => 'Cómo funciona',
			),
		),
		array(
			'match'  => '#^pricing#',
			'path'   => 'pricing',
			'labels' => array(
				'en' => 'Pricing',
				'fr' => 'Tarifs',
				'es' => 'Precios',
			),
		),
		array(
			'match'  => '#blog#',
			'path'   => 'blog',
			'labels' => array(
				'en' => 'Blog',
				'fr' => 'Blog',
				'es' => 'Blog',
			),
		),
	);
}

/**
 * Chemin relatif → URL absolue site.
 *
 * @param string $path Segment(s) sans slash de début/fin ; vide = accueil.
 * @return string
 */
function avi_header_nav_build_url( $path ) {
	$path = is_string( $path ) ? trim( $path, '/' ) : '';
	if ( $path === '' ) {
		return home_url( '/' );
	}
	return home_url( '/' . $path . '/' );
}

/**
 * Fusionne une ligne sauvegardée avec les défauts (clés manquantes).
 *
 * @param array<string,mixed> $row Ligne issue de la base.
 * @param array<string,mixed> $def Ligne défaut même index.
 * @return array{match:string,path:string,labels:array<string,string>}
 */
function avi_header_nav_merge_row( $row, $def ) {
	$row   = is_array( $row ) ? $row : array();
	$match = isset( $row['match'] ) ? (string) $row['match'] : (string) $def['match'];
	$path  = isset( $row['path'] ) ? (string) $row['path'] : (string) $def['path'];
	$labels = array();
	if ( isset( $row['labels'] ) && is_array( $row['labels'] ) ) {
		foreach ( array( 'en', 'fr', 'es' ) as $lc ) {
			if ( isset( $row['labels'][ $lc ] ) ) {
				$labels[ $lc ] = (string) $row['labels'][ $lc ];
			} elseif ( isset( $def['labels'][ $lc ] ) ) {
				$labels[ $lc ] = (string) $def['labels'][ $lc ];
			}
		}
	} else {
		$labels = isset( $def['labels'] ) && is_array( $def['labels'] ) ? $def['labels'] : array();
	}
	return array(
		'match'  => $match,
		'path'   => $path,
		'labels' => $labels,
	);
}

/**
 * Configuration complète (défauts + option).
 *
 * @return array<int, array{match:string,path:string,labels:array<string,string>}>
 */
function avi_header_nav_get_config() {
	$defaults = avi_header_nav_get_defaults();
	$saved    = get_option( AVI_HEADER_NAV_OPTION, null );
	if ( ! is_array( $saved ) ) {
		return $defaults;
	}
	$out = array();
	foreach ( $defaults as $i => $def ) {
		$row    = isset( $saved[ $i ] ) ? $saved[ $i ] : array();
		$out[] = avi_header_nav_merge_row( $row, $def );
	}
	// Lignes supplémentaires sauvegardées (extensions futures).
	$n = count( $defaults );
	for ( $i = $n; isset( $saved[ $i ] ); $i++ ) {
		$blank = array(
			'match'  => '#^$#',
			'path'   => '',
			'labels' => array( 'en' => '', 'fr' => '', 'es' => '' ),
		);
		$out[] = avi_header_nav_merge_row( $saved[ $i ], $blank );
	}
	return $out;
}

/**
 * Regex utilisable pour preg_match sur le chemin courant.
 *
 * @param string $pattern Motif regex.
 * @return bool
 */
function avi_header_nav_is_valid_match_pattern( $pattern ) {
	$pattern = (string) $pattern;
	if ( $pattern === '' ) {
		return false;
	}
	return @preg_match( $pattern, '' ) !== false;
}

/**
 * Utilisé par templates/layout/header.php.
 *
 * @param string $lang en|fr|es.
 * @return array<int, array{label:string,url:string,match:string}>
 */
function avi_header_nav_get_items_for_lang( $lang ) {
	$lang = in_array( $lang, array( 'en', 'fr', 'es' ), true ) ? $lang : 'en';
	$config = avi_header_nav_get_config();
	$out    = array();
	foreach ( $config as $row ) {
		$labels = isset( $row['labels'] ) && is_array( $row['labels'] ) ? $row['labels'] : array();
		$label  = isset( $labels[ $lang ] ) ? $labels[ $lang ] : '';
		if ( $label === '' && isset( $labels['en'] ) ) {
			$label = (string) $labels['en'];
		}
		$match = isset( $row['match'] ) ? (string) $row['match'] : '#';
		if ( ! avi_header_nav_is_valid_match_pattern( $match ) ) {
			$match = '#';
		}
		$path = isset( $row['path'] ) ? (string) $row['path'] : '';
		$path = preg_replace( '/[^a-zA-Z0-9\-\/]/', '', str_replace( '\\', '', $path ) );
		$path = trim( preg_replace( '#/{2,}#', '/', $path ), '/' );

		$out[] = array(
			'label' => $label,
			'url'   => avi_header_nav_build_url( $path ),
			'match' => $match,
		);
	}
	return $out;
}

/**
 * Sanitize POST → structure option.
 *
 * @param array<string,mixed> $post Données $_POST.
 * @return array<int, array{match:string,path:string,labels:array<string,string>}>|null null si invalide.
 */
function avi_header_nav_sanitize_post( $post ) {
	if ( ! isset( $post['avi_nav_rows'] ) || ! is_array( $post['avi_nav_rows'] ) ) {
		return null;
	}
	$defaults = avi_header_nav_get_defaults();
	$rows_in  = $post['avi_nav_rows'];
	$out      = array();
	$max      = max( count( $defaults ), count( $rows_in ) );
	for ( $i = 0; $i < $max; $i++ ) {
		if ( ! isset( $rows_in[ $i ] ) || ! is_array( $rows_in[ $i ] ) ) {
			if ( isset( $defaults[ $i ] ) ) {
				$out[] = $defaults[ $i ];
			}
			continue;
		}
		$r = $rows_in[ $i ];
		$match = isset( $r['match'] ) ? wp_unslash( (string) $r['match'] ) : '';
		if ( ! avi_header_nav_is_valid_match_pattern( $match ) ) {
			$match = isset( $defaults[ $i ]['match'] ) ? (string) $defaults[ $i ]['match'] : '#^$#';
		}
		$path = isset( $r['path'] ) ? wp_unslash( (string) $r['path'] ) : '';
		$path = preg_replace( '/[^a-zA-Z0-9\-\/]/', '', str_replace( '\\', '', $path ) );
		$path = trim( preg_replace( '#/{2,}#', '/', $path ), '/' );

		$labels = array();
		foreach ( array( 'en', 'fr', 'es' ) as $lc ) {
			$key           = 'label_' . $lc;
			$labels[ $lc ] = isset( $r[ $key ] ) ? sanitize_text_field( wp_unslash( (string) $r[ $key ] ) ) : '';
		}
		$out[] = array(
			'match'  => $match,
			'path'   => $path,
			'labels' => $labels,
		);
	}
	return $out;
}

/**
 * Page admin AVISION → Navigation.
 *
 * @return void
 */
function avi_render_header_nav_admin_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Accès refusé.', 'avision-dashboard' ), '', array( 'response' => 403 ) );
	}

	if ( isset( $_POST['avi_header_nav_save'] ) && isset( $_POST['_wpnonce'] )
		&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'avi_header_nav_save' ) ) {
		$san = avi_header_nav_sanitize_post( $_POST );
		if ( is_array( $san ) ) {
			update_option( AVI_HEADER_NAV_OPTION, $san, false );
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Navigation enregistrée.', 'avision-dashboard' ) . '</p></div>';
		} else {
			echo '<div class="notice notice-error"><p>' . esc_html__( 'Données invalides.', 'avision-dashboard' ) . '</p></div>';
		}
	}

	$config = avi_header_nav_get_config();
	$header_file = defined( 'AVISION_PATH' ) ? trailingslashit( AVISION_PATH ) . 'templates/layout/header.php' : '';

	echo '<div class="wrap">';
	echo '<h1>' . esc_html__( 'Navigation (header public)', 'avision-dashboard' ) . '</h1>';
	echo '<p class="description">' . esc_html__( 'Libellés multilingues (EN / FR / ES), chemin relatif à la racine du site (sans domaine) et motif regex pour le lien actif. Les modifications s’appliquent immédiatement au front.', 'avision-dashboard' ) . '</p>';

	if ( $header_file !== '' ) {
		echo '<p><span class="description">' . esc_html__( 'Fichier d’affichage :', 'avision-dashboard' ) . '</span> <code>' . esc_html( $header_file ) . '</code></p>';
	}

	echo '<form method="post" action="">';
	wp_nonce_field( 'avi_header_nav_save' );
	echo '<input type="hidden" name="avi_header_nav_save" value="1" />';

	echo '<table class="form-table" role="presentation"><tbody>';
	foreach ( $config as $index => $row ) {
		$labels = isset( $row['labels'] ) && is_array( $row['labels'] ) ? $row['labels'] : array();
		echo '<tr><th scope="row">' . esc_html( sprintf( /* translators: %d: row number */ __( 'Lien %d', 'avision-dashboard' ), (int) $index + 1 ) ) . '</th><td>';
		echo '<fieldset style="display:grid;gap:10px;max-width:720px;">';
		echo '<label><span class="screen-reader-text">' . esc_html__( 'Chemin', 'avision-dashboard' ) . '</span>';
		echo '<span class="description" style="display:block;margin-bottom:4px;">' . esc_html__( 'Chemin (slug)', 'avision-dashboard' ) . '</span>';
		echo '<input type="text" class="regular-text code" name="avi_nav_rows[' . (int) $index . '][path]" value="' . esc_attr( isset( $row['path'] ) ? (string) $row['path'] : '' ) . '" placeholder="pricing" />';
		echo '</label>';
		echo '<label><span class="description" style="display:block;margin-bottom:4px;">' . esc_html__( 'Motif regex (état actif)', 'avision-dashboard' ) . '</span>';
		echo '<input type="text" class="large-text code" name="avi_nav_rows[' . (int) $index . '][match]" value="' . esc_attr( isset( $row['match'] ) ? (string) $row['match'] : '' ) . '" />';
		echo '</label>';
		foreach ( array( 'en' => 'EN', 'fr' => 'FR', 'es' => 'ES' ) as $lc => $lc_label ) {
			$val = isset( $labels[ $lc ] ) ? (string) $labels[ $lc ] : '';
			echo '<label><span class="description" style="display:block;margin-bottom:4px;">' . esc_html( $lc_label ) . '</span>';
			echo '<input type="text" class="regular-text" name="avi_nav_rows[' . (int) $index . '][label_' . esc_attr( $lc ) . ']" value="' . esc_attr( $val ) . '" />';
			echo '</label>';
		}
		echo '</fieldset>';
		echo '</td></tr>';
	}
	echo '</tbody></table>';

	submit_button( __( 'Enregistrer la navigation', 'avision-dashboard' ) );
	echo '</form>';

	echo '<p style="margin-top:24px;display:flex;gap:12px;flex-wrap:wrap;">';
	echo '<a class="button button-secondary" href="' . esc_url( admin_url( 'admin.php?page=avi-pages-admin' ) ) . '">' . esc_html__( '← Pages Avision', 'avision-dashboard' ) . '</a>';
	echo '<a class="button button-secondary" href="' . esc_url( admin_url( 'admin.php?page=avi-footer-admin' ) ) . '">' . esc_html__( 'Footer (colonnes) →', 'avision-dashboard' ) . '</a>';
	echo '</p>';
	echo '</div>';
}
