<?php
// AVI_VERSION: 1.0.0 | nav-admin | 2026-04-30
defined( 'ABSPATH' ) || exit;

class Avision_Nav_Admin {

	public static function init(): void {
		add_action( 'admin_menu', array( __CLASS__, 'add_menu' ), 25 );
		add_action( 'wp_ajax_avi_save_nav', array( __CLASS__, 'ajax_save' ) );
	}

	public static function add_menu(): void {
		add_submenu_page(
			'avision-dashboard',
			'Navigation & Footer',
			'🧭 Navigation',
			'manage_options',
			'avi-nav-admin',
			array( __CLASS__, 'render_page' )
		);
	}

	public static function ajax_save(): void {
		check_ajax_referer( 'avi_nav_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized' );
		}
		$type = sanitize_key( $_POST['type'] ?? '' );
		$data = $_POST['data'] ?? '';

		$decoded = json_decode( stripslashes( $data ), true );
		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error( 'Invalid JSON' );
		}

		$clean = array();
		foreach ( $decoded as $item ) {
			$clean[] = array(
				'label'  => sanitize_text_field( $item['label'] ?? '' ),
				'url'    => esc_url_raw( $item['url'] ?? '' ),
				'target' => sanitize_key( $item['target'] ?? '_self' ),
			);
		}

		update_option( 'avi_nav_' . $type, $clean );
		wp_send_json_success( array( 'saved' => count( $clean ) ) );
	}

	public static function render_page(): void {

		$nav_items    = get_option( 'avi_nav_main', array() );
		$footer_col1  = get_option( 'avi_nav_footer_col1', array() );
		$footer_col2  = get_option( 'avi_nav_footer_col2', array() );
		$footer_col3  = get_option( 'avi_nav_footer_col3', array() );
		$footer_col4  = get_option( 'avi_nav_footer_col4', array() );

		if ( empty( $nav_items ) ) {
			$nav_items = array(
				array( 'label' => 'Agencies', 'url' => '/' ),
				array( 'label' => 'Local Business', 'url' => '/local-business/' ),
				array( 'label' => 'How it works', 'url' => '/how-it-works/' ),
				array( 'label' => 'Pricing', 'url' => '/pricing/' ),
				array( 'label' => 'Blog', 'url' => '/blog/' ),
			);
		}
		if ( empty( $footer_col1 ) ) {
			$footer_col1 = array(
				array( 'label' => 'How It Works', 'url' => '/how-it-works/' ),
				array( 'label' => 'Pricing', 'url' => '/pricing/' ),
				array( 'label' => 'Demo', 'url' => '/demo-dashboard/' ),
			);
		}
		if ( empty( $footer_col2 ) ) {
			$footer_col2 = array(
				array( 'label' => 'Agency Plans', 'url' => '/agency-pricing/' ),
				array( 'label' => 'Nonprofits', 'url' => '/nonprofits/' ),
				array( 'label' => 'AppSumo LTD', 'url' => '/appsumo-redeem/' ),
			);
		}
		if ( empty( $footer_col3 ) ) {
			$footer_col3 = array(
				array( 'label' => 'Blog', 'url' => '/blog/' ),
				array( 'label' => 'Free Audit', 'url' => '/local-audit/' ),
				array( 'label' => 'About', 'url' => '/about/' ),
			);
		}
		if ( empty( $footer_col4 ) ) {
			$footer_col4 = array(
				array( 'label' => 'Privacy Policy', 'url' => '/privacy-policy/' ),
				array( 'label' => 'Terms of Use', 'url' => '/terms-of-use/' ),
				array( 'label' => 'API Security', 'url' => '/api-security/' ),
				array( 'label' => 'GDPR', 'url' => '/legal/#gdpr' ),
			);
		}

		$nonce = wp_create_nonce( 'avi_nav_admin_nonce' );
		$ajax  = admin_url( 'admin-ajax.php' );
		?>
		<div class="wrap">
		<h1>🧭 Navigation &amp; Footer Editor</h1>
		<p style="color:#666;margin-bottom:20px">
			Add, remove or reorder links. Changes apply immediately after saving.
		</p>

		<?php
		$sections = array(
			'main'        => array(
				'title' => '🔗 Main Navigation (top nav)',
				'data'  => $nav_items,
			),
			'footer_col1' => array(
				'title' => '🦶 Footer — Product column',
				'data'  => $footer_col1,
			),
			'footer_col2' => array(
				'title' => '🦶 Footer — Agencies column',
				'data'  => $footer_col2,
			),
			'footer_col3' => array(
				'title' => '🦶 Footer — Resources column',
				'data'  => $footer_col3,
			),
			'footer_col4' => array(
				'title' => '🦶 Footer — Legal column',
				'data'  => $footer_col4,
			),
		);
		foreach ( $sections as $type => $section ) :
			?>
		<div style="background:#fff;border:1px solid #e0e0e0;
					border-radius:8px;padding:20px;
					margin-bottom:20px">
			<h2 style="margin-top:0;font-size:15px">
				<?php echo esc_html( $section['title'] ); ?>
			</h2>
			<div id="list-<?php echo esc_attr( $type ); ?>">
				<?php foreach ( $section['data'] as $i => $item ) : ?>
				<div class="avi-nav-row"
					 style="display:flex;gap:8px;
							margin-bottom:8px;align-items:center"
					 data-type="<?php echo esc_attr( $type ); ?>"
					 data-index="<?php echo esc_attr( (string) $i ); ?>">
					<span style="cursor:grab;color:#ccc;
								 font-size:16px;padding:4px">⠿</span>
					<input type="text"
						   class="nav-label"
						   value="<?php echo esc_attr( $item['label'] ); ?>"
						   placeholder="Label"
						   style="flex:1;padding:7px 10px;
								  border:1px solid #ddd;
								  border-radius:6px;font-size:13px"/>
					<input type="text"
						   class="nav-url"
						   value="<?php echo esc_attr( $item['url'] ); ?>"
						   placeholder="/url/"
						   style="flex:2;padding:7px 10px;
								  border:1px solid #ddd;
								  border-radius:6px;font-size:13px;
								  font-family:monospace"/>
					<select class="nav-target"
							style="padding:7px 8px;border:1px solid #ddd;
								   border-radius:6px;font-size:13px">
						<option value="_self" <?php selected( $item['target'] ?? '_self', '_self' ); ?>>
							Same tab
						</option>
						<option value="_blank" <?php selected( $item['target'] ?? '_self', '_blank' ); ?>>
							New tab
						</option>
					</select>
					<button onclick="removeRow(this)"
							style="background:#fee;border:1px solid #fcc;
								   color:#c00;border-radius:6px;
								   padding:6px 10px;cursor:pointer;
								   font-size:12px">
						✕
					</button>
				</div>
				<?php endforeach; ?>
			</div>
			<div style="display:flex;gap:8px;margin-top:10px">
				<button onclick="addRow('<?php echo esc_js( $type ); ?>')"
						class="button">
					+ Add link
				</button>
				<button onclick="saveSection('<?php echo esc_js( $type ); ?>')"
						class="button button-primary"
						style="background:#6B46E8;
							   border-color:#5030C0">
					💾 Save
				</button>
				<span class="save-status-<?php echo esc_attr( $type ); ?>"
					  style="font-size:12px;color:#666;
							 align-self:center"></span>
			</div>
		</div>
			<?php endforeach; ?>
		</div>

		<script>
		const ajaxUrl = '<?php echo esc_js( $ajax ); ?>';
		const nonce   = '<?php echo esc_js( $nonce ); ?>';

		function addRow(type) {
			const list = document.getElementById('list-' + type);
			const div  = document.createElement('div');
			div.className = 'avi-nav-row';
			div.style = 'display:flex;gap:8px;margin-bottom:8px;align-items:center';
			div.dataset.type = type;
			div.innerHTML = `
			  <span style="cursor:grab;color:#ccc;font-size:16px;padding:4px">⠿</span>
			  <input type="text" class="nav-label" placeholder="Label"
				style="flex:1;padding:7px 10px;border:1px solid #ddd;border-radius:6px;font-size:13px"/>
			  <input type="text" class="nav-url" placeholder="/url/"
				style="flex:2;padding:7px 10px;border:1px solid #ddd;border-radius:6px;font-size:13px;font-family:monospace"/>
			  <select class="nav-target" style="padding:7px 8px;border:1px solid #ddd;border-radius:6px;font-size:13px">
				<option value="_self">Same tab</option>
				<option value="_blank">New tab</option>
			  </select>
			  <button onclick="removeRow(this)"
				style="background:#fee;border:1px solid #fcc;color:#c00;border-radius:6px;padding:6px 10px;cursor:pointer;font-size:12px">✕</button>`;
			list.appendChild(div);
		}

		function removeRow(btn) {
			btn.closest('.avi-nav-row').remove();
		}

		function saveSection(type) {
			const rows = document.querySelectorAll('#list-' + type + ' .avi-nav-row');
			const data = [];
			rows.forEach(row => {
				const label  = row.querySelector('.nav-label').value.trim();
				const url    = row.querySelector('.nav-url').value.trim();
				const target = row.querySelector('.nav-target').value;
				if ( label && url ) {
					data.push({ label, url, target });
				}
			});
			const status = document.querySelector('.save-status-' + type);
			status.textContent = 'Saving…';
			fetch(ajaxUrl, {
				method  : 'POST',
				headers : {'Content-Type':'application/x-www-form-urlencoded'},
				body    : new URLSearchParams({
					action : 'avi_save_nav',
					nonce,
					type,
					data   : JSON.stringify(data),
				}),
			})
			.then(r => r.json())
			.then(res => {
				status.textContent = res.success ? ('✓ Saved (' + res.data.saved + ' links)') : '✗ Error';
				setTimeout(() => status.textContent = '', 3000);
			});
		}
		</script>
		<?php
	}
}

