<?php
/**
 * Admin functionality.
 *
 * Registers admin menus, enqueues assets, handles product metabox,
 * and renders the tab-based admin interface.
 *
 * @package Waitlytics
 */

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

/**
 * Class WTLY_Admin
 */
class WTLY_Admin {

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

		// Product edit metabox.
		add_filter( 'woocommerce_product_data_tabs', array( $this, 'add_product_data_tab' ) );
		add_action( 'woocommerce_product_data_panels', array( $this, 'render_product_data_panel' ) );
		add_action( 'woocommerce_process_product_meta', array( $this, 'save_product_meta' ) );

		// Plugin action links on Plugins page.
		add_filter( 'plugin_action_links_' . WTLY_PLUGIN_BASENAME, array( $this, 'add_plugin_action_links' ) );
	}

	/**
	 * Register submenu page under WooCommerce.
	 */
	public function register_menu() {
		add_submenu_page(
			'woocommerce',
			__( 'Waitlytics', 'waitlytics' ),
			__( 'Waitlytics', 'waitlytics' ),
			'manage_woocommerce',
			'waitlytics',
			array( $this, 'render_admin_page' )
		);
	}

	/**
	 * Enqueue admin CSS and JS only on our plugin pages.
	 *
	 * @param string $hook Current admin page hook suffix.
	 */
	public function enqueue_assets( $hook ) {
		// Only load on our plugin pages and WC product edit.
		$is_our_page = ( false !== strpos( $hook, 'waitlytics' ) );
		$is_product  = in_array( $hook, array( 'post.php', 'post-new.php' ), true );

		if ( ! $is_our_page && ! $is_product ) {
			return;
		}

		wp_enqueue_style(
			'wtly-admin',
			WTLY_PLUGIN_URL . 'admin/css/wtly-admin.css',
			array(),
			WTLY_VERSION
		);

		wp_enqueue_script(
			'wtly-admin',
			WTLY_PLUGIN_URL . 'admin/js/wtly-admin.js',
			array( 'jquery' ),
			WTLY_VERSION,
			true
		);

		wp_localize_script( 'wtly-admin', 'wtlyData', array(
			'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
			'nonce'     => wp_create_nonce( 'wtly_admin_nonce' ),
			'restUrl'   => esc_url_raw( rest_url( 'wtly/v1/' ) ),
			// CSV export is handled on admin_init (WTLY_CSV_Export::handle_export_request),
			// not via REST — build a nonced admin URL the handler will recognise.
			'exportUrl' => wp_nonce_url(
				admin_url( 'admin.php?page=waitlytics&wtly_export_csv=1' ),
				'wtly_export_csv'
			),
			'i18n'      => array(
				'confirm'      => esc_html__( 'Are you sure?', 'waitlytics' ),
				'running'      => esc_html__( 'Running...', 'waitlytics' ),
				'runForecast'  => esc_html__( 'Run Forecast Now', 'waitlytics' ),
				'error'        => esc_html__( 'An error occurred. Please try again.', 'waitlytics' ),
				'exported'     => esc_html__( 'CSV exported successfully.', 'waitlytics' ),
				'deleted'      => esc_html__( 'Subscriber deleted.', 'waitlytics' ),
				'saving'       => esc_html__( 'Saving...', 'waitlytics' ),
				'saved'        => esc_html__( 'Settings saved.', 'waitlytics' ),
				'testing'      => esc_html__( 'Testing...', 'waitlytics' ),
				'testSuccess'  => esc_html__( 'Connection successful!', 'waitlytics' ),
				'testFailed'   => esc_html__( 'Connection failed.', 'waitlytics' ),
			),
		) );
	}

	/**
	 * Render the main admin page with tab navigation.
	 */
	public function render_admin_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'waitlytics' ) );
		}

		// The tab key only selects which read-only admin view to render; it mutates
		// nothing, so nonce verification is not applicable.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'dashboard';
		$tabs        = $this->get_tabs();

		// Validate tab.
		if ( ! array_key_exists( $current_tab, $tabs ) ) {
			$current_tab = 'dashboard';
		}

		?>
		<div class="wrap wtly-wrap">
			<h1 class="wtly-page-title">
				<?php esc_html_e( 'Waitlytics', 'waitlytics' ); ?>
				<span class="wtly-version"><?php echo esc_html( 'v' . WTLY_VERSION ); ?></span>
				<?php
				/**
				 * Fires after the admin page title. The Pro build uses this
				 * to render the PRO badge and license status.
				 */
				do_action( 'wtly_admin_page_header' );
				?>
			</h1>

			<nav class="nav-tab-wrapper wtly-nav-tabs">
				<?php foreach ( $tabs as $tab_key => $tab_label ) : ?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=waitlytics&tab=' . $tab_key ) ); ?>"
					   class="nav-tab <?php echo esc_attr( $current_tab === $tab_key ? 'nav-tab-active' : '' ); ?>">
						<?php echo esc_html( $tab_label ); ?>
					</a>
				<?php endforeach; ?>
			</nav>

			<div class="wtly-tab-content">
				<?php $this->render_tab( $current_tab ); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Get available admin tabs.
	 *
	 * @return array Tab key => label pairs.
	 */
	private function get_tabs() {
		$tabs = array(
			'dashboard'   => __( 'Dashboard', 'waitlytics' ),
			'subscribers' => __( 'Subscribers', 'waitlytics' ),
			'settings'    => __( 'Settings', 'waitlytics' ),
		);

		/**
		 * Filter the available admin tabs. The Pro build registers its own
		 * tabs here; the free build ships no Pro tab references at all.
		 *
		 * @param array $tabs Tab key => label pairs.
		 */
		return apply_filters( 'wtly_admin_tabs', $tabs );
	}

	/**
	 * Render the content for a specific tab.
	 *
	 * @param string $tab Current tab key.
	 */
	private function render_tab( $tab ) {
		switch ( $tab ) {
			case 'dashboard':
				include WTLY_PLUGIN_DIR . 'admin/partials/wtly-dashboard.php';
				break;
			case 'subscribers':
				include WTLY_PLUGIN_DIR . 'admin/partials/wtly-subscribers.php';
				break;
			case 'settings':
				include WTLY_PLUGIN_DIR . 'admin/partials/wtly-settings.php';
				break;
			default:
				/**
				 * Fires for admin tabs this class does not render itself.
				 * The Pro build uses this to render its tab views. Only
				 * tabs registered via wtly_admin_tabs can reach here —
				 * unknown tabs already fell back to the dashboard.
				 *
				 * @param string $tab Current tab key.
				 */
				do_action( 'wtly_admin_render_tab', $tab );
				break;
		}
	}

	/**
	 * Add Waitlytics tab to WooCommerce product data panel.
	 *
	 * @param array $tabs Existing product data tabs.
	 * @return array Modified tabs.
	 */
	public function add_product_data_tab( $tabs ) {
		$tabs['wtly'] = array(
			'label'    => __( 'Waitlytics', 'waitlytics' ),
			'target'   => 'wtly_product_data',
			'class'    => array(),
			'priority' => 90,
		);
		return $tabs;
	}

	/**
	 * Render product data panel content.
	 */
	public function render_product_data_panel() {
		global $post;

		$product_id   = $post->ID;
		$disable_form = get_post_meta( $product_id, '_wtly_disable_notify_form', true );
		$custom_msg   = get_post_meta( $product_id, '_wtly_custom_email_message', true );
		$subscriber   = new WTLY_Subscriber();
		$active_count = $subscriber->count_by_product( $product_id );

		// Get notified count.
		global $wpdb;
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
		$notified_count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->prefix}wtly_subscribers WHERE product_id = %d AND status = %s",
				$product_id,
				'notified'
			)
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter

		wp_nonce_field( 'wtly_save_product_meta', 'wtly_product_meta_nonce' );
		?>
		<div id="wtly_product_data" class="panel woocommerce_options_panel">
			<div class="options_group">
				<?php
				woocommerce_wp_checkbox( array(
					'id'          => '_wtly_disable_notify_form',
					'label'       => __( 'Disable "Notify Me" form', 'waitlytics' ),
					'description' => __( 'Hide the notification form on this product page.', 'waitlytics' ),
					'value'       => $disable_form,
				) );
				?>
			</div>

			<div class="options_group">
				<?php
				woocommerce_wp_textarea_input( array(
					'id'          => '_wtly_custom_email_message',
					'label'       => __( 'Custom email message', 'waitlytics' ),
					'description' => __( 'Optional override for the notification email body for this product.', 'waitlytics' ),
					'value'       => $custom_msg,
					'desc_tip'    => true,
				) );
				?>
			</div>

			<div class="options_group">
				<p class="form-field">
					<label><?php esc_html_e( 'Subscriber Info', 'waitlytics' ); ?></label>
					<span class="wtly-product-stats">
						<?php
						printf(
							/* translators: %d: number of active subscribers */
							esc_html__( 'Active subscribers: %d', 'waitlytics' ),
							absint( $active_count )
						);
						?>
						<br>
						<?php
						printf(
							/* translators: %d: number of notified subscribers */
							esc_html__( 'Total notified: %d', 'waitlytics' ),
							absint( $notified_count )
						);
						?>
						<br>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=waitlytics&tab=subscribers' ) ); ?>">
							<?php esc_html_e( 'View Subscribers', 'waitlytics' ); ?> &rarr;
						</a>
					</span>
				</p>
			</div>

			<?php
			/**
			 * Fires at the end of the product data panel. The Pro build uses
			 * this to render the forecast data block.
			 *
			 * @param int $product_id Product post ID.
			 */
			do_action( 'wtly_product_data_panel', $product_id );
			?>
		</div>
		<?php
	}

	/**
	 * Save per-product meta on product save.
	 *
	 * @param int $post_id Product post ID.
	 */
	public function save_product_meta( $post_id ) {
		if ( ! isset( $_POST['wtly_product_meta_nonce'] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wtly_product_meta_nonce'] ) ), 'wtly_save_product_meta' )
		) {
			return;
		}

		if ( ! current_user_can( 'edit_product', $post_id ) ) {
			return;
		}

		// Disable notify form checkbox.
		$disable_form = isset( $_POST['_wtly_disable_notify_form'] ) ? 'yes' : 'no';
		update_post_meta( $post_id, '_wtly_disable_notify_form', $disable_form );

		// Custom email message.
		$custom_msg = isset( $_POST['_wtly_custom_email_message'] )
			? wp_kses_post( wp_unslash( $_POST['_wtly_custom_email_message'] ) )
			: '';
		update_post_meta( $post_id, '_wtly_custom_email_message', $custom_msg );
	}

	/**
	 * Add Settings link on the Plugins page.
	 *
	 * @param array $links Existing plugin action links.
	 * @return array Modified links.
	 */
	public function add_plugin_action_links( $links ) {
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=waitlytics&tab=settings' ) ),
			esc_html__( 'Settings', 'waitlytics' )
		);
		array_unshift( $links, $settings_link );
		return $links;
	}
}
