<?php
/**
 * Unlock Advance Mega Menu – settings in Appearance → Menus.
 * Lets user declare a menu as "mega menu" and choose template (1–5 or custom Elementor page).
 *
 * @package Unlockafe_addons\Classes
 */

namespace Unlockafe_addons\Classes;

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

class Mega_Menu_Nav_Settings {

	const OPTION_KEY = 'unlockafe_mega_menu_settings';

	public static function get_templates() {
		return [
			// 'template_1' => __( 'Template 1 (Blocks)', 'unlock-addons-for-elementor' ),
			// 'template_2' => __( 'Template 2 (Features)', 'unlock-addons-for-elementor' ),
			// 'template_3' => __( 'Template 3 (Solutions)', 'unlock-addons-for-elementor' ),
			// 'template_4' => __( 'Template 4 (Posts)', 'unlock-addons-for-elementor' ),
			// 'template_5' => __( 'Template 5 (Pages)', 'unlock-addons-for-elementor' ),
			'custom'     => __( 'Custom Elementor page', 'unlock-addons-for-elementor' ),
		];
	}

	public static function get_layout_for_template( $template ) {
		$map = [
			'template_1' => 'blocks',
			'template_2' => 'features',
			'template_3' => 'solutions',
			'template_4' => 'posts',
			'template_5' => 'pages',
		];
		return isset( $map[ $template ] ) ? $map[ $template ] : 'blocks';
	}

	public static function get_settings_for_menu( $menu_id ) {
		$all = get_option( self::OPTION_KEY, [] );
		$id  = (int) $menu_id;
		if ( ! $id || ! is_array( $all ) || ! isset( $all[ $id ] ) ) {
			return [ 'enabled' => false ];
		}
		$s = $all[ $id ];
		return [ 'enabled' => ! empty( $s['enabled'] ) ];
	}

	const ITEM_META_TEMPLATE = '_unlockafe_amm_item_template';
	const ITEM_META_CUSTOM_PAGE = '_unlockafe_amm_item_custom_page_id';

	public function __construct() {
		add_action( 'admin_init', [ $this, 'add_meta_box' ] );
		add_action( 'wp_update_nav_menu', [ $this, 'save_settings' ], 10, 1 );
		add_action( 'wp_nav_menu_item_custom_fields', [ $this, 'render_item_fields' ], 10, 5 );
		add_action( 'wp_update_nav_menu_item', [ $this, 'save_item_fields' ], 10, 3 );
	}

	public function add_meta_box() {
		add_meta_box(
			'unlockafe-amm-menu-settings',
			__( 'Unlock Advance Mega Menu', 'unlock-addons-for-elementor' ),
			[ $this, 'render_meta_box' ],
			'nav-menus',
			'side',
			'high'
		);
	}

	public function render_meta_box() {
		$menu_id = isset( $_GET['menu'] ) ? (int) $_GET['menu'] : 0;
		$settings = self::get_settings_for_menu( $menu_id );
		wp_nonce_field( 'unlockafe_amm_menu_settings', 'unlockafe_amm_menu_nonce' );
		?>
		<div class="unlockafe-amm-menu-settings" style="padding: 0 0 10px;">
			<p>
				<label>
					<input type="checkbox" name="unlockafe_amm_mega_enabled" value="1" <?php checked( $settings['enabled'] ); ?> />
					<?php esc_html_e( 'Enable this menu for Advance Mega Menu', 'unlock-addons-for-elementor' ); ?>
				</label>
			</p>
			<p class="description" style="margin-top: 8px;">
				<?php esc_html_e( 'Choose a mega menu template under each menu item (click the arrow next to the item). Hover or click that item on the frontend to show its chosen template.', 'unlock-addons-for-elementor' ); ?>
			</p>
		</div>
		<script>
		(function(){
			// Move "Unlock Advance Mega Menu" box to the RIGHT side (under menu, inside the form)
			function moveBoxToRight() {
				var form = document.getElementById('update-nav-menu');
				var box = document.getElementById('unlockafe-amm-menu-settings');
				if (form && box && box.parentNode) {
					var target = form.querySelector('.menu-edit') || form.querySelector('#nav-menu-header') || form.firstElementChild;
					if (target) {
						form.insertBefore(box, target);
					} else {
						form.insertBefore(box, form.firstChild);
					}
				}
			}
			if (document.readyState === 'loading') {
				document.addEventListener('DOMContentLoaded', moveBoxToRight);
			} else {
				moveBoxToRight();
			}
			// Fallback: ensure checkbox and nonce are submitted if box is outside form
			var form = document.getElementById('update-nav-menu');
			if (form) {
				form.addEventListener('submit', function() {
					var enabled = document.querySelector('input[name="unlockafe_amm_mega_enabled"]');
					var nonce = document.querySelector('input[name="unlockafe_amm_menu_nonce"]');
					if (nonce && !form.querySelector('input[name="unlockafe_amm_menu_nonce"]')) {
						var n = document.createElement('input');
						n.type = 'hidden'; n.name = nonce.name; n.value = nonce.value;
						form.appendChild(n);
					}
					if (enabled && !form.querySelector('input[name="unlockafe_amm_mega_enabled"]')) {
						var e = document.createElement('input');
						e.type = 'hidden'; e.name = 'unlockafe_amm_mega_enabled'; e.value = enabled.checked ? '1' : '';
						form.appendChild(e);
					}
				});
			}
		})();
		</script>
		<?php
	}

	public function save_settings( $menu_id ) {
		if ( ! isset( $_POST['unlockafe_amm_menu_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['unlockafe_amm_menu_nonce'] ) ), 'unlockafe_amm_menu_settings' ) ) {
			return;
		}
		$menu_id = (int) $menu_id;
		if ( ! $menu_id ) {
			return;
		}
		$all = get_option( self::OPTION_KEY, [] );
		if ( ! is_array( $all ) ) {
			$all = [];
		}
		$enabled = isset( $_POST['unlockafe_amm_mega_enabled'] ) && $_POST['unlockafe_amm_mega_enabled'] === '1';
		$all[ $menu_id ] = [
			'enabled' => $enabled,
		];
		update_option( self::OPTION_KEY, $all );
	}

	/**
	 * Per-menu-item: show "Mega template" choice when editing a menu item (e.g. Sample Page).
	 * When user hovers/clicks that item on frontend, the chosen template shows as mega panel.
	 */
	public function render_item_fields( $item_id, $menu_item, $depth, $args, $current_object_id = 0 ) {
		$item_id = (int) $item_id;
		if ( $item_id <= 0 ) {
			return;
		}
		$templates = [ '' => __( '— No mega (normal link) —', 'unlock-addons-for-elementor' ) ] + self::get_templates();
		$current = get_post_meta( $item_id, self::ITEM_META_TEMPLATE, true );
		$custom_page_id = (int) get_post_meta( $item_id, self::ITEM_META_CUSTOM_PAGE, true );
		$pages = get_posts( [
			'post_type'      => 'page',
			'post_status'    => 'publish',
			'posts_per_page' => 100,
			'orderby'        => 'title',
			'order'          => 'ASC',
		] );
		?>
		<div class="unlockafe-amm-item-mega-wrap" style="margin: 8px 0 0; padding: 8px 0 0; border-top: 1px solid #ddd;">
			<strong style="display: block; margin-bottom: 6px;"><?php esc_html_e( 'Unlock Advance Mega Menu', 'unlock-addons-for-elementor' ); ?></strong>
		<p class="field-unlockafe-mega description description-wide" style="margin: 0 0 5px;">
			<label for="unlockafe_amm_item_template_<?php echo esc_attr( $item_id ); ?>">
				<?php esc_html_e( 'Mega menu template', 'unlock-addons-for-elementor' ); ?>
			</label>
			<select name="unlockafe_amm_item_template[<?php echo esc_attr( $item_id ); ?>]" id="unlockafe_amm_item_template_<?php echo esc_attr( $item_id ); ?>" class="widefat unlockafe-amm-item-template">
				<?php foreach ( $templates as $value => $label ) : ?>
					<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current, $value ); ?>><?php echo esc_html( $label ); ?></option>
				<?php endforeach; ?>
			</select>
		</p>
		<p class="field-unlockafe-mega-custom description description-wide unlockafe-amm-item-custom-wrap" style="margin: 5px 0 0; <?php echo ( $current === 'custom' ) ? '' : 'display:none;'; ?>">
			<label for="unlockafe_amm_item_custom_page_<?php echo esc_attr( $item_id ); ?>">
				<?php esc_html_e( 'Custom page', 'unlock-addons-for-elementor' ); ?>
			</label>
			<select name="unlockafe_amm_item_custom_page[<?php echo esc_attr( $item_id ); ?>]" id="unlockafe_amm_item_custom_page_<?php echo esc_attr( $item_id ); ?>" class="widefat">
				<option value="0"><?php esc_html_e( '— Select page —', 'unlock-addons-for-elementor' ); ?></option>
				<?php foreach ( $pages as $page ) : ?>
					<option value="<?php echo esc_attr( $page->ID ); ?>" <?php selected( $custom_page_id, $page->ID ); ?>><?php echo esc_html( $page->post_title ); ?></option>
				<?php endforeach; ?>
			</select>
		</p>
		</div>
		<script>
		(function(){
			var sel = document.getElementById('unlockafe_amm_item_template_<?php echo (int) $item_id; ?>');
			if (sel) {
				var menuItem = sel.closest('.menu-item');
				var wrap = menuItem ? menuItem.querySelector('.unlockafe-amm-item-custom-wrap') : null;
				function toggle() { if (wrap) wrap.style.display = sel.value === 'custom' ? '' : 'none'; }
				sel.addEventListener('change', toggle);
				toggle();
			}
		})();
		</script>
		<?php
	}

	public function save_item_fields( $menu_id, $menu_item_db_id, $menu_item_args ) {
		if ( ! isset( $_POST['unlockafe_amm_item_template'] ) || ! is_array( $_POST['unlockafe_amm_item_template'] ) ) {
			return;
		}
		$item_id = (int) $menu_item_db_id;
		if ( $item_id <= 0 ) {
			return;
		}
		$templates = array_merge( [ '' ], array_keys( self::get_templates() ) );
		$key = (string) $item_id;
		$template = isset( $_POST['unlockafe_amm_item_template'][ $key ] ) ? sanitize_text_field( wp_unslash( $_POST['unlockafe_amm_item_template'][ $key ] ) ) : '';
		$custom_page_id = isset( $_POST['unlockafe_amm_item_custom_page'][ $key ] ) ? (int) $_POST['unlockafe_amm_item_custom_page'][ $key ] : 0;
		if ( $template !== '' && ! in_array( $template, $templates, true ) ) {
			$template = '';
		}
		update_post_meta( $item_id, self::ITEM_META_TEMPLATE, $template );
		update_post_meta( $item_id, self::ITEM_META_CUSTOM_PAGE, $custom_page_id );
	}

	/**
	 * Get template and custom_page_id for a nav menu item. Returns array with 'template' and 'custom_page_id'.
	 * If item has its own template set, use that; else return null so caller uses menu default.
	 */
	public static function get_item_template( $menu_item_id ) {
		$item_id = (int) $menu_item_id;
		if ( $item_id <= 0 ) {
			return null;
		}
		$template = get_post_meta( $item_id, self::ITEM_META_TEMPLATE, true );
		$template = is_string( $template ) ? trim( $template ) : '';
		if ( $template === '' ) {
			return null;
		}
		// Ensure template is a known key (template_1 … template_5 or custom)
		$valid = array_keys( self::get_templates() );
		if ( ! in_array( $template, $valid, true ) ) {
			return null;
		}
		$custom_page_id = (int) get_post_meta( $item_id, self::ITEM_META_CUSTOM_PAGE, true );
		return [ 'template' => $template, 'custom_page_id' => $custom_page_id ];
	}
}
