<?php
namespace Mamba\Modules\Media\Admin;

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

/**
 * Detect Nginx server and provide Next-Gen (WebP/AVIF) configuration guidance.
 * - Notice only for manage_options and when likely Nginx + WebP/AVIF enabled
 */
final class WebPNginxSupport {
    private const TRANSIENT_KEY = 'mamba_nextgen_nginx_support';
    private const ACK_OPTION = 'mamba_nextgen_nginx_ack';

    public function register(): void {
        add_action('admin_init', [$this, 'adminInit']);
        add_action('admin_notices', [$this, 'maybeShowNotice']);
    }

    public function adminInit(): void {
        if (!current_user_can('manage_options')) return;

        // Handle "Mark as done" acknowledgment
        if (!empty($_POST['mamba_nextgen_nginx_ack']) && isset($_POST['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'mamba_nextgen_nginx_ack')) {
            update_option(self::ACK_OPTION, 1);
            // Redirect to avoid resubmission
            wp_safe_redirect(remove_query_arg([]));
            exit;
        }

        // Reset acknowledgment if settings changed (so user sees updated config)
        $this->maybeResetAckOnSettingsChange();

        // Skip detection if acked
        if ((int) get_option(self::ACK_OPTION, 0) === 1) return;

        // Only detect for likely Nginx servers with WebP or AVIF enabled
        $hasNextGen = get_option('mamba_enable_webp_conversion', 0) || get_option('mamba_enable_avif_conversion', 0);
        if (!$this->isLikelyNginx() || !$hasNextGen) return;

        // Respect transient (12h)
        $cached = get_transient(self::TRANSIENT_KEY);
        if ($cached !== false) return;

        // Cache result for 12 hours
        set_transient(self::TRANSIENT_KEY, [
            'needs_config' => true,
            'time' => time(),
        ], 12 * HOUR_IN_SECONDS);
    }
    
    /**
     * Reset acknowledgment if user changes WebP/AVIF settings so they see updated config
     */
    private function maybeResetAckOnSettingsChange(): void {
        $currentWebP = (bool) get_option('mamba_enable_webp_conversion', 0);
        $currentAvif = (bool) get_option('mamba_enable_avif_conversion', 0);
        $lastWebP = (bool) get_option('mamba_nginx_last_webp', 0);
        $lastAvif = (bool) get_option('mamba_nginx_last_avif', 0);
        
        if ($currentWebP !== $lastWebP || $currentAvif !== $lastAvif) {
            // Settings changed, reset ack so user sees new config
            delete_option(self::ACK_OPTION);
            delete_transient(self::TRANSIENT_KEY);
            update_option('mamba_nginx_last_webp', $currentWebP ? 1 : 0);
            update_option('mamba_nginx_last_avif', $currentAvif ? 1 : 0);
        }
    }

    public function maybeShowNotice(): void {
        // DISABLED: Nginx configuration notice is now ONLY shown inline on the Media tab
        // The inline snippet in TabMedia.php is sufficient - no need for admin notices elsewhere
        return;
        
        // Legacy code below kept for reference but never executed
        if (!is_admin()) return;
        if (!current_user_can('manage_options')) return;
        if ((int) get_option(self::ACK_OPTION, 0) === 1) return;
        if (!$this->isLikelyNginx()) return;
        
        $hasNextGen = get_option('mamba_enable_webp_conversion', 0) || get_option('mamba_enable_avif_conversion', 0);
        if (!$hasNextGen) return;

        $cached = get_transient(self::TRANSIENT_KEY);
        if (!is_array($cached) || empty($cached['needs_config'])) return;

        $snippet = $this->getNginxNextGenSnippet();
        $formatLabel = $this->getEnabledFormatsLabel();
        ?>
        <div class="notice notice-info is-dismissible" style="background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%); border: 1px solid #93c5fd; border-left: 4px solid #3b82f6; border-radius: 8px; padding: 16px 20px; margin: 15px 0; box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1); animation: successSlideIn 0.3s ease-out;">
            <div style="display: flex; align-items: flex-start; gap: 12px;">
                <div style="flex-shrink: 0; width: 20px; height: 20px; background: linear-gradient(135deg, #3b82f6 0%, #3b82f6 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-top: 1px;">
                    <span style="color: white; font-size: 12px; font-weight: bold;">ℹ</span>
                </div>
                
                <div style="flex: 1; min-width: 0;">
                    <div style="margin-bottom: 12px;">
                        <span style="color: #1e40af; font-size: 11px; font-weight: 500;"><?php echo esc_html($formatLabel); ?> conversion is enabled. To serve next-gen images on Nginx, add this configuration:</span>
                    </div>
                    
                    <div style="background: #ffffff; border: 1px solid #93c5fd; border-radius: 6px; padding: 12px; margin-bottom: 12px; position: relative; font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace; font-size: 11px; line-height: 1.4; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                        <code id="mamba-nextgen-nginx-snippet-code" style="color: #1e293b; display: block; padding-right: 45px; line-height: 1.6; white-space: pre-wrap;"><?php echo esc_html($snippet); ?></code>
                        <button type="button" class="button button-small" data-mamba-copy="mamba-nextgen-nginx-snippet-code" style="position: absolute; top: 8px; right: 8px; font-size: 9px; padding: 2px 6px; height: 18px; line-height: 1; background: #3b82f6; border-color: #3b82f6; color: white; border-radius: 3px; font-weight: 500;">
                            <span class="copy-text">Copy</span>
                            <span class="copied-text" style="display: none;">✓ Copied</span>
                        </button>
                    </div>
                    
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <form method="post" style="margin: 0;">
                            <?php wp_nonce_field('mamba_nextgen_nginx_ack'); ?>
                            <input type="hidden" name="mamba_nextgen_nginx_ack" value="1" />
                            <button type="submit" class="button button-primary" style="font-size: 11px; padding: 6px 12px; height: 26px; line-height: 1; background: #3b82f6; border-color: #3b82f6; color: white; border-radius: 4px; font-weight: 500;">
                                Mark as Resolved
                            </button>
                        </form>
                        <span style="color: #1e40af; font-size: 10px; font-weight: 500;">
                            After adding, restart Nginx to apply changes. Ask your hosting provider for help if you are unsure.
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    private function isLikelyNginx(): bool {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized via sanitize_text_field
        $serverSoftware = isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : '';
        if (stripos($serverSoftware, 'nginx') !== false) return true;
        // Heuristic: presence of X-Accel headers suggests Nginx
        if (!empty($_SERVER['HTTP_X_ACCEL_REDIRECT']) || !empty($_SERVER['HTTP_X_ACCEL_EXPIRES'])) return true;
        // Conservative default to avoid false positives
        return false;
    }
    
    /**
     * Get label for enabled formats (WebP, AVIF, or both)
     */
    private function getEnabledFormatsLabel(): string {
        $webp = (bool) get_option('mamba_enable_webp_conversion', 0);
        $avif = (bool) get_option('mamba_enable_avif_conversion', 0);
        
        if ($webp && $avif) {
            return 'AVIF + WebP';
        } elseif ($avif) {
            return 'AVIF';
        } elseif ($webp) {
            return 'WebP';
        }
        return 'Next-Gen';
    }

    /**
     * Get Nginx configuration snippet using HtaccessManager
     */
    private function getNginxNextGenSnippet(): string {
        $htaccessManager = new \Mamba\Modules\Media\Services\HtaccessManager();
        return $htaccessManager->getNginxNextGenConfig();
    }
}
