<?php
/**
 * Admin Menu Management.
 *
 * This file contains the Admin_Menu class which is responsible for creating
 * and managing admin menus for the Postomatic plugin.
 *
 * @package Postomatic
 * @subpackage Admin
 * @since      1.0.0
 */

namespace Postomatic\Admin;

use Postomatic\Constants;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class responsible for creating and managing admin menus.
 */
class Admin_Menu {

	/**
	 * Initialize the admin menu.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
	}

	/**
	 * Register all admin menus and submenus.
	 */
	public function register_menu() {
		// Main plugin menu.
		add_menu_page(
			__( 'Postomatic', 'postomatic' ),
			__( 'Postomatic', 'postomatic' ),
			'manage_options',
			Constants::PAGE_MAIN,
			array( $this, 'render_main_page' ), // Callback function.
			'dashicons-text', // Choose an appropriate dashicon.
			6
		);

		// Submenu pages - these will appear under the main menu.
		add_submenu_page(
			'postomatic', // Parent slug.
			Constants::PAGE_MAIN_TITLE, // Page title.
			Constants::PAGE_MAIN_TITLE, // Menu title.
			'manage_options', // Capability.
			Constants::PAGE_MAIN, // Menu slug (same as parent to override).
			array( $this, 'render_main_page' ) // Callback function.
		);

		add_submenu_page(
			'postomatic',
			Constants::PAGE_MEMBERSHIP_TITLE,
			Constants::PAGE_MEMBERSHIP_TITLE,
			'manage_options',
			Constants::PAGE_MEMBERSHIP,
			array( $this, 'render_membership_page' )
		);

		add_submenu_page(
			'postomatic',
			Constants::PAGE_ADD_CREDIT_TITLE,
			Constants::PAGE_ADD_CREDIT_TITLE,
			'manage_options',
			Constants::PAGE_ADD_CREDIT,
			array( $this, 'render_credit_page' )
		);

		add_submenu_page(
			'postomatic',
			Constants::PAGE_SUPPORT_TITLE,
			Constants::PAGE_SUPPORT_TITLE,
			'manage_options',
			Constants::PAGE_SUPPORT,
			array( $this, 'render_support_page' )
		);

		add_submenu_page(
			'postomatic',
			Constants::PAGE_AUTOPILOT_TITLE,
			Constants::PAGE_AUTOPILOT_TITLE,
			'manage_options',
			Constants::PAGE_AUTOPILOT,
			array( $this, 'render_autopilot_page' )
		);
	}

	/**
	 * Render the main plugin page.
	 */
	public function render_main_page() {
		$this->render_template( 'main-page.php' );
	}

	/**
	 * Check if the current host is localhost but not mywordpress.local
	 *
	 * @return bool True if the host is localhost but not mywordpress.local, false otherwise
	 */
	private function is_restricted_localhost() {
		$host        = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
		$server_name = isset( $_SERVER['SERVER_NAME'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) ) : '';

		// Allow mywordpress.local.
		if ( 'mywordpress.local' === $host || 'mywordpress.local' === $server_name ) {
			return false;
		}

		// Check for localhost patterns.
		$localhost_patterns = array(
			'localhost',
			'127.0.0.1',
			'::1',
			'.local',
			'.test',
			'.localhost',
			'.dev',
		);

		foreach ( $localhost_patterns as $pattern ) {
			if ( strpos( $host, $pattern ) !== false || strpos( $server_name, $pattern ) !== false ) {
				return true;
			}
		}

		// Check for private IP ranges.
		$remote_addr = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
		if ( $remote_addr ) {
			// Check for IPv4 private ranges.
			if ( filter_var( $remote_addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
				$private_ipv4_ranges = array(
					'/^10\./',          // 10.0.0.0/8.
					'/^172\.(1[6-9]|2[0-9]|3[0-1])\./', // 172.16.0.0/12.
					'/^192\.168\./',     // 192.168.0.0/16.
				);

				foreach ( $private_ipv4_ranges as $range ) {
					if ( preg_match( $range, $remote_addr ) ) {
						return true;
					}
				}
			}

			// Check for IPv6 localhost.
			if ( '::1' === $remote_addr ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Helper function to render templates.
	 *
	 * @param string $template The template file name.
	 */
	private function render_template( $template ) {
		// Check if accessing from localhost (except mywordpress.local).
		if ( $this->is_restricted_localhost() ) {
			?>
			<div style="
				font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
				max-width: 620px;
				margin: 40px 20px;
				padding: 32px 36px;
				background: #fff;
				border-left: 5px solid #dc3232;
				border-radius: 4px;
				box-shadow: 0 1px 4px rgba(0,0,0,.1);
			">
				<h2 style="margin: 0 0 12px; color: #dc3232; font-size: 18px;">
					⚠️ <?php esc_html_e( 'Postomatic cannot run on a local environment', 'postomatic' ); ?>
				</h2>

				<p style="margin: 0 0 14px; font-size: 14px; color: #3c3c3c; line-height: 1.6;">
					<?php esc_html_e( 'Postomatic generates content by connecting to an external AI service (Buildomatics API). This connection requires your WordPress site to be reachable over the internet — something a local machine cannot provide.', 'postomatic' ); ?>
				</p>

				<p style="margin: 0 0 14px; font-size: 14px; color: #3c3c3c; line-height: 1.6;">
					<?php esc_html_e( 'What happens on localhost:', 'postomatic' ); ?>
				</p>
				<ul style="margin: 0 0 18px; padding-left: 20px; font-size: 14px; color: #3c3c3c; line-height: 1.8;">
					<li><?php esc_html_e( 'The AI API cannot send generated content back to your site.', 'postomatic' ); ?></li>
					<li><?php esc_html_e( 'Credit checks, activation, and post creation will all fail.', 'postomatic' ); ?></li>
					<li><?php esc_html_e( 'Webhooks and callbacks from the server cannot reach localhost.', 'postomatic' ); ?></li>
				</ul>

				<p style="margin: 0 0 20px; font-size: 14px; color: #3c3c3c; line-height: 1.6;">
					<strong><?php esc_html_e( 'To use Postomatic, deploy your site to a live or publicly accessible staging server.', 'postomatic' ); ?></strong>
				</p>

				<div style="background: #f8f8f8; border-radius: 4px; padding: 14px 18px; font-size: 13px; color: #555; line-height: 1.6;">
					<?php esc_html_e( 'If you are a developer testing locally, you need a tunnel tool such as', 'postomatic' ); ?>
					<a href="https://ngrok.com" target="_blank" rel="noopener noreferrer" style="color: #2271b1;">ngrok</a>
					<?php esc_html_e( 'or', 'postomatic' ); ?>
					<a href="https://expose.dev" target="_blank" rel="noopener noreferrer" style="color: #2271b1;">Expose</a>
					<?php esc_html_e( 'to make your local site publicly reachable. Even then, some features may not work correctly.', 'postomatic' ); ?>
				</div>
			</div>
			<?php
			return;
		}

		$template_path = POSTOMATIC_PLUGIN_DIR . 'includes/admin/templates/' . $template;

		if ( file_exists( $template_path ) ) {
			include_once $template_path;
		} else {
			echo '<div class="notice notice-error"><p>';
			// Translators: %s is the template filename that was not found.
			echo esc_html( sprintf( __( 'Template file %s not found.', 'postomatic' ), $template ) );
			echo '</p></div>';
		}
	}

	/**
	 * Render the setting plugin page.
	 */
	public function render_settings_page() {
		$this->render_template( 'settings.php' );
	}

	/**
	 * Render the membership page.
	 */
	public function render_membership_page() {
		$this->render_template( 'subscription.php' );
	}

	/**
	 * Render the credit page.
	 */
	public function render_credit_page() {
		$this->render_template( 'add-credit.php' );
	}

	/**
	 * Render the support page.
	 */
	public function render_support_page() {
		$this->render_template( 'support-ticket-template.php' );
	}

	/**
	 * Render the autopilot page.
	 */
	public function render_autopilot_page() {
		$this->render_template( 'autopilot.php' );
	}
}
