<?php
/**
 * Menu management
 */

namespace Lean_CSNS;

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Menu Class
 *
 * Handles menu registration, lex settings bootstrap, and plugin action links.
 */
class Menu {

	/**
	 * Singleton instance
	 *
	 * @var Menu
	 */
	private static $instance = null;

	/**
	 * Lex Settings instance
	 *
	 * @var \Lex\Settings\V2\Settings|null
	 */
	private $lex_settings = null;

	/**
	 * Get singleton instance
	 *
	 * @return Menu
	 */
	public static function get_instance() {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Private constructor to prevent direct instantiation
	 */
	private function __construct() {
		$this->init();
	}

	/**
	 * Initialize menu functionality
	 */
	private function init() {
		add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );

		// Init lex on admin_init (fires after admin_menu) so translations are loaded
		add_action( 'admin_init', [ $this, 'init_lex_settings' ] );

		add_filter( 'plugin_action_links_' . plugin_basename( LEAN_CSNS_PL_FILE ), [ $this, 'add_plugin_action_links' ] );
		add_action( 'admin_head', [ $this, 'suppress_admin_notices' ] );

		// Point the upgrade-modal CTA at our in-plugin Freemius pricing page.
		add_filter( 'lex_settings/upgrade_cta', [ $this, 'filter_upgrade_cta' ], 10, 2 );
	}

	/**
	 * Set the upgrade-modal button URL/target for our settings instance.
	 * Other instances pass through untouched.
	 *
	 * @param array  $cta         url/target/label for the CTA button.
	 * @param string $instance_id The lex-settings instance the modal belongs to.
	 * @return array
	 */
	public function filter_upgrade_cta( $cta, $instance_id ) {
		if ( 'lean_csns' !== $instance_id ) {
			return $cta;
		}

		// Freemius pricing page lives in wp-admin, so open it in the same tab.
		if ( function_exists( 'lean_csns_fs' ) ) {
			$cta['url']    = lean_csns_fs()->pricing_url();
			$cta['target'] = '';
		}

		return $cta;
	}

	/**
	 * Initialize Lex Settings Framework
	 * Called on admin_init so translations are loaded and admin_menu has already fired
	 */
	public function init_lex_settings() {
		// Only initialize once
		if ( $this->lex_settings !== null ) {
			return;
		}

		$framework_file = LEAN_CSNS_PL_DIR . 'includes/libs/lex-settings-new/core/Settings.php';
		$framework_dir  = dirname( $framework_file );

		if ( ! file_exists( $framework_file ) ) {
			return;
		}

		if ( ! class_exists( '\Lex\Settings\V2\Settings' ) ) {
			require_once $framework_file;
		}

		$default_settings = include LEAN_CSNS_PL_DIR . 'includes/default-settings.php';

		$this->lex_settings = new \Lex\Settings\V2\Settings( [
			'framework_path'      => $framework_dir,
			'register_menu'       => false, // We register our own menu via add_admin_menu()
			'menu_slug'           => 'lean-csns-settings',
			'instance_id'         => 'lean_csns',
			'option_key'          => 'lean_csns_settings',
			'page_title'          => __( 'Cart Share & Save', 'lean-cart-share-and-save' ),
			'menu_title'          => __( 'Cart Share & Save', 'lean-cart-share-and-save' ),
			'capability'          => 'manage_options',
			'logo'                => 'dashicons dashicons-cart',
			'version'             => LEAN_CSNS_VERSION,
			'defaults'            => $default_settings,
			'page_check_callback' => [ $this, 'is_plugin_admin_page' ],
		] );

		$this->register_tabs();
	}

	/**
	 * Register Lex Settings tabs
	 */
	public function register_tabs() {
		if ( ! $this->lex_settings ) {
			return;
		}

		$this->lex_settings->registerTab( [
			'id'    => 'share-cart',
			'label' => __( 'Share Cart', 'lean-cart-share-and-save' ),
			'icon'  => 'dashicons-share',
			'order' => 10,
		] );

		$this->lex_settings->registerTab( [
			'id'    => 'save-cart',
			'label' => __( 'Save Cart', 'lean-cart-share-and-save' ),
			'icon'  => 'dashicons-saved',
			'order' => 20,
		] );

		$this->lex_settings->registerTab( [
			'id'    => 'advanced',
			'label' => __( 'Advanced', 'lean-cart-share-and-save' ),
			'icon'  => 'dashicons-admin-tools',
			'order' => 30,
		] );
	}

	/**
	 * Add admin menu page
	 */
	public function add_admin_menu() {
		add_menu_page(
			__( 'Cart Share & Save', 'lean-cart-share-and-save' ),
			__( 'Cart Share & Save', 'lean-cart-share-and-save' ),
			'manage_options',
			'lean-csns-settings',
			[ $this, 'settings_page_cb' ],
			'dashicons-share',
			56
		);

		// WordPress auto-creates a first submenu that duplicates the top-level title.
		// Re-registering the same slug overrides that duplicate and renames it to "Settings"
		// (top-level stays "Cart Share & Save"). Same technique the player plugin uses.
		add_submenu_page(
			'lean-csns-settings',
			__( 'Settings', 'lean-cart-share-and-save' ),
			__( 'Settings', 'lean-cart-share-and-save' ),
			'manage_options',
			'lean-csns-settings',
			[ $this, 'settings_page_cb' ]
		);
	}

	/**
	 * Settings page callback — renders the lex settings page
	 */
	public function settings_page_cb() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'lean-cart-share-and-save' ) );
		}

		if ( $this->lex_settings ) {
			$this->lex_settings->menu->renderPage();
		} else {
			echo '<div class="wrap"><p>' . esc_html__( 'Settings framework not available.', 'lean-cart-share-and-save' ) . '</p></div>';
		}
	}

	/**
	 * Add plugin action links
	 */
	public function add_plugin_action_links( $links ) {
		$quick_settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=lean-csns-settings' ) ) . '">' . esc_html__( 'Settings', 'lean-cart-share-and-save' ) . '</a>';
		return array_merge( [ 'settings' => $quick_settings_link ], $links );
	}

	/**
	 * Suppress admin notices on plugin pages
	 */
	public function suppress_admin_notices() {
		if ( $this->is_plugin_admin_page() ) {
			remove_all_actions( 'admin_notices' );
			remove_all_actions( 'all_admin_notices' );
		}
	}

	/**
	 * Check if we are on our plugin's admin page
	 * Public so it can be passed as page_check_callback to lex settings
	 *
	 * @return bool
	 */
	public function is_plugin_admin_page() {
		$current_screen = get_current_screen();

		if ( ! $current_screen ) {
			return false;
		}

		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		return $current_screen->id === 'toplevel_page_lean-csns-settings'
			|| $page === 'lean-csns-settings';
	}
}

// Initialize singleton instance
Menu::get_instance();
