<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class SmallPict_Settings {

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

	public function enqueue_assets( $hook ) {
		// 1. Load Page-Specific Assets
		if ( $hook === 'toplevel_page_smallpict' || $hook === 'smallpict_page_smallpict' ) {
			wp_enqueue_style( 'smallpict-admin', plugin_dir_url( __DIR__ ) . 'assets/admin.css', array(), '1.0.0' );

			$dashboard_css = '
/* Minimal CSS for Dashboard */
.quota-bar-wrap { background:#eee; height:20px; border-radius:10px; overflow:hidden; margin-bottom:5px; }
.quota-bar-fill { background:#2271b1; height:100%; transition:width 0.3s; }
.quota-labels { display:flex; justify-content:space-between; font-size:12px; color:#666; }
.smallpict-badge { padding: 4px 8px; background:#ddd; border-radius:4px; font-weight:bold; }
.smallpict-badge.pro { background:#d4edda; color:#155724; }
';
			wp_add_inline_style( 'smallpict-admin', $dashboard_css );
		}

		// 2. Load Global Menu Icon CSS (Must be loaded on ALL admin pages)
		$icon_url     = plugin_dir_url( __DIR__ ) . 'assets/images/smallpict.svg';
		$icon_url_esc = esc_url( $icon_url );
		$custom_css   = "
            #adminmenu .toplevel_page_smallpict .wp-menu-image {
                background-color: currentColor !important;
                -webkit-mask: url('{$icon_url_esc}') no-repeat center center;
                mask: url('{$icon_url_esc}') no-repeat center center;
                -webkit-mask-size: 20px 20px;
                mask-size: 20px 20px;
            }
            #adminmenu .toplevel_page_smallpict .wp-menu-image img {
                display: none !important;
            }
        ";
		// Attach to 'admin-menu' which is always loaded in backend
		wp_add_inline_style( 'admin-menu', $custom_css );

		if ( $hook === 'toplevel_page_smallpict' || $hook === 'smallpict_page_smallpict' ) {
			wp_enqueue_script( 'jquery' );
			$inline_js = "
            jQuery(document).ready(function($) {
                var \$mode = $('#smallpict_compression_mode');
                var \$targetCheck = $('#smallpict_target_size_enabled');
                var msgId = 'sp-auto-lossy-msg';

                \$mode.after('<p id=\"'+msgId+'\" class=\"description\" style=\"color: #eba300; display:none; margin-top: 5px; font-weight: 500;\">⚠️ Target Size enabled. Switched to <strong>Lossy</strong> mode to ensure size reduction.</p>');

                \$targetCheck.on('change', function() {
                    if ($(this).is(':checked')) {
                        if (\$mode.val() === 'lossless') {
                            \$mode.val('lossy').trigger('change');
                            $('#'+msgId).fadeIn().delay(4000).fadeOut();
                        }
                    }
                });

                \$mode.on('change', function() {
                    if (\$targetCheck.is(':checked') && $(this).val() === 'lossless') {
                        var keepTarget = confirm(\"Target Size Strategy requires Lossy compression to work effectively.\\n\\nClick OK to keep Lossy.\\nClick Cancel to use Lossless (this will DISABLE Target Size).\");
                        if (keepTarget) {
                            $(this).val('lossy');
                        } else {
                            \$targetCheck.prop('checked', false);
                        }
                    }
                });
            });
            ";
			wp_add_inline_script( 'jquery', $inline_js );
		}
	}

	public function add_admin_menu() {
		// 1. Top Level Menu
		add_menu_page(
			'SmallPict',
			'SmallPict',
			'manage_options',
			'smallpict',
			array( $this, 'settings_page_html' ),
			'',
			80
		);

		// 2. Add "Settings" as the first submenu (re-using the parent slug ensures it's the default)
		add_submenu_page(
			'smallpict',
			'Settings',
			'Settings',
			'manage_options',
			'smallpict',
			array( $this, 'settings_page_html' )
		);
	}

	public function register_settings() {
		register_setting( 'smallpict_options', 'smallpict_auto_optimize', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'smallpict_options', 'smallpict_compression_mode', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'smallpict_options', 'smallpict_output_format', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'smallpict_options', 'smallpict_quality', array( 'sanitize_callback' => 'absint' ) );

		register_setting( 'smallpict_options', 'smallpict_target_size_enabled', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'smallpict_options', 'smallpict_target_kb', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'smallpict_options', 'smallpict_aggressive_resize', array( 'sanitize_callback' => 'absint' ) );
		register_setting( 'smallpict_options', 'smallpict_max_edge', array( 'sanitize_callback' => 'absint' ) );
		// Removed AWS Credential Settings
	}

	public function settings_page_html() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$slug      = get_option( 'smallpict_current_plan_slug', 'free' );
		$plan_name = ucfirst( $slug );

		// Pretty Names
		if ( $slug == 'starter' ) {
			$plan_name = 'Starter';
		}
		if ( $slug == 'pro' ) {
			$plan_name = 'Pro';
		}
		if ( $slug == 'business' ) {
			$plan_name = 'Business';
		}
		if ( $slug == 'agency' ) {
			$plan_name = 'Agency';
		}
		if ( $slug == 'enterprise' ) {
			$plan_name = 'Enterprise';
		}

		$upgrade_url = 'https://smallpict.tuxnoob.com';
		

		?>
		<div class="smallpict-wrap">
			<?php settings_errors(); ?>
			<!-- HEADER -->
			<div class="smallpict-header">
				<div class="sp-icon">
					<img src="<?php echo esc_url( plugin_dir_url( __DIR__ ) . 'assets/images/smallpict-logo.svg' ); ?>" alt="SmallPict" style="width: 32px; height: 32px; display: block;">
				</div>
				<div class="smallpict-title">
					<h1>SmallPict Settings</h1>
					<span style="color: #646970;">Serverless Image Optimization</span>
				</div>
				<div class="smallpict-status">
					
				</div>
			</div>

			<form action="options.php" method="post">
				<?php
				settings_fields( 'smallpict_options' );
				do_settings_sections( 'smallpict_options' );
				?>

				<div class="smallpict-grid">
					<!-- LEFT COLUMN -->
					<div class="main-column">
						
						<!-- GENERAL SETTINGS CARD -->
						<div class="smallpict-card">
							<div class="card-header">
								<h2>General Optimization</h2>
								<span class="card-subtitle">Configure how images are handled on upload.</span>
							</div>
							<div class="sp-settings-block">
								<!-- Auto Optimize -->
								<div class="form-group" style="display: flex; align-items: center; justify-content: space-between;">
									<div>
										<label for="smallpict_auto_optimize" style="margin:0; font-size: 14px;">Automatic Optimization</label>
										<p class="description" style="margin: 5px 0 0 0;">Optimize images immediately upon upload.</p>
									</div>
									<div class="toggle-wrapper">
										<input type="checkbox" name="smallpict_auto_optimize" id="smallpict_auto_optimize" value="1" <?php checked( 1, get_option( 'smallpict_auto_optimize', 1 ), true ); ?> />
									</div>
								</div>
								<hr style="border: 0; border-top: 1px solid #f0f0f1; margin: 20px 0;">

								<!-- Compression Mode -->
								<?php
									$slug = get_option( 'smallpict_current_plan_slug', 'free' );

									// Lossless requires PRO+
									$can_lossless = in_array( $slug, array( 'pro', 'business', 'agency', 'enterprise' ) );

									$lossless_label = 'Lossless (Best Quality)';
								if ( $slug == 'pro' ) {
									$lossless_label .= ' (2x Credit)';
								}
									$current_mode = get_option( 'smallpict_compression_mode', 'lossy' );
								?>
								<div class="form-group">
									<label for="smallpict_compression_mode">Compression Mode</label>
									<select name="smallpict_compression_mode" id="smallpict_compression_mode">
										<option value="lossy" <?php selected( $current_mode, 'lossy' ); ?>>Lossy (Best Compression)</option>
										<?php if ( $can_lossless ) : ?>
										<option value="lossless" <?php selected( $current_mode, 'lossless' ); ?>><?php echo esc_html( $lossless_label ); ?></option>
										<?php endif; ?>
									</select>
									<?php if ( ! $can_lossless ) : ?>
										<p class="description" style="color: #d63638; margin-top: 5px;">Lossless mode is available in Pro Plan or higher.</p>
									<?php endif; ?>
								</div>

								<!-- Output Format -->
								<div class="form-group">
									<label for="smallpict_output_format">Output Format</label>
									<?php
										$current_fmt = get_option( 'smallpict_output_format', 'webp' );

										// "Keep Original" requires PRO+ to actually work (otherwise falls back to WebP/JPG)
										// To avoid ambiguity, we disable it for Free/Starter.
										$can_original = in_array( $slug, array( 'pro', 'business', 'agency', 'enterprise' ) );

										// If user selected "Original" but is on Free/Starter, force visual to WebP
									if ( ! $can_original && $current_fmt === 'original' ) {
										$current_fmt = 'webp';
									}
									?>
									<select name="smallpict_output_format" id="smallpict_output_format">
										<?php if ( $can_original ) : ?>
										<option value="original" <?php selected( $current_fmt, 'original' ); ?>>Keep Original Format</option>
										<?php endif; ?>
										<option value="webp" <?php selected( $current_fmt, 'webp' ); ?>>WebP (Recommended)</option>
										<?php if ( $can_lossless ) : ?>
										<option value="avif" <?php selected( $current_fmt, 'avif' ); ?>>AVIF (Pro - Best Quality)</option>
										<?php endif; ?>
										<option value="jpg" <?php selected( $current_fmt, 'jpg' ); ?>>JPEG</option>
										<?php if ( $can_lossless ) : ?>
										<option value="png" <?php selected( $current_fmt, 'png' ); ?>>PNG (Pro)</option>
										<?php endif; ?>
									</select>
									<?php if ( ! $can_lossless || ! $can_original ) : ?>
										<p class="description" style="color: #d63638; margin-top: 5px;">Some formats (Original, AVIF, PNG) are available in Pro Plan or higher.</p>
									<?php else : ?>
										<p class="description" style="margin-top: 5px; font-size: 12px; color: #666;">
											* Static AVIF: <strong>Pro Plan</strong> <br>
											* Animated AVIF: <strong>Business Plan</strong> (Fallback to WebP on Pro)
										</p>
									<?php endif; ?>
								</div>
								
								<!-- Quality Slider -->
								<div class="form-group">
									<label for="smallpict_quality">Image Quality (Lossy Mode)</label>
									<?php $info_val = get_option( 'smallpict_quality', 80 ); ?>
									<div style="display: flex; align-items: center; gap: 15px;">
										<input type="range" name="smallpict_quality" id="smallpict_quality" value="<?php echo esc_attr( $info_val ); ?>" min="50" max="95" step="1" oninput="this.nextElementSibling.innerText = this.value" style="flex: 1;">
										<span style="font-weight: bold; background: #f0f0f1; padding: 2px 8px; border-radius: 4px; border: 1px solid #ccc; min-width: 30px; text-align: center;"><?php echo esc_html( $info_val ); ?></span>
									</div>
									<p class="description">Recommended: 80. Lower values reduce file size but may reduce visual quality.</p>
								</div>
							</div>
						</div>

						<!-- ADVANCED CARD -->
						

						<!-- DIAGNOSTICS CARD -->
						<div class="smallpict-card">
							<div class="card-header">
								<h2>Diagnostics & Environment</h2>
								<span class="card-subtitle">Troubleshooting tools for upload issues.</span>
							</div>
							<div class="sp-settings-block">
								<table class="widefat" style="border:0; box-shadow:none;">
									<tbody>
										<?php
                                            // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
											// TEST 1: Big Image Threshold
											$threshold_val    = apply_filters( 'big_image_size_threshold', 2560, array( 0, 0 ), '', 0 );
											$threshold_status = ( $threshold_val === false ) ? '<span style="color:green; font-weight:bold;">DISABLED (OK)</span>' : '<span style="color:red; font-weight:bold;">ENABLED (' . esc_html( wp_json_encode( $threshold_val ) ) . ')</span>';

											// TEST 2: Huge Image Resize Bypass
											// Simulate a huge image (5000x5000)
											$fake_sizes    = array(
												'medium' => array(),
												'large'  => array(),
											);
											$fake_meta     = array(
												'width'  => 5000,
												'height' => 5000,
											);
											$resize_val    = apply_filters( 'intermediate_image_sizes_advanced', $fake_sizes, $fake_meta );
											$resize_status = empty( $resize_val ) ? '<span style="color:green; font-weight:bold;">BYPASSED (OK)</span>' : '<span style="color:red; font-weight:bold;">FAILED (' . esc_html( wp_json_encode( count( $resize_val ) ) ) . ' sizes active)</span>';
                                            // phpcs:enable

											// TEST 3: Memory Limit
											$mem  = ini_get( 'memory_limit' );
											$time = ini_get( 'max_execution_time' );
											?>
										<tr>
											<td style="padding: 10px 0;"><strong>Big Image Threshold</strong></td>
											<td style="padding: 10px 0;"><?php echo wp_kses_post( $threshold_status ); ?> <br><span class="description">Must be DISABLED to allow huge uploads.</span></td>
										</tr>
										<tr>
											<td style="padding: 10px 0;"><strong>Huge Image Resize</strong></td>
											<td style="padding: 10px 0;"><?php echo wp_kses_post( $resize_status ); ?> <br><span class="description">Must be BYPASSED to prevent server crash.</span></td>
										</tr>
										<tr>
											<td style="padding: 10px 0;"><strong>PHP Environment</strong></td>
											<td style="padding: 10px 0;">
												Memory: <code><?php echo esc_html( $mem ); ?></code> <br>
												Time Limit: <code><?php echo esc_html( $time ); ?>s</code>
											</td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>
						
						<!-- Submit Button Container -->
						<div style="margin-top: 20px;">
							<?php submit_button( 'Save Changes', 'primary large', 'submit', false ); ?>
						</div>

					</div> <!-- End Main Column -->

					<!-- RIGHT COLUMN (SIDEBAR) -->
					<div class="sidebar-column">
						
						<!-- Quota Card -->
						<div class="smallpict-card">
							<div class="card-header">
								<h2>Usage & Quota</h2>
							</div>
							<div class="sp-settings-block">
								<?php
									$limit_mb = SmallPict_Quota_Manager::get_quota_display();
									$percent  = SmallPict_Quota_Manager::get_usage_percent();
								?>
									
								<!-- WPORG_REMOVE_START -->
								<?php if ( function_exists( 'smallpict_fs' ) && smallpict_fs()->is_paying_or_trial() && $limit_mb > 10000 ) : ?>
									<!-- Only show "Active Plan" banner if user is paying AND limit is huge (unlimited/very high) -->
									<div style="text-align: center; padding: 10px 0;">
										<div style="font-size: 24px; font-weight: bold; color: #2271b1;"><?php echo esc_html( $plan_name ); ?></div>
										<p style="margin: 5px 0;">Active Plan</p>
									</div>
									<a href="<?php echo esc_url( smallpict_fs()->get_account_url() ); ?>" target="_blank" class="button btn-full">View Dashboard</a>
								<?php else : ?>
									<!-- Show Usage Bar for Free AND Pro users with Quota -->
									<div style="margin-bottom: 15px;">
										<div style="display: flex; justify-content: space-between; font-size: 13px; font-weight: 600; margin-bottom: 5px;">
											<span>Monthly Quota</span>
											<span><?php echo esc_html( $percent ); ?>%</span>
										</div>
										<div style="background: #f0f0f1; border-radius: 4px; height: 10px; width: 100%; overflow: hidden;">
											<div style="background: <?php echo esc_attr( $percent > 90 ? '#d63638' : '#2271b1' ); ?>; height: 100%; width: <?php echo esc_attr( $percent ); ?>%;"></div>
										</div>
										<p class="description" style="text-align: right; margin-top: 5px;">
											<?php echo ( $limit_mb >= 999999 ) ? esc_html__( 'Unlimited', 'smallpict' ) : esc_html( $limit_mb ) . 'MB Limit'; ?>
										</p>
									</div>
									<?php if ( $slug == 'free' ) : ?>
										<a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank" class="button button-primary btn-full">Upgrade Limit</a>
									<?php else : ?>
										<a href="<?php echo esc_url( smallpict_fs()->get_account_url() ); ?>" target="_blank" class="button btn-full" style="margin-top: 10px;">Manage Subscription</a>
									<?php endif; ?>
								<?php endif; ?>
							</div>
						</div>

						<!-- Actions Card -->
						<div class="smallpict-card sp-actions-card">
							<div class="action-list">
								<a href="https://smallpict.tuxnoob.com" target="_blank" class="action-item" style="text-decoration: none; color: inherit;">
									<div class="action-icon">📚</div>
									<div class="action-content">
										<h3>Documentation</h3>
										<p>Learn how to get the most out of SmallPict.</p>
									</div>
								</a>
								<a href="https://smallpict.tuxnoob.com/support" target="_blank" class="action-item" style="text-decoration: none; color: inherit;">
									<div class="action-icon">💬</div>
									<div class="action-content">
										<h3>Support</h3>
										<p>Need help? Contact our support team.</p>
									</div>
								</a>
							</div>
						</div>
						 
						<div class="sp-info-card">
							SmallPict v<?php echo esc_html( SMALLPICT_VERSION ?? '1.0.0' ); ?>
						</div>

					</div> <!-- End Sidebar Column -->
				</div> <!-- End Grid -->
			</form>

		</div>
		<?php
	}
}
