<?php
/**
 * Admin interface logic for the plugin.
 * 
 * @package WPStaticHTMLPages
 */

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

class WPSH_Admin {

	/**
	 * Initialize admin hooks.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_bar_menu', array( $this, 'add_toolbar_button' ), 100 );
		
		add_filter( 'post_row_actions', array( $this, 'add_row_actions' ), 10, 2 );
		add_filter( 'page_row_actions', array( $this, 'add_row_actions' ), 10, 2 );
		
		add_action( 'admin_post_wpsh_manual_regenerate', array( $this, 'handle_manual_regenerate' ) );
		add_action( 'admin_notices', array( $this, 'display_notices' ) );
		add_filter( 'plugin_action_links_' . plugin_basename( WPSH_PATH . 'moon-static-html-pages.php' ), array( $this, 'add_plugin_action_links' ) );
	}

	/**
	 * Add the admin menu page.
	 */
	public function add_menu_page() {
		add_menu_page(
			'Moon Static HTML',
			'Moon Static HTML',
			'manage_options',
			'moon-static-html-pages',
			array( $this, 'render_admin_page' ),
			'dashicons-html',
			100
		);
	}

	/**
	 * Enqueue CSS and JS assets.
	 */
	public function enqueue_assets( $hook ) {
		// If on frontend, ensure we have permission and the admin bar is active.
		if ( ! is_admin() ) {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}
		} else {
			// If in admin, use original screen checks.
			$screens = array( 'edit.php', 'post.php', 'post-new.php' );
			if ( false === strpos( $hook, 'moon-static-html-pages' ) && ! in_array( $hook, $screens, true ) ) {
				return;
			}
		}

		$lib_url   = plugin_dir_url( dirname( __FILE__ ) ) . 'assets/lib/';
		$assets_url = plugin_dir_url( dirname( __FILE__ ) ) . 'assets/';

		// Third-party libraries (Local).
		wp_enqueue_style( 'toastr-css', $lib_url . 'toastr.min.css', array(), '2.1.4' );
		wp_enqueue_script( 'toastr-js', $lib_url . 'toastr.min.js', array( 'jquery' ), '2.1.4', true );
		wp_enqueue_style( 'sweetalert2-css', $lib_url . 'sweetalert2.min.css', array(), '11.0.0' );
		wp_enqueue_script( 'sweetalert2-js', $lib_url . 'sweetalert2.all.min.js', array(), '11.0.0', true );

		// Plugin assets.
		// Ensure Dashicons are available on this custom admin page.
		wp_enqueue_style( 'dashicons' );
		wp_enqueue_style( 'wpsh-admin-css', $assets_url . 'css/admin.css', array(), WPSH_VERSION );
		
		// jQuery DataTables.
		wp_enqueue_style( 'datatables-css', $assets_url . 'css/jquery.dataTables.min.css', array(), '1.10.25' );
		wp_enqueue_script( 'datatables-js', $assets_url . 'js/jquery.dataTables.min.js', array( 'jquery' ), '1.10.25', true );

		wp_enqueue_script( 'wpsh-admin-js', $assets_url . 'js/admin.js', array( 'jquery', 'toastr-js', 'datatables-js' ), WPSH_VERSION, true );

		$nonce_auto_refresh_enabled = (bool) get_option( 'wpsh_nonce_auto_refresh_enabled', true );
		$nonce_auto_refresh_interval_ms = (int) get_option( 'wpsh_nonce_auto_refresh_interval_ms', 5 * MINUTE_IN_SECONDS * 1000 );
		$nonce_auto_refresh_enabled = (bool) apply_filters( 'wpsh_nonce_auto_refresh_enabled', $nonce_auto_refresh_enabled );
		$nonce_auto_refresh_interval_ms = (int) apply_filters( 'wpsh_nonce_auto_refresh_interval_ms', $nonce_auto_refresh_interval_ms );
		$nonce_auto_refresh_interval_ms = max( 60 * 1000, $nonce_auto_refresh_interval_ms );

		wp_localize_script( 'wpsh-admin-js', 'wpsh_admin_vars', array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonces'   => array(
				'generate' => wp_create_nonce( 'wpsh_generate_all' ),
				'clear'    => wp_create_nonce( 'wpsh_clear_cache' ),
				'redir'    => wp_create_nonce( 'wpsh_redir_nonce' ),
				'settings' => wp_create_nonce( 'wpsh_settings_nonce' ),
				'htaccess' => wp_create_nonce( 'wpsh_update_htaccess' ),
			),
			'nonce_auto_refresh' => array(
				'enabled'     => $nonce_auto_refresh_enabled,
				'interval_ms' => $nonce_auto_refresh_interval_ms,
			),
		) );

		wp_add_inline_script( 'toastr-js', "
			toastr.options = { 'closeButton': true, 'progressBar': true, 'positionClass': 'toast-top-right', 'timeOut': '3000' };
		" );
	}

	/**
	 * Render the main admin page.
	 */
	public function render_admin_page() {
		include plugin_dir_path( __FILE__ ) . 'views/admin-main.php';
	}

	/**
	 * Add "Regenerate" button to admin toolbar.
	 */
	public function add_toolbar_button( $admin_bar ) {
		if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$url = false;
		$is_excluded = false;

		if ( is_admin() ) {
			$screen = get_current_screen();
			if ( $screen && $screen->base === 'post' ) {
				global $post;
				if ( $post && in_array( $post->post_type, get_post_types( array( 'public' => true ) ) ) ) {
					$url = get_permalink( $post->ID );
					$is_excluded = WPSH_Helper::is_excluded( $post->ID );
					if ( $post->post_status !== 'publish' ) {
						$url = false;
					}
				}
			}
		} else {
			// On frontend.
			if ( is_singular() ) {
				$post_id = get_queried_object_id();
				if ( $post_id ) {
					if ( get_post_status( $post_id ) !== 'publish' ) {
						$url = false;
					} else {
						$is_excluded = WPSH_Helper::is_excluded( $post_id );
					}
				}
			} elseif ( is_category() || is_tag() || is_tax() ) {
				$term = get_queried_object();
				if ( $term && isset( $term->taxonomy ) ) {
					$url = get_term_link( $term );
					$is_excluded = WPSH_Helper::is_taxonomy_excluded( $term->taxonomy );
				}
			} elseif ( is_front_page() || is_home() ) {
				$url = home_url( '/' );
			}
		}

		if ( $url ) {
			$admin_bar->add_node( array(
				'id'    => 'wpsh-regenerate-node',
				'title' => '<span class="ab-icon dashicons-html"></span> Regenerate Static',
				'href'  => $is_excluded ? '#' : admin_url( 'admin-post.php?action=wpsh_manual_regenerate&url=' . urlencode( $url ) . '&_wpnonce=' . wp_create_nonce( 'wpsh_manual_regen' ) ),
				'meta'  => array( 
					'title' => 'Refresh static HTML for this page',
					'class' => $is_excluded ? 'wpsh-regen-excluded' : 'wpsh-regen-link'
				)
			) );
		}
	}

	/**
	 * Add "Regenerate Static" link to post/page rows.
	 */
	public function add_row_actions( $actions, $post ) {
		if ( ! current_user_can( 'manage_options' ) ) return $actions;
		if ( ! in_array( $post->post_type, get_post_types( array( 'public' => true ) ) ) ) return $actions;
		if ( $post->post_status !== 'publish' ) return $actions;

		$is_excluded = WPSH_Helper::is_excluded( $post->ID );
		$url = get_permalink( $post->ID );
		$regen_url = admin_url( 'admin-post.php?action=wpsh_manual_regenerate&url=' . urlencode( $url ) . '&_wpnonce=' . wp_create_nonce( 'wpsh_manual_regen' ) );

		$actions['wpsh_regen'] = sprintf(
			'<a href="%s" aria-label="%s" class="%s">%s</a>',
			$is_excluded ? '#' : $regen_url,
			esc_attr( 'Regenerate Static HTML' ),
			$is_excluded ? 'wpsh-regen-excluded' : 'wpsh-regen-link',
			'Regenerate Static'
		);

		return $actions;
	}

	/**
	 * Handle manual regeneration requests.
	 */
	public function handle_manual_regenerate() {
		check_admin_referer( 'wpsh_manual_regen' );
		if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Permission denied' );

		$url = isset( $_GET['url'] ) ? esc_url_raw( wp_unslash( $_GET['url'] ) ) : false;
		if ( $url ) {
			$post_id = url_to_postid( $url );
			if ( $post_id ) {
				if ( get_post_status( $post_id ) !== 'publish' ) {
					wp_die( 'Cannot generate static HTML for non-published content.' );
				}
				if ( WPSH_Helper::is_excluded( $post_id ) ) {
					wp_die( 'This post is excluded from static HTML generation.' );
				}
			} else {
				// Check for taxonomy exclusion if not a post.
				$path = wp_parse_url( $url, PHP_URL_PATH );
				$term = false;
				
				// Try to find if it's a term URL.
				foreach ( get_taxonomies( array( 'public' => true ), 'names' ) as $taxonomy ) {
					$t = get_term_by( 'slug', basename( rtrim( $path, '/' ) ), $taxonomy );
					if ( $t ) {
						$term = $t;
						break;
					}
				}
				
				if ( $term && WPSH_Helper::is_taxonomy_excluded( $term->taxonomy ) ) {
					wp_die( 'This taxonomy is excluded from static HTML generation.' );
				}
			}

			$core = new WPSH_Core();
			$core->generate_html_by_url( $url );
			
			$redirect = wp_get_referer() ?: admin_url( 'admin.php?page=moon-static-html-pages' );
			$redirect = add_query_arg( 'wpsh_msg', 'regenerated', $redirect );
			wp_safe_redirect( $redirect );
			exit;
		}
		wp_die( 'Invalid URL' );
	}

	/**
	 * Display admin notices.
	 */
	public function display_notices() {
		// Nonce check not required for displaying a status message via GET.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['wpsh_msg'] ) && sanitize_text_field( wp_unslash( $_GET['wpsh_msg'] ) ) === 'regenerated' ) {
			echo '<div class="notice notice-success is-dismissible"><p>Static HTML has been regenerated successfully.</p></div>';
		}
	}
	
	/**
	 * Add settings link to plugin action links.
	 */
	public function add_plugin_action_links( $links ) {
		$settings_link = '<a href="' . admin_url( 'admin.php?page=moon-static-html-pages' ) . '">' . __( 'Settings', 'moon-static-html-pages' ) . '</a>';
		array_unshift( $links, $settings_link );
		return $links;
	}
}
