<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Admin page: Widgets Options.
 *
 * @package Sifency_Addons
 */
class Sifency_Addons_Admin_Page_Widgets_Options {

	public function __construct() {
		add_action( 'admin_init', array( $this, 'register_settings' ) );
	}

	// -------------------------------------------------------------------------
	// Settings API
	// -------------------------------------------------------------------------
	public function register_settings() {
		register_setting(
			'sifency_addons_options',
			'sifency_addons_settings',
			array( $this, 'sanitize_settings' )
		);
	}

	public function sanitize_settings( $input ) {
		$sanitized_input = array();

		if ( isset( $input['widgets'] ) && is_array( $input['widgets'] ) ) {
			foreach ( $input['widgets'] as $widget_slug => $status ) {
				$sanitized_slug   = sanitize_key( $widget_slug );
				$sanitized_status = ( 'on' === $status ) ? 'on' : 'off';

				$sanitized_input['widgets'][ $sanitized_slug ] = $sanitized_status;
			}
		}

		return $sanitized_input;
	}

	// -------------------------------------------------------------------------
	// Helpers
	// -------------------------------------------------------------------------

	/**
	 * Loads categorized widget list from the registry, respecting exclusion
	 * filters so that widgets removed by the active theme do not appear here.
	 *
	 * @return array<string, array<string, array>>
	 */
	private function get_all_widgets_for_admin(): array {
		if ( class_exists( '\Sifency_Addons\Includes\Elementor\Sifency_Addons_Widget_Registry' ) ) {
			return \Sifency_Addons\Includes\Elementor\Sifency_Addons_Widget_Registry::get_categorized();
		}

		$raw    = \Sifency_Addons\Includes\Elementor\Sifency_Addons_Widget_Registry::load_raw();
		$merged = apply_filters( 'sifency_addons_widget_list', $raw );
		return is_array( $merged ) ? $merged : $raw;
	}

	/**
	 * Splits a categorized widget array into free / premium sub-arrays.
	 *
	 * @param array $all_widgets Categorized widget list.
	 * @return array{ free: array, premium: array }
	 */
	private function split_widgets( array $all_widgets ): array {
		$free    = array();
		$premium = array();

		foreach ( $all_widgets as $category => $widgets ) {
			if ( ! is_array( $widgets ) ) {
				continue;
			}
			foreach ( $widgets as $slug => $widget ) {
				if ( ! empty( $widget['sync_widget'] ) ) {
					$premium[ $category ][ $slug ] = $widget;
				} else {
					$free[ $category ][ $slug ] = $widget;
				}
			}
		}

		return array(
			'free'    => $free,
			'premium' => $premium,
		);
	}

	// -------------------------------------------------------------------------
	// Page render
	// -------------------------------------------------------------------------

	public function render_admin_page() {
		$settings = get_option( 'sifency_addons_settings', array() );

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'widgets';

		$all_widgets     = $this->get_all_widgets_for_admin();
		$split           = $this->split_widgets( $all_widgets );
		$free_widgets    = $split['free'];
		$premium_widgets = $split['premium'];

		// true  = site has active pro license → pro widgets fully unlocked.
		// false = free site → pro widgets visible but toggle locked.
		$is_pro_environment = (bool) Sifency_Addons_Theme_Builder_Master::sync_environment_state();
		?>

		<div class="sifency-admin-wrap sifency-dashboard-layout">

			<nav class="sifency-dashboard-nav">
				<a href="?page=sifency-addons-widgets"
				   class="sifency-nav-item sifency-admin-btn <?php echo ( 'widgets' === $active_tab ) ? 'active' : ''; ?>">
					<span class="dashicons dashicons-tagcloud"></span>
					<?php esc_html_e( 'All Widgets', 'sifency-addons' ); ?>
				</a>

				<a href="?page=sifency-addons-widgets&tab=free"
				   class="sifency-nav-item sifency-admin-btn <?php echo ( 'free' === $active_tab ) ? 'active' : ''; ?>">
					<span class="dashicons dashicons-star-empty"></span>
					<?php esc_html_e( 'Free', 'sifency-addons' ); ?>
				</a>

				<a href="?page=sifency-addons-widgets&tab=premium"
				   class="sifency-nav-item sifency-admin-btn <?php echo ( 'premium' === $active_tab ) ? 'active' : ''; ?>">
					<span class="dashicons dashicons-awards"></span>
					<?php esc_html_e( 'Premium', 'sifency-addons' ); ?>
				</a>
			</nav>

			<div class="sifency-admin-content">
				<form method="post" action="options.php">
					<?php settings_fields( 'sifency_addons_options' ); ?>

					<?php
					if ( 'free' === $active_tab ) {
						$this->render_widgets_tab( $settings, $free_widgets, $is_pro_environment );
					} elseif ( 'premium' === $active_tab ) {
						$this->render_widgets_tab( $settings, $premium_widgets, $is_pro_environment );
					} else {
						// Default: 'widgets' tab — show everything.
						$this->render_widgets_tab( $settings, $all_widgets, $is_pro_environment );
					}
					?>

					<?php submit_button( esc_html__( 'Save Changes', 'sifency-addons' ) ); ?>
					<div class="sifency-floating-add-btn text">
						<?php submit_button( esc_html__( 'Save Changes', 'sifency-addons' ) ); ?>
					</div>

				</form>
			</div>
		</div>
		<?php
	}

	// -------------------------------------------------------------------------
	// Tab render
	// -------------------------------------------------------------------------

	/**
	 * Renders the widget grid for a given tab.
	 *
	 * @param array $settings         Saved plugin settings.
	 * @param array $widgets_data     Categorized widget definitions to render.
	 * @param bool  $is_pro_environment Whether the site has an active pro license.
	 */
	private function render_widgets_tab( array $settings, array $widgets_data, bool $is_pro_environment ) {
		$total_count = 0;
		foreach ( $widgets_data as $widgets ) {
			if ( is_array( $widgets ) ) {
				$total_count += count( $widgets );
			}
		}
		?>

		<div class="sifency-addons-widgets-settings">

			<!-- Global category nav + global bulk buttons -->
			<div class="sifency-tab-header">
				<div class="sifency-category-nav-tabs">

					<button type="button" class="sifency-tab-trigger active" data-target="all">
						<span class="sifency-tab-text"><?php esc_html_e( 'All', 'sifency-addons' ); ?></span>
						<span class="sifency-tab-count"><?php echo esc_html( $total_count ); ?></span>
					</button>

					<?php foreach ( $widgets_data as $category_title => $widgets ) : ?>
						<?php
						$category_id  = 'sifency-cat-' . sanitize_title( $category_title );
						$widget_count = is_array( $widgets ) ? count( $widgets ) : 0;
						?>
						<button type="button"
							class="sifency-tab-trigger"
							data-target="<?php echo esc_attr( $category_id ); ?>">
							<span class="sifency-tab-text"><?php echo esc_html( $category_title ); ?></span>
							<span class="sifency-tab-count"><?php echo esc_html( $widget_count ); ?></span>
						</button>
					<?php endforeach; ?>

				</div>

				<!-- Global Enable All / Disable All -->
				<div class="sifency-master-controls">
					<div class="sifency-control-group">
						<button type="button"
							class="button sifency-toggle-all-btn sifency-admin-btn"
							data-action="enable"
							data-scope="global">
							<?php esc_html_e( 'Enable All', 'sifency-addons' ); ?>
						</button>
					</div>
					<div class="sifency-control-group">
						<button type="button"
							class="button sifency-toggle-all-btn sifency-admin-btn"
							data-action="disable"
							data-scope="global">
							<?php esc_html_e( 'Disable All', 'sifency-addons' ); ?>
						</button>
					</div>
				</div>
			</div>
			<!-- /sifency-tab-header -->

			<div class="sifency-tab-content-wrapper">

				<?php foreach ( $widgets_data as $category_title => $widgets ) : ?>
					<?php
					if ( ! is_array( $widgets ) || empty( $widgets ) ) {
						continue;
					}
					$category_id = 'sifency-cat-' . sanitize_title( $category_title );
					?>

					<div id="<?php echo esc_attr( $category_id ); ?>" class="sifency-widget-category-block">

						<!-- Category header: title + count + per-category bulk buttons -->
						<div class="sifency-section-header">
							<div class="sifency-section-header-left">
								<h2 class="sifency-widget-category-title">
									<?php echo esc_html( $category_title ); ?>
								</h2>
								<span class="sifency-section-count"><?php echo esc_html( count( $widgets ) ); ?></span>
							</div>

							<div class="sifency-category-bulk-controls">
								<button type="button"
									class="button sifency-category-toggle-btn sifency-admin-btn"
									data-action="enable"
									data-category="<?php echo esc_attr( $category_id ); ?>"
									data-is-pro="<?php echo esc_attr( $is_pro_environment ? '1' : '0' ); ?>">
									<?php esc_html_e( 'Enable All', 'sifency-addons' ); ?>
								</button>
								<button type="button"
									class="button sifency-category-toggle-btn sifency-admin-btn"
									data-action="disable"
									data-category="<?php echo esc_attr( $category_id ); ?>"
									data-is-pro="<?php echo esc_attr( $is_pro_environment ? '1' : '0' ); ?>">
									<?php esc_html_e( 'Disable All', 'sifency-addons' ); ?>
								</button>
							</div>
						</div>
						<!-- /sifency-section-header -->

						<div class="sifency-addons-widgets-grid">

							<?php foreach ( $widgets as $slug => $widget ) : ?>
								<?php
								$is_enabled    = isset( $settings['widgets'][ $slug ] ) && 'on' === $settings['widgets'][ $slug ];
								$is_pro_widget = ! empty( $widget['sync_widget'] );
								$has_tooltip   = ! empty( $widget['tooltip'] );

								/*
								 * Locked = pro widget on a free site.
								 * Pro users can toggle any widget freely.
								 * Free users see the card but the toggle is disabled and
								 * the hidden input always sends "off" (server-side guard below).
								 */
								$is_locked = $is_pro_widget && ! $is_pro_environment;

								$url_slug       = ! empty( $widget['demo_slug'] ) ? $widget['demo_slug'] : $slug;
								$base_demo_url  = 'https://sifency.com/sifency-addons/';
								$final_demo_url = $base_demo_url . $url_slug;

								if ( ! empty( $widget['live_demo'] ) && filter_var( $widget['live_demo'], FILTER_VALIDATE_URL ) ) {
									$final_demo_url = $widget['live_demo'];
								}

								$card_classes = 'sifency-widget-card';
								if ( $is_pro_widget ) {
									$card_classes .= ' pro-widget';
								}
								if ( $is_locked ) {
									$card_classes .= ' is-locked';
								}
								?>

								<div class="<?php echo esc_attr( $card_classes ); ?>"
									data-is-pro="<?php echo $is_pro_widget ? '1' : '0'; ?>">

									<div class="sifency-widget-card-header">
										<div class="sifency-header-left">
											<i class="<?php echo esc_attr( $widget['icon'] ); ?> sifency-widget-icon"></i>
											<h3 class="sifency-widget-title">
												<?php echo esc_html( $widget['title'] ); ?>
											</h3>
										</div>

										<?php if ( $is_pro_widget ) : ?>
											<span class="sifency-pro-badge">Pro</span>
										<?php endif; ?>
									</div>

									<div class="sifency-widget-card-footer">

										<div class="sifency-widget-actions">
											<a href="<?php echo esc_url( $final_demo_url ); ?>"
												target="_blank"
												rel="noopener noreferrer"
												class="sifency-demo-link text_underline_animation sifency-admin-btn">
												<span><?php esc_html_e( 'Live Demo', 'sifency-addons' ); ?></span>
											</a>
										</div>

										<div class="sifency-widget-toggle">
											<label class="sifency-switch<?php echo $is_locked ? ' sifency-switch--locked' : ''; ?>"
												<?php if ( $has_tooltip ) : ?>
													data-tooltip="<?php echo esc_attr( $widget['tooltip'] ); ?>"
												<?php endif; ?>
											>
												<!--
													Hidden input always sends "off".
													If the checkbox is checked, its value wins (browsers send the last
													matching name when the hidden + checkbox coexist).
													For locked widgets the checkbox is disabled so it is never submitted,
													meaning the hidden input sends "off" — free users can never activate pro.
												-->
												<input type="hidden"
													name="sifency_addons_settings[widgets][<?php echo esc_attr( $slug ); ?>]"
													value="off">

												<input
													type="checkbox"
													class="sifency-widget-toggle-checkbox"
													name="sifency_addons_settings[widgets][<?php echo esc_attr( $slug ); ?>]"
													value="on"
													<?php checked( $is_enabled && ! $is_locked, true ); ?>
													<?php disabled( $is_locked, true ); ?>
												>

												<span class="slider round"></span>
											</label>

											<?php if ( $is_locked ) : ?>
												<span class="sifency-locked-label">
													<?php esc_html_e( 'Pro Only', 'sifency-addons' ); ?>
												</span>
											<?php endif; ?>
										</div>

									</div>
								</div>
								<!-- /sifency-widget-card -->

							<?php endforeach; ?>

						</div>
						<!-- /sifency-addons-widgets-grid -->

					</div>
					<!-- /sifency-widget-category-block -->

				<?php endforeach; ?>

			</div>
			<!-- /sifency-tab-content-wrapper -->

		</div>
		<!-- /sifency-addons-widgets-settings -->

		<script>
		( function () {



		} )();
		</script>

		<?php
	}
}

new Sifency_Addons_Admin_Page_Widgets_Options();
