<?php
/**
 * Admin bootstrap — menus, asset loading, page rendering.
 *
 * @package PrivexPasswordProtect
 */

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

/**
 * Class PPMSTR_Admin
 */
class PPMSTR_Admin {

	/**
	 * The page hook suffix returned by add_menu_page / add_submenu_page.
	 *
	 * @var array
	 */
	private $page_hooks = array();

	/**
	 * Register hooks.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Register admin menu and submenu pages.
	 */
	public function register_menu() {

		$this->page_hooks['dashboard'] = add_menu_page(
			__( 'Privex Password Protect', 'privex-password-protect' ),
			__( 'Pass Protect', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-dashboard',
			array( $this, 'render_dashboard' ),
			'dashicons-lock',
			30
		);

		// Rename the first submenu so it shows "Dashboard" instead of duplicating the parent label.
		$this->page_hooks['dashboard'] = add_submenu_page(
			'ppmstr-dashboard',
			__( 'Dashboard — Privex Password Protect', 'privex-password-protect' ),
			__( 'Dashboard', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-dashboard',
			array( $this, 'render_dashboard' )
		);

		$this->page_hooks['settings'] = add_submenu_page(
			'ppmstr-dashboard',
			__( 'Settings — Privex Password Protect', 'privex-password-protect' ),
			__( 'Settings', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-settings',
			array( $this, 'render_settings' )
		);

		$this->page_hooks['passwords'] = add_submenu_page(
			'ppmstr-dashboard',
			__( 'Passwords — Privex Password Protect', 'privex-password-protect' ),
			__( 'Passwords', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-passwords',
			array( $this, 'render_passwords' )
		);

		$this->page_hooks['security'] = add_submenu_page(
			'ppmstr-dashboard',
			__( 'Security — Privex Password Protect', 'privex-password-protect' ),
			__( 'Security', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-security',
			array( $this, 'render_security' )
		);

		$this->page_hooks['templates'] = add_submenu_page(
			'ppmstr-dashboard',
			__( 'Templates — Privex Password Protect', 'privex-password-protect' ),
			__( 'Templates', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-templates',
			array( $this, 'render_templates' )
		);

		$submenus = array(
			'analytics'    => __( 'Analytics', 'privex-password-protect' ),
		);

		foreach ( $submenus as $slug => $label ) {
			$this->page_hooks[ $slug ] = add_submenu_page(
				'ppmstr-dashboard',
				/* translators: %s: Submenu label */
				sprintf( esc_html__( '%s — Privex Password Protect', 'privex-password-protect' ), $label ),
				$label,
				'manage_options',
				'ppmstr-' . $slug,
				( 'analytics' === $slug ) ? array( $this, 'render_analytics' ) : array( $this, 'render_placeholder' )
			);
		}

		// Hidden page for the template builder (no menu item).
		$this->page_hooks['template-builder'] = add_submenu_page(
			null, // Hidden — not shown in menu.
			__( 'Template Builder — Privex Password Protect', 'privex-password-protect' ),
			__( 'Template Builder', 'privex-password-protect' ),
			'manage_options',
			'ppmstr-template-builder',
			array( $this, 'render_template_builder' )
		);
	}

	/**
	 * Enqueue admin assets only on our own pages.
	 *
	 * @param string $hook_suffix Current admin page hook suffix.
	 */
	public function enqueue_assets( $hook_suffix ) {
		if ( ! $this->is_plugin_page( $hook_suffix ) ) {
			return;
		}

		wp_enqueue_style(
			'ppmstr-admin',
			PPMSTR_PLUGIN_URL . 'assets/css/ppmstr-admin.css',
			array(),
			PPMSTR_VERSION
		);

		wp_enqueue_script(
			'ppmstr-admin',
			PPMSTR_PLUGIN_URL . 'assets/js/ppmstr-admin.js',
			array( 'jquery' ),
			PPMSTR_VERSION,
			true
		);

		wp_localize_script(
			'ppmstr-admin',
			'ppmstrAdmin',
			array(
				'ajaxUrl'      => esc_url( admin_url( 'admin-ajax.php' ) ),
				'nonce'        => wp_create_nonce( 'ppmstr_admin_nonce' ),
				'templatesUrl' => esc_url( admin_url( 'admin.php?page=ppmstr-templates' ) ),
				'isPro'        => ( function_exists( 'ppp_fs' ) && ppp_fs()->can_use_premium_code__premium_only() ) ? true : false,
				'upgradeUrl'   => function_exists( 'ppp_fs' ) ? esc_url( ppp_fs()->get_upgrade_url() ) : '#',
				'i18n'         => array(
					'proTitle'   => esc_html__( 'PRO Feature', 'privex-password-protect' ),
					'proMessage' => esc_html__( 'This feature is available in the PRO version. Upgrade to unlock it.', 'privex-password-protect' ),
					'upgradeCta' => esc_html__( '⚡ Upgrade to PRO', 'privex-password-protect' ),
				),
			)
		);

		// PRO upgrade tooltip — shown on all plugin pages for non-PRO users.
		wp_enqueue_script(
			'ppmstr-pro-tooltip',
			PPMSTR_PLUGIN_URL . 'assets/js/ppmstr-pro-tooltip.js',
			array( 'ppmstr-admin' ), // Depends on ppmstr-admin so ppmstrAdmin object is already set.
			PPMSTR_VERSION,
			true
		);

		// Security page assets.
		if ( isset( $this->page_hooks['security'] ) && $hook_suffix === $this->page_hooks['security'] ) {
			wp_enqueue_script(
				'ppmstr-security-page',
				PPMSTR_PLUGIN_URL . 'assets/js/ppmstr-security-page.js',
				array(),
				PPMSTR_VERSION,
				true
			);
		}

		// Settings page assets.
		if ( isset( $this->page_hooks['settings'] ) && $hook_suffix === $this->page_hooks['settings'] ) {
			wp_enqueue_script(
				'ppmstr-settings-page',
				PPMSTR_PLUGIN_URL . 'assets/js/ppmstr-settings-page.js',
				array(),
				PPMSTR_VERSION,
				true
			);
		}

		// Builder-specific assets.
		if ( isset( $this->page_hooks['template-builder'] ) && $hook_suffix === $this->page_hooks['template-builder'] ) {
			wp_enqueue_media();

			wp_enqueue_style(
				'ppmstr-builder',
				PPMSTR_PLUGIN_URL . 'assets/css/ppmstr-template-builder.css',
				array( 'ppmstr-admin' ),
				PPMSTR_VERSION
			);

			wp_enqueue_script(
				'ppmstr-builder',
				PPMSTR_PLUGIN_URL . 'assets/js/ppmstr-template-builder.js',
				array( 'ppmstr-admin' ),
				PPMSTR_VERSION,
				true
			);

			$ppmstr_edit_id  = isset( $_GET['template_id'] ) ? sanitize_key( wp_unslash( $_GET['template_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$ppmstr_preset   = isset( $_GET['preset'] ) ? sanitize_key( wp_unslash( $_GET['preset'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$ppmstr_edit_tpl = null;

			if ( $ppmstr_edit_id ) {
				$ppmstr_edit_tpl = PPMSTR_Template_Builder::get_template( $ppmstr_edit_id );
			} elseif ( $ppmstr_preset ) {
				$ppmstr_edit_tpl = PPMSTR_Template_Builder::get_template( $ppmstr_preset );
				$ppmstr_edit_id  = '';
			}

			// Compute animation CSS for the builder canvas preview.
			$ppmstr_anim_css  = '';
			$ppmstr_anim_slug = 'none';
			if ( $ppmstr_edit_tpl ) {
				$ppmstr_anim_slug   = isset( $ppmstr_edit_tpl['global']['animation'] ) ? $ppmstr_edit_tpl['global']['animation'] : 'none';
				$ppmstr_anim_accent = '';
				foreach ( isset( $ppmstr_edit_tpl['blocks'] ) ? $ppmstr_edit_tpl['blocks'] : array() as $_ppmstr_b ) {
					if ( 'submit_button' === ( isset( $_ppmstr_b['type'] ) ? $_ppmstr_b['type'] : '' ) ) {
						$ppmstr_anim_accent = isset( $_ppmstr_b['settings']['bgcolor'] ) ? $_ppmstr_b['settings']['bgcolor'] : '';
						break;
					}
				}
				if ( 'none' !== $ppmstr_anim_slug ) {
					$ppmstr_anim_css = PPMSTR_Template_Builder::get_animation_css(
						$ppmstr_anim_slug,
						isset( $ppmstr_edit_tpl['global'] ) ? $ppmstr_edit_tpl['global'] : array(),
						$ppmstr_anim_accent
					);
				}
			}

			$ppmstr_free_template_ids = array( 'preset_minimal', 'preset_minimal_dark' );
			$ppmstr_is_free_mode      = false;
			$ppmstr_is_pro_template   = false;
			$ppmstr_has_pro           = function_exists( 'ppp_fs' ) && ppp_fs()->can_use_premium_code__premium_only();

			if ( $ppmstr_edit_tpl ) {
				// It's a preset edit — check if it's free or PRO.
				$ppmstr_tpl_id = $ppmstr_edit_id ?: $ppmstr_preset;
				if ( in_array( $ppmstr_tpl_id, $ppmstr_free_template_ids, true ) ) {
					$ppmstr_is_free_mode = ! $ppmstr_has_pro;
				} else {
					$ppmstr_is_pro_template = ! $ppmstr_has_pro;
				}
			} else {
				// New template creation — PRO only.
				$ppmstr_is_pro_template = ! $ppmstr_has_pro;
			}

			$settings = get_option( 'ppmstr_settings', array() );

			$builder_data = array(
				'editId'        => $ppmstr_edit_id,
				'editTpl'       => $ppmstr_edit_tpl,
				'animationCSS'  => $ppmstr_anim_css,
				'animationSlug' => $ppmstr_anim_slug,
				'isFreeMode'    => $ppmstr_is_free_mode,
				'isProTemplate' => $ppmstr_is_pro_template,
				'defaults'      => array(
					'headline'    => isset( $settings['form_headline'] ) ? $settings['form_headline'] : '',
					'description' => isset( $settings['form_description'] ) ? $settings['form_description'] : '',
					'placeholder' => isset( $settings['form_placeholder'] ) ? $settings['form_placeholder'] : '',
					'buttonText'  => isset( $settings['form_button_text'] ) ? $settings['form_button_text'] : '',
				),
			);

			wp_add_inline_script(
				'ppmstr-builder',
				'var ppmstrBuilderData = ' . wp_json_encode( $builder_data ) . ';',
				'before'
			);
		}
	}

	/* ------------------------------------------------------------------
	 * Page renderers — each includes the common layout that wraps
	 * a header + sidebar + the page-specific view.
	 * ----------------------------------------------------------------*/

	/**
	 * Render the Dashboard page.
	 */
	public function render_dashboard() {
		$this->render_page( 'dashboard' );
	}

	/**
	 * Render the Settings page.
	 */
	public function render_settings() {
		$this->render_page( 'settings' );
	}

	/**
	 * Render a "coming soon" placeholder for unbuilt pages.
	 */
	public function render_placeholder() {
		$this->render_page( 'placeholder' );
	}

	/**
	 * Render the Analytics dashboard.
	 */
	public function render_analytics() {
		$this->render_page( 'analytics' );
	}

	/**
	 * Render the Passwords page.
	 */
	public function render_passwords() {
		$this->render_page( 'passwords' );
	}

	/**
	 * Render the Security page.
	 */
	public function render_security() {
		$this->render_page( 'security' );
	}

	/**
	 * Render the Templates page.
	 */
	public function render_templates() {
		$this->render_page( 'templates' );
	}

	/**
	 * Render the Template Builder page.
	 */
	public function render_template_builder() {
		$this->render_page( 'template-builder' );
	}

	/* ------------------------------------------------------------------
	 * Helpers
	 * ----------------------------------------------------------------*/

	/**
	 * Render an admin page inside the shared layout.
	 *
	 * @param string $page Page slug (matches file name in admin/views/).
	 */
	private function render_page( $page ) {
		$current_page = sanitize_key( $page );
		$view_file    = PPMSTR_PLUGIN_DIR . 'admin/views/page-' . $current_page . '.php';

		if ( ! file_exists( $view_file ) ) {
			$view_file = PPMSTR_PLUGIN_DIR . 'admin/views/page-placeholder.php';
		}

		include PPMSTR_PLUGIN_DIR . 'admin/views/layout.php';
	}

	/**
	 * Check whether the current admin screen belongs to this plugin.
	 *
	 * @param string $hook_suffix Current admin page hook suffix.
	 * @return bool
	 */
	private function is_plugin_page( $hook_suffix ) {
		return in_array( $hook_suffix, $this->page_hooks, true );
	}
}
