<?php

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

/**
 * Class VSERPB_Admin_Settings.
 */
class VSERPB_Admin_Settings {
	/**
	 * Init
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'vserpb_add_settings_page' ) );
		add_action( 'admin_init', array( __CLASS__, 'vserpb_register_settings' ) );
		add_action( 'admin_init', array( __CLASS__, 'vserpb_auto_disable_product_schema_if_wc_missing' ) );
		add_shortcode( 'vserpb_schema_links', array( __CLASS__, 'vserpb_schema_links_shortcode' ) );
		add_filter( 'plugin_action_links_voidek-serp-schema-builder/voidek-serp-schema-builder.php', array( __CLASS__, 'vserpb_add_settings_link' ) );
        add_action( 'admin_notices', array( __CLASS__, 'vserpb_show_success_notice' ) );
		add_action( 'admin_enqueue_scripts', [ __CLASS__, 'vserpb_admin_scripts' ] );
	}

public static function vserpb_admin_scripts( $hook ) {

    if ( $hook !== 'toplevel_page_voidek-serp-schema-builder' ) {
        return;
    }

    wp_add_inline_script(
        'jquery',
        "
        jQuery(document).ready(function($) {

            let formChanged = false;

            // Detect changes in form
            $('.vserpb-settings-container form').on('change input', function() {
                formChanged = true;
            });

            // On page leave
            window.addEventListener('beforeunload', function (e) {
                if (formChanged) {
                    e.preventDefault();
                    e.returnValue = '';
                }
            });

            // On form submit (Save button)
            $('.vserpb-settings-container form').on('submit', function() {
                formChanged = false;
            });

        });
        "
    );
}

    
    public static function vserpb_show_success_notice() {
    
        if ( ! isset( $_GET['settings-updated'] ) ) {
            return;
        }
    
        $screen = get_current_screen();
    
        if ( ! isset( $screen->id ) || $screen->id !== 'toplevel_page_voidek-serp-schema-builder' ) {
            return;
        }
    
        echo '<div class="notice notice-success is-dismissible vserpb-notice">
            <p><strong>' . esc_html__( 'Settings saved successfully.', 'voidek-serp-schema-builder' ) . '</strong></p>
        </div>';
    }
	public static function vserpb_add_settings_link( $links ) {
		$settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=voidek-serp-schema-builder' ) ) . '">'
			. esc_html__( 'Settings', 'voidek-serp-schema-builder' )
			. '</a>';
		array_unshift( $links, $settings_link );
		return $links;
	}



	/**
	 * Vserpb_add_settings_page.
	 *
	 * @return void
	 */
	public static function vserpb_add_settings_page() {
		add_menu_page(
			esc_html__( 'Product Schema Manager', 'voidek-serp-schema-builder' ),
			esc_html__( 'Voidek SERP', 'voidek-serp-schema-builder' ),
			'manage_options',
			'voidek-serp-schema-builder',
			array( __CLASS__, 'vserpb_settings_page' ),
			'dashicons-edit'
		);
	}

	/**
	 * Vserpb_settings_page.
	 *
	 * @return void
	 */
	public static function vserpb_settings_page() {
		?>
		<div class="vserp-wrap ">
			<div class="vserpb-settings-wrap">
			<div class="vserpb-settings-header">
				<div class="vserpb-header-content">
					<h2><?php esc_html_e( 'Voidek Auto Schema Generator - Configuration', 'voidek-serp-schema-builder' ); ?></h2>
					<p><?php esc_html_e( 'Enable or disable specific schema types to control how your Site appear in search results.', 'voidek-serp-schema-builder' ); ?></p>
				</div>
			</div>
			
			<?php do_action( 'vserpb_after_settings_header' ); ?>

		<div class="vserpb-settings-container card">
				<form method="post" action="options.php">
					<?php
					settings_fields( 'vserpb_settings_group' );
					do_settings_sections( 'voidek-serp-schema-builder' );
					submit_button(
						esc_html__( 'Save Settings', 'voidek-serp-schema-builder' ),
						'primary vserpb-submit-button'
					);
					?>
				</form>
			</div>
			
			<div class="vserpb-settings-sidebar">
				<div class="vserpb-sidebar-card">
					<h3><?php esc_html_e( 'Schema Tips', 'voidek-serp-schema-builder' ); ?></h3>
					<ul>
						<li><?php esc_html_e( 'Enable only the schema types you need to keep your markup clean.', 'voidek-serp-schema-builder' ); ?></li>
						<li><?php esc_html_e( 'Product and Offer schemas are most important for e-commerce sites.', 'voidek-serp-schema-builder' ); ?></li>
						<li><?php esc_html_e( 'Use the Google Rich Results Test to validate your schema.', 'voidek-serp-schema-builder' ); ?></li>
					</ul>
				</div>
						<div class="vserpb-sidebar-card">
					<?php echo do_shortcode( '[vserpb_schema_links]' ); ?>
				</div>
				
			</div>
			</div>
		</div>
		<?php
	}
	

	/**
	 * Check if WooCommerce is active
	 *
	 * @return bool
	 */
	private static function vserpb_is_woocommerce_active() {
		return class_exists( 'WooCommerce' );
	}

	
	/**
	 * Shortcode callback: Schema validation links
	 *
	 */
	public static function vserpb_schema_links_shortcode( $atts ) {

	$atts = shortcode_atts(
		array(
			'url' => home_url(),
		),
		$atts,
		'vserpb_schema_links'
	);

	ob_start();
	?>
	<div class="vserpb-schema-links">
		<h3><?php esc_html_e( 'Helpful Resources', 'voidek-serp-schema-builder' ); ?></h3>

		<ul>
			<li>
				<a href="https://wordpress.org/support/plugin/voidek-serp-schema-builder/"
				target="_blank" rel="noopener noreferrer">
					🆘 <?php esc_html_e( 'Get Help / Support', 'voidek-serp-schema-builder' ); ?>
				</a>
			</li>


			<li>
				<a href="https://wordpress.org/support/plugin/voidek-serp-schema-builder/reviews/#new-post"
				target="_blank" rel="noopener noreferrer">
					⭐ <?php esc_html_e( 'Rate this Plugin', 'voidek-serp-schema-builder' ); ?>
				</a>
			</li>
		</ul>

		<hr>

		<h3><?php esc_html_e( 'Schema Validation', 'voidek-serp-schema-builder' ); ?></h3>

		<ul>
			<li>
				<a href="https://search.google.com/test/rich-results"
				target="_blank" rel="noopener noreferrer">
					🔍 <?php esc_html_e( 'Google Rich Results Test', 'voidek-serp-schema-builder' ); ?>
				</a>
			</li>
			<li>
				<a href="https://validator.schema.org/"
				target="_blank" rel="noopener noreferrer">
					✅ <?php esc_html_e( 'Schema Markup Validator', 'voidek-serp-schema-builder' ); ?>
				</a>
			</li>
		</ul>
	</div>
	<?php

	return ob_get_clean();
}
	/**
	 * Automatically disable Product schema if WooCommerce is inactive
	 *
	 * @return void
	 */
	public static function vserpb_auto_disable_product_schema_if_wc_missing() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			$options = get_option( 'vserpb_product_schema', array() );

			if ( isset( $options['vserpb_enable_schema'] ) && 1 === (int) $options['vserpb_enable_schema'] ) {
				$options['vserpb_enable_schema'] = 0;
				update_option( 'vserpb_product_schema', $options );
			}
		}
	}

	
	/**
	 * vserpb_register_settings.
	 *
	 * @return void
	 */
	public static function vserpb_register_settings() {
		register_setting(
			'vserpb_settings_group',
			'vserpb_product_schema',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( __CLASS__, 'vserpb_sanitize_settings_array' ),
				'default'           => array(),
			)
		);
		$vserpb_settings = array(
			'vserpb_enable_schema' => array(
				'label'       => esc_html__( 'Enable Schema for Products', 'voidek-serp-schema-builder' ),
				'description' => esc_html__(
					'Enable this option to generate comprehensive Product schema markup, including properties like name, description, SKU, brand, image, offers, aggregateRating, review, and more. Helps search engines better understand your product pages and display rich results.',
					'voidek-serp-schema-builder'
				),
			),
			'asm_enable_schema'    => array(
				'label'       => esc_html__( 'Enable Schema for Articles', 'voidek-serp-schema-builder' ),
				'description' => esc_html__(
					'Enable this option to add structured data for Articles, including properties such as headline, author, datePublished, image, publisher, and articleBody. This enhances SEO and allows articles to appear as rich snippets in search results.',
					'voidek-serp-schema-builder'
				),
			),
			'rsm_enable_schema'    => array(
				'label'       => esc_html__( 'Enable Schema for Review', 'voidek-serp-schema-builder' ),
				'description' => esc_html__(
					'Enable Review schema to generate structured data for reviews, including properties like reviewBody, reviewRating, author, itemReviewed, and datePublished. This boosts your chances of showing review stars and rich details in search results.',
					'voidek-serp-schema-builder'
				),
			),
		);
$vserpb_settings['wsm_enable_schema'] = array(
    'label'       => esc_html__( 'Enable Schema for Pages', 'voidek-serp-schema-builder' ),
    'description' => esc_html__(
        'Enable this option to add structured data for WordPress Pages (WebPage, AboutPage, ContactPage, FAQPage). Includes properties such as name, description, breadcrumb, image, publisher, datePublished, and potentialAction.',
        'voidek-serp-schema-builder'
    ),
);
		add_settings_section(
			'vserpb_settings_section',
			esc_html__( 'Schema Options', 'voidek-serp-schema-builder' ),
			'__return_null',
			'voidek-serp-schema-builder'
		);

		foreach ( $vserpb_settings as $key => $setting ) {
			add_settings_field(
				$key,
				$setting['label'],
				array( __CLASS__, 'vserpb_render_toggle' ),
				'voidek-serp-schema-builder',
				'vserpb_settings_section',
				array(
					'key'         => $key,
					'description' => $setting['description'],
				)
			);
			// 👇 ADD THIS RIGHT AFTER PRODUCT SCHEMA FIELD
if ( 'vserpb_enable_schema' === $key ) {
	add_settings_field(
		'vserpb_pro_section',
		'', // no label (full width row)
		array( __CLASS__, 'vserpb_render_pro_section' ),
		'voidek-serp-schema-builder',
		'vserpb_settings_section',
		array(
			'class' => 'vserpb-full-width-row'
		)
	);
}
		}

		
	}
public static function vserpb_render_pro_section() {

	if ( ! self::vserpb_is_woocommerce_active() ) {
		return; // optional: hide if WooCommerce inactive
	}
	?>

	<div class="vserpb-pro-wrap">
		<div class="vserpb-pro-grid">

			<div class="vserpb-card pro">
				<div class="vserpb-badge">MOST POWERFUL</div>

				<div class="vserpb-card-header">
					<h3>PRO</h3>
				</div>

				<ul>
				<li>✔ Everything in Free</li>
				<li>✔ Advanced product metabox</li>
				<li>✔ Shipping & return schema</li>
				<li>✔ Manufacturer & brand data</li>
				<li>✔ Advanced ratings</li>
				<li>✔ Conditional rules engine</li>
				<li>✔ Schema validation dashboard</li>
				<li>✔ JSON-LD live preview</li>
				<li>✔ Rich Results Test integration</li>
				<li>✔ GTIN, condition, flags</li>
				<li>✔ Priority support</li>
				</ul>

				<div class="vserpb-card-footer">
					<a href="https://voidek.in/pro-pricing" target="_blank" class="vserpb-upgrade-btn">
						Upgrade to Pro →
					</a>
				</div>
			</div>

		</div>
	</div>

	<?php
}
	/**
	 * vserpb_render_toggle.
	 *
	 * @param  mixed $args
	 * @return void
	 */
	public static function vserpb_render_toggle( $args ) {
		$options = get_option( 'vserpb_product_schema', array() );
		$key     = $args['key'];
		$value   = isset( $options[ $key ] ) ? (int) $options[ $key ] : 0;

		$is_product_schema = ( 'vserpb_enable_schema' === $key );
		$is_wc_active      = self::vserpb_is_woocommerce_active();

		$disabled = ( $is_product_schema && ! $is_wc_active ) ? 'disabled' : '';
		?>

		<div class="vserpb-toggle-container">

		<label class="vserpb-toggle-switch">
				<input type="checkbox"
					name="vserpb_product_schema[<?php echo esc_attr( $key ); ?>]"
					value="1"
					<?php checked( $value, 1 ); ?>
					<?php echo esc_attr( $disabled ); ?>
					class="vserpb-toggle-input" />
				<span class="vserpb-toggle-slider"></span>
			</label>

			<?php if ( ! empty( $args['description'] ) ) : ?>
				<p class="description"><?php echo esc_html( $args['description'] ); ?></p>
			<?php endif; ?>

		</div>

		<?php if ( $is_product_schema && ! $is_wc_active ) : ?>
			<div class="notice notice-warning inline vserpb-inline-notice">
				<p>
					<strong><?php esc_html_e( 'WooCommerce is required to enable Product schema.', 'voidek-serp-schema-builder' ); ?></strong><br>
					<a href="<?php echo esc_url( admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' ) ); ?>">
						<?php esc_html_e( 'Install or Activate WooCommerce', 'voidek-serp-schema-builder' ); ?>
					</a>
				</p>
			</div>
		<?php endif; ?>

		</div>
		<?php
	}


	/**
	 * vserpb_sanitize_settings_array.
	 *
	 * @param  mixed $input
	 * @return void
	 */
	public static function vserpb_sanitize_settings_array( $input ) {
		$sanitized = array();

		$allowed_keys = array(
				'vserpb_enable_schema',
				'asm_enable_schema',
				'rsm_enable_schema',
				'wsm_enable_schema',   // <-- ADD THIS LINE
			);

		foreach ( $allowed_keys as $key ) {

			//  Block Product schema if WooCommerce is inactive
			if ( 'vserpb_enable_schema' === $key && ! self::vserpb_is_woocommerce_active() ) {
				$sanitized[ $key ] = 0;
				continue;
			}

			$sanitized[ $key ] = ( isset( $input[ $key ] ) && '1' === (string) $input[ $key ] ) ? 1 : 0;
		}

		return $sanitized;
	}

}


VSERPB_Admin_Settings::init();
