<?php
/**
 * Main Plugin Orchestrator
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI;

defined('ABSPATH') || exit;

/**
 * Main plugin class - singleton pattern
 */
final class Plugin {

    /**
     * Plugin instance
     *
     * @var Plugin|null
     */
    private static ?Plugin $instance = null;

    /**
     * Hook loader
     *
     * @var Loader
     */
    private Loader $loader;

    /**
     * Get plugin instance
     *
     * @return Plugin
     */
    public static function instance(): Plugin {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Private constructor
     */
    private function __construct() {
        $this->loader = new Loader();
        $this->define_admin_hooks();
    }

    /**
     * Define admin hooks
     */
    private function define_admin_hooks(): void {
        // Settings page
        $settings = new Admin\SettingsPage();
        $this->loader->add_action('admin_menu', $settings, 'add_menu_page');
        $this->loader->add_action('admin_init', $settings, 'register_settings');
        $this->loader->add_action('wp_ajax_packshotphoto_test_api', $settings, 'ajax_test_api');
        $this->loader->add_action('wp_ajax_packshotphoto_fetch_context', $settings, 'ajax_fetch_context');
        $this->loader->add_action('wp_ajax_packshotphoto_save_site_context', $settings, 'ajax_save_site_context');
        $this->loader->add_action('wp_ajax_packshotphoto_test_custom_api', $settings, 'ajax_test_custom_api');
        $this->loader->add_action('wp_ajax_packshotphoto_reset_settings', $settings, 'ajax_reset_settings');

        // Custom columns
        $columns = new Admin\Columns();
        $this->loader->add_filter('manage_media_columns', $columns, 'add_columns');
        $this->loader->add_action('manage_media_custom_column', $columns, 'render_column', 10, 2);

        // Inline editor AJAX
        $editor = new Admin\InlineEditor();
        $this->loader->add_action('wp_ajax_packshotphoto_save_field', $editor, 'save_field');
        $this->loader->add_action('wp_ajax_packshotphoto_generate_ai', $editor, 'generate_ai');
        $this->loader->add_action('wp_ajax_packshotphoto_revert_ai_metadata', $editor, 'revert_ai_metadata');
        $this->loader->add_action('wp_ajax_packshotphoto_get_comparison_data', $editor, 'get_comparison_data');
        $this->loader->add_action('wp_ajax_packshotphoto_restore_original', $editor, 'restore_original');
        $this->loader->add_action('wp_ajax_packshotphoto_get_restore_options', $editor, 'get_restore_options');

        // WebP converter AJAX (manual button only)
        $webp = new Core\WebPConverter();
        $this->loader->add_action('wp_ajax_packshotphoto_convert_webp', $webp, 'ajax_convert');

        // AVIF converter AJAX (manual button only)
        $avif = new Core\AvifConverter();
        $this->loader->add_action('wp_ajax_packshotphoto_convert_avif', $avif, 'ajax_convert');

        // Image Resizer AJAX (manual button only)
        $processor = new Core\ImageProcessor();
        $this->loader->add_action('wp_ajax_packshotphoto_resize_image', $processor, 'ajax_resize');

        // EU AI Act Labeller AJAX
        $eu_ai = new Core\EuAiActLabeller();
        $this->loader->add_action('wp_ajax_packshotphoto_apply_eu_ai_label', $eu_ai, 'ajax_apply_label');
        $this->loader->add_action('wp_ajax_packshotphoto_get_eu_ai_icons', $eu_ai, 'ajax_get_icons');

        // Cache busting for admin media library thumbnails
        if (is_admin()) {
            $this->loader->add_filter('wp_get_attachment_image_src', $this, 'filter_attachment_image_src_cache_bust', 10, 4);
            $this->loader->add_filter('wp_get_attachment_image_attributes', $this, 'filter_attachment_image_attrs_cache_bust', 10, 3);
        }

        // Upload coordinator — auto-resize, AI, WebP after upload
        Core\UploadCoordinator::register_hooks();

        // Upload panel — session-level override UI on media-new.php
        Admin\UploadPanel::register_hooks();

        // Bulk actions
        $bulk = new Admin\BulkActions();
        $this->loader->add_filter('bulk_actions-upload', $bulk, 'add_bulk_actions');
        $this->loader->add_filter('handle_bulk_actions-upload', $bulk, 'handle_bulk_action', 10, 3);
        $this->loader->add_action('admin_notices', $bulk, 'show_bulk_notice');
        $this->loader->add_action('admin_notices', $bulk, 'show_pro_notice');
        $this->loader->add_action('admin_notices', $this, 'show_media_info_banner');
        $this->loader->add_action('wp_ajax_packshotphoto_dismiss_banner', $this, 'ajax_dismiss_banner');
        $this->loader->add_action('wp_ajax_packshotphoto_log_deactivation_survey', $this, 'ajax_log_deactivation_survey');
        $this->loader->add_action('wp_ajax_packshotphoto_process_batch', $bulk, 'ajax_process_batch');
        
        // Queue Manager (Background processing)
        $queue = new Core\QueueManager();
        $queue->register_hooks();
        $this->loader->add_action('wp_ajax_packshotphoto_get_queue_status', $this, 'ajax_get_queue_status');

        // Settings Page AJAX hooks (reuse $settings instance from above)
        $this->loader->add_action('wp_ajax_packshotphoto_save_api_key', $settings, 'ajax_save_api_key');

        // Checkout handler
        $checkout = new API\CheckoutHandler();
        $this->loader->add_action('rest_api_init', $checkout, 'register_routes');
        $this->loader->add_action('admin_init', $checkout, 'handle_php_checkout_redirect');

        // Assets
        $this->loader->add_action('admin_enqueue_scripts', $this, 'enqueue_admin_assets');

        // REST API (Webhooks)
        $this->loader->add_action('rest_api_init', $this, 'register_rest_routes');

        // Plugin action links
        $plugin_basename = plugin_basename(PACKSHOTPHOTO_AI_FILE);
        $this->loader->add_filter("plugin_action_links_{$plugin_basename}", $this, 'add_settings_link');
    }

    /**
     * Enqueue admin assets
     *
     * @param string $hook Current admin page hook
     */
    public function enqueue_admin_assets(string $hook): void {
        // Load on media library, plugins list, or our settings page
        $allowed_pages = [
            'upload.php',                        // Media library
            'media-new.php',                     // Add new media
            'plugins.php',                       // Plugins page (for deactivation feedback modal)
            'tools_page_packshotphoto-ai',      // Our settings page (add_management_page)
            'plugins_page_packshotphoto-ai',     // Our settings page (add_plugins_page)
        ];
        
        if (!in_array($hook, $allowed_pages, true)) {
            return;
        }

        wp_enqueue_media();

        wp_enqueue_style(
            'packshotphoto-admin',
            PACKSHOTPHOTO_AI_URL . 'assets/css/admin.css',
            [],
            PACKSHOTPHOTO_AI_VERSION . '.' . filemtime(PACKSHOTPHOTO_AI_DIR . 'assets/css/admin.css')
        );

        wp_enqueue_script(
            'packshotphoto-admin',
            PACKSHOTPHOTO_AI_URL . 'assets/js/admin.js',
            [],
            PACKSHOTPHOTO_AI_VERSION . '.' . filemtime(PACKSHOTPHOTO_AI_DIR . 'assets/js/admin.js'),
            true
        );

        $modal_strings = $this->get_localized_modal_strings();

        wp_localize_script('packshotphoto-admin', 'packshotphotoConfig', [
            'ajaxUrl'        => admin_url('admin-ajax.php'),
            'restUrl'        => get_rest_url(null, 'packshotphoto/v1'),
            'restNonce'      => wp_create_nonce('wp_rest'),
            'nonce'          => wp_create_nonce('packshotphoto_global_nonce'),
            'connectionType' => get_option('packshotphoto_connection_type', 'our_service'),
            'isPro'          => \PackshotPhotoAI\Core\LicenseManager::is_pro(),
            'settingsUrl'    => admin_url('tools.php?page=packshotphoto-ai'),
            'i18n'    => array_merge($modal_strings, [
                'proRequiredTitle'     => __('PRO Feature Required', 'packshotphoto-ai'),
                'proRequiredMessage'   => __('Bulk operations, image resizing, and format conversion (WebP/AVIF) are exclusively available to our clients with an active PackshotPhoto AI subscription and connection to our server.', 'packshotphoto-ai'),
                'goToSettings'         => __('Go to Settings', 'packshotphoto-ai'),
                'saving'                => __('Saving...', 'packshotphoto-ai'),
                'saved'                => __('Saved!', 'packshotphoto-ai'),
                'error'                => __('Error', 'packshotphoto-ai'),
                'generating'           => __('Generating...', 'packshotphoto-ai'),
                'overwrite'            => __('Overwrite existing value?', 'packshotphoto-ai'),
                'testSuccess'          => __('Connection OK!', 'packshotphoto-ai'),
                'testFail'             => __('Connection error:', 'packshotphoto-ai'),
                'networkError'         => __('Network error', 'packshotphoto-ai'),
                'serverInvalidResponse' => __('Server returned invalid response', 'packshotphoto-ai'),
                'errorReverting'       => __('Error reverting', 'packshotphoto-ai'),
                'enterLicenseKey'      => __('Enter license key first', 'packshotphoto-ai'),
                'deactivateConfirm'    => __('Are you sure you want to deactivate PRO?', 'packshotphoto-ai'),
                /* translators: %d: number of items */
                'startingProcessing'   => __('Starting processing of %d items...', 'packshotphoto-ai'),
                'generate'             => __('Generate', 'packshotphoto-ai'),
                'processingAI'         => __('Processing AI', 'packshotphoto-ai'),
                'optimizingLibrary'    => __('Optimizing media library...', 'packshotphoto-ai'),
                'processingInBackground' => __('Processing in background', 'packshotphoto-ai'),
                'completingTasks'      => __('Completing batch tasks...', 'packshotphoto-ai'),
                'progress'             => __('Progress', 'packshotphoto-ai'),
                'renameWarning'        => __('Warning: URL Change', 'packshotphoto-ai'),
                'filenameWarning'      => __('Warning: Changing the physical file name of an image already used in posts or pages will break those links (404 errors) unless you manually update them. This is NOT recommended for existing content.', 'packshotphoto-ai'),
                'renameOldPrefix'      => __('Old name:', 'packshotphoto-ai'),
                'renameNewPrefix'      => __('New name:', 'packshotphoto-ai'),
                'renameConfirm'        => __('Proceed anyway?', 'packshotphoto-ai'),
                'renameWarningTitle'   => __('Warning: URL Change', 'packshotphoto-ai'),
                'renameWarningDesc'    => __('Changing the file name will change the image URL. If this file is already linked on your site, the images will disappear (404).', 'packshotphoto-ai'),
                'renameSlugOnly'       => __('Change Title & Slug ONLY (Safe - keeps original URL)', 'packshotphoto-ai'),
                'existingDataTitle'    => __('Existing data found', 'packshotphoto-ai'),
                'selectFieldsToOverwrite' => __('Select which fields to overwrite with AI:', 'packshotphoto-ai'),
                'cancel'               => __('Cancel', 'packshotphoto-ai'),
                'apply'                => __('Apply', 'packshotphoto-ai'),
                'aiGenerated'          => __('AI generated!', 'packshotphoto-ai'),
                'defaultSize'          => __('default', 'packshotphoto-ai'),
                'restore'              => __('Restore', 'packshotphoto-ai'),
                'restoreTitle'         => __('Restore original values', 'packshotphoto-ai'),
                'altText'              => __('Alt Text', 'packshotphoto-ai'),
                'captionLabel'         => __('Caption', 'packshotphoto-ai'),
                'descriptionLabel'     => __('Description', 'packshotphoto-ai'),
                'filenameLabel'        => __('Filename', 'packshotphoto-ai'),
                'empty'                => __('empty', 'packshotphoto-ai'),
                'renameSafeDesc'       => __('Keep original URL. Safe for images already published in posts.', 'packshotphoto-ai'),
                'renameUnsafeWarn'     => __('* Uncheck "Safe Rename" only for new images that are not yet linked anywhere on your site.', 'packshotphoto-ai'),
                'success'              => __('Success', 'packshotphoto-ai'),
                'errors'               => __('Errors', 'packshotphoto-ai'),
                'remaining'            => __('Remaining', 'packshotphoto-ai'),
                'restoreOriginalFile'  => __('Restore original file format', 'packshotphoto-ai'),
                'restoredAlt'          => __('Alt text restored', 'packshotphoto-ai'),
                'restoredCaption'      => __('Caption restored', 'packshotphoto-ai'),
                'restoredDescription'   => __('Description restored', 'packshotphoto-ai'),
                'restoredFilename'      => __('Filename restored', 'packshotphoto-ai'),
                'restoredFile'          => __('Original file restored', 'packshotphoto-ai'),
                'noRestoreAvailable'    => __('Nothing to restore', 'packshotphoto-ai'),
                'original'             => __('Original', 'packshotphoto-ai'),
                'current'             => __('Current', 'packshotphoto-ai'),
                'smaller'             => __('smaller', 'packshotphoto-ai'),
                'larger'              => __('larger', 'packshotphoto-ai'),
                'adjustingDimensions' => __('Adjusting image dimensions...', 'packshotphoto-ai'),
                'avifConversion'      => __('AVIF Conversion', 'packshotphoto-ai'),
                'convertingImages'    => __('Converting images to modern format...', 'packshotphoto-ai'),
                /* translators: 1: success count, 2: errors count */
                'doneBatch'           => __('Done: %1$s success, %2$s errors.', 'packshotphoto-ai'),
                'movingToBackground'  => __('Large batch - moving to background processing...', 'packshotphoto-ai'),
                'processing'          => __('Processing...', 'packshotphoto-ai'),
                'resizing'            => __('Resizing', 'packshotphoto-ai'),
                'restoreConfirm'      => __('Are you sure you want to restore the original file? The current version will be replaced.', 'packshotphoto-ai'),
                'versionsAvailable'   => __('versions available', 'packshotphoto-ai'),
                'webpConversion'      => __('WebP Conversion', 'packshotphoto-ai'),
                'workInProgress'      => __('Work in progress...', 'packshotphoto-ai'),
                // Resize
                'resizeTitle'         => __('Resize image', 'packshotphoto-ai'),
                'resizePrompt'       => __('Enter target width (px):', 'packshotphoto-ai'),
                'widthPx'            => __('Width (px)', 'packshotphoto-ai'),
                'resizeBtn'          => __('Resize', 'packshotphoto-ai'),
                /* translators: %d: number of images */
                'resizeImages'        => __('Resize %d images?', 'packshotphoto-ai'),
                'width'               => __('Width', 'packshotphoto-ai'),
                'px'                  => __('px', 'packshotphoto-ai'),
                // Convert
                'convertTitle'        => __('Convert Image Format', 'packshotphoto-ai'),
                'convertPrompt'       => __('Select target compression format to reduce file size:', 'packshotphoto-ai'),
                'convertBtn'          => __('Convert', 'packshotphoto-ai'),
                'estimatedSize'       => __('Estimated size:', 'packshotphoto-ai'),
                'webpSavings'         => __('30% savings', 'packshotphoto-ai'),
                'avifSavings'         => __('50% savings', 'packshotphoto-ai'),
                'webpSavingsBadge'    => __('-30% size', 'packshotphoto-ai'),
                'avifSavingsBadge'    => __('-50% size', 'packshotphoto-ai'),
                'webpDesc'            => __('Standard for modern websites. Reduces size without visible quality loss.', 'packshotphoto-ai'),
                'avifDesc'            => __('Next generation compression. Extreme file size reduction while preserving perfect details.', 'packshotphoto-ai'),
                // Billing
                'creditGeneration'    => __('1 credit = 1 AI generation', 'packshotphoto-ai'),
                'maxPlan'             => __('of max plan', 'packshotphoto-ai'),
                'noTransactions'      => __('No transactions yet', 'packshotphoto-ai'),
                'purchase'            => __('Purchase', 'packshotphoto-ai'),
                'aiUse'               => __('AI Use', 'packshotphoto-ai'),
                'refund'              => __('Refund', 'packshotphoto-ai'),
                'manual'              => __('Manual', 'packshotphoto-ai'),
                'syncing'             => __('Syncing...', 'packshotphoto-ai'),
                'syncSupabase'        => __('Synchronizing with server...', 'packshotphoto-ai'),
                'testing'             => __('Testing...', 'packshotphoto-ai'),
                'loading'             => __('Loading...', 'packshotphoto-ai'),
                'successConfirm'      => __('Success! Credits updated.', 'packshotphoto-ai'),
                // Settings
                'testConnection'     => __('Test connection', 'packshotphoto-ai'),
                'activating'         => __('Activating...', 'packshotphoto-ai'),
                'deactivating'       => __('Deactivating...', 'packshotphoto-ai'),
                // Status messages
                'checking'           => __('Checking...', 'packshotphoto-ai'),
                'analyzing'          => __('Analyzing...', 'packshotphoto-ai'),
                'done'               => __('Done!', 'packshotphoto-ai'),
                'analyzingError'     => __('Error:', 'packshotphoto-ai'),
                // Compare
                'compareTitle'       => __('Compare', 'packshotphoto-ai'),
                'restoring'          => __('Restoring...', 'packshotphoto-ai'),
                // License
                'activatePro'        => __('Activate PRO', 'packshotphoto-ai'),
                'deactivate'         => __('Deactivate', 'packshotphoto-ai'),
                'activationSuccess'  => __('License activated!', 'packshotphoto-ai'),
                'activationFailed'  => __('Activation failed', 'packshotphoto-ai'),
                'resetConfirm'       => __('Are you sure you want to reset all settings to factory defaults? This action cannot be undone.', 'packshotphoto-ai'),
                'close'             => __('Close', 'packshotphoto-ai'),
                'ok'                => __('OK', 'packshotphoto-ai'),
                'invalidSize'         => __('Invalid size', 'packshotphoto-ai'),
                // Settings
                'analyzeSite'       => __('Analyzing your site...', 'packshotphoto-ai'),
                'contextSaved'      => __('Site context saved!', 'packshotphoto-ai'),
                'generateContext'   => __('Generate Context with AI', 'packshotphoto-ai'),
                'additionalTasks'   => __('Additional tasks added...', 'packshotphoto-ai'),
            ]),
        ]);
    }

    /**
     * Show info banner on media library page
     */
    public function show_media_info_banner(): void {
        $screen = get_current_screen();
        if (!$screen || 'upload' !== $screen->id) {
            return;
        }

        // Don't show if dismissed
        $dismissed = get_user_meta(get_current_user_id(), 'packshotphoto_banner_dismissed', true);
        if ($dismissed) {
            return;
        }

        $settings_url = admin_url('tools.php?page=packshotphoto-ai');
        ?>
        <div class="notice notice-info packshotphoto-info-banner is-dismissible" data-packshotphoto-dismiss="banner">
            <p>
                <strong>💡 PackshotPhoto AI:</strong>
                <?php esc_html_e('Select multiple files and use "Bulk actions" for mass AI descriptions, WebP conversion, or image resizing.', 'packshotphoto-ai'); ?>
                <a href="<?php echo esc_url($settings_url); ?>">
                    <?php esc_html_e('Settings →', 'packshotphoto-ai'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * AJAX: Dismiss info banner for current user
     */
    public function ajax_dismiss_banner(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        update_user_meta(get_current_user_id(), 'packshotphoto_banner_dismissed', 1);
        wp_send_json_success();
    }

    /**
     * AJAX: Get background queue status
     */
    public function ajax_get_queue_status(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $status = Core\QueueManager::get_status();
        wp_send_json_success($status);
    }

    /**
     * Register REST API routes
     */
    public function register_rest_routes(): void {
        $webhook = new API\WebhookHandler();
        $webhook->register_routes();

        $checkout = new API\CheckoutHandler();
        $checkout->register_routes();
    }

    /**
     * Add settings link to plugin action links in Plugins list
     *
     * @param array $links Current links
     * @return array
     */
    public function add_settings_link(array $links): array {
        $settings_url = admin_url('tools.php?page=packshotphoto-ai');
        $settings_link = '<a href="' . esc_url($settings_url) . '">' . __('Settings', 'packshotphoto-ai') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    /**
     * Get localized modal strings for connection and credit errors
     *
     * @return array
     */
    private function get_localized_modal_strings(): array {
        $locale = get_locale();
        $lang = strtolower(substr($locale, 0, 2));

        // Default English
        $strings = [
            'missingConnectionTitle'   => __('No Connection to PackshotPhoto AI', 'packshotphoto-ai'),
            'missingConnectionMessage' => __('No connection to the PackshotPhoto AI server. Please connect to our service in the Settings page to use AI generation. You will receive 10 free credits to start!', 'packshotphoto-ai'),
            'insufficientCreditsTitle' => __('Insufficient AI Credits', 'packshotphoto-ai'),
            'insufficientCreditsMessage' => __('You have exhausted your free starter credits or do not have enough funds in your account. You can purchase a package of additional credits in the settings page.', 'packshotphoto-ai'),
            'buyCredits'               => __('Buy Credits', 'packshotphoto-ai'),
            'cancel'                   => __('Cancel', 'packshotphoto-ai'),
            'settings'                 => __('Settings', 'packshotphoto-ai'),
            'deactivateSurveyTitle'       => __('Why are you deactivating PackshotPhoto AI?', 'packshotphoto-ai'),
            'deactivateReason1'            => __('I found a better plugin', 'packshotphoto-ai'),
            'deactivateReason2'            => __('It doesn\'t work / has bugs', 'packshotphoto-ai'),
            'deactivateReason3'            => __('I don\'t understand how to use it', 'packshotphoto-ai'),
            'deactivateReason4'            => __('Temporary deactivation / debugging', 'packshotphoto-ai'),
            'deactivateReason5'            => __('Other (please specify)', 'packshotphoto-ai'),
            'deactivateReasonPlaceholder' => __('Briefly explain the issue...', 'packshotphoto-ai'),
            'submitAndDeactivate'          => __('Submit & Deactivate', 'packshotphoto-ai'),
            'skipAndDeactivate'            => __('Skip & Deactivate', 'packshotphoto-ai'),
        ];

        // Explicit translations for other languages supported by the plugin
        switch ($lang) {
            case 'pl':
                $strings['missingConnectionTitle']   = 'Brak połączenia z PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Brak połączenia z serwerem PackshotPhoto AI. Połącz się z naszym serwisem w sekcji Ustawień, aby móc korzystać z generowania AI. Otrzymasz 10 darmowych kredytów na start!';
                $strings['insufficientCreditsTitle'] = 'Brak kredytów AI';
                $strings['insufficientCreditsMessage'] = 'Wyczerpałeś darmowe kredyty startowe lub nie posiadasz wystarczających środków na koncie. Możesz zakupić pakiet dodatkowych kredytów w zakładce ustawień.';
                $strings['buyCredits']               = 'Doładuj kredyty';
                $strings['cancel']                   = 'Anuluj';
                $strings['settings']                 = 'Ustawienia';
                $strings['deactivateSurveyTitle']       = 'Dlaczego odinstalowujesz PackshotPhoto AI?';
                $strings['deactivateReason1']            = 'Znalazłem lepszą wtyczkę';
                $strings['deactivateReason2']            = 'Wtyczka nie działa / zawiera błędy';
                $strings['deactivateReason3']            = 'Nie rozumiem, jak jej używać';
                $strings['deactivateReason4']            = 'Tymczasowa dezaktywacja / debugowanie';
                $strings['deactivateReason5']            = 'Inny powód (proszę określić)';
                $strings['deactivateReasonPlaceholder'] = 'Wyjaśnij krótko powód...';
                $strings['submitAndDeactivate']          = 'Wyślij i dezaktywuj';
                $strings['skipAndDeactivate']            = 'Pomiń i dezaktywuj';
                break;
            case 'de':
                $strings['missingConnectionTitle']   = 'Keine Verbindung zu PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Keine Verbindung zum PackshotPhoto AI-Server. Bitte verbinden Sie sich auf der Einstellungsseite mit unserem Dienst, um die KI-Generierung zu nutzen. Sie erhalten 10 kostenlose Credits zum Start!';
                $strings['insufficientCreditsTitle'] = 'Unzureichende KI-Credits';
                $strings['insufficientCreditsMessage'] = 'Sie haben Ihre kostenlosen Start-Credits aufgebraucht oder haben nicht genügend Guthaben auf Ihrem Konto. Sie können ein Paket mit zusätzlichen Credits auf der Einstellungsseite erwerben.';
                $strings['buyCredits']               = 'Credits kaufen';
                $strings['cancel']                   = 'Abbrechen';
                $strings['settings']                 = 'Einstellungen';
                break;
            case 'es':
                $strings['missingConnectionTitle']   = 'Sin conexión a PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Sin conexión al servidor PackshotPhoto AI. Por favor, conéctese a nuestro servicio en la página de ajustes para usar la generación de IA. ¡Recibirá 10 créditos gratis para comenzar!';
                $strings['insufficientCreditsTitle'] = 'Créditos de IA insuficientes';
                $strings['insufficientCreditsMessage'] = 'Ha agotado sus créditos iniciales gratuitos o no tiene suficientes fondos en su cuenta. Puede comprar un paquete de créditos adicionales en la página de ajustes.';
                $strings['buyCredits']               = 'Comprar créditos';
                $strings['cancel']                   = 'Cancelar';
                $strings['settings']                 = 'Ajustes';
                break;
            case 'fr':
                $strings['missingConnectionTitle']   = 'Pas de connexion à PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Pas de connexion au serveur PackshotPhoto AI. Veuillez vous connecter à notre service dans la page des réglages pour utiliser la génération IA. Vous recevrez 10 crédits gratuits pour commencer !';
                $strings['insufficientCreditsTitle'] = 'Crédits IA insuffisants';
                $strings['insufficientCreditsMessage'] = 'Vous avez épuisé vos crédits de départ gratuits ou vous n\'avez pas assez de fonds sur votre compte. Vous pouvez acheter un pack de crédits supplémentaires sur la page des réglages.';
                $strings['buyCredits']               = 'Acheter des crédits';
                $strings['cancel']                   = 'Annuler';
                $strings['settings']                 = 'Réglages';
                break;
            case 'it':
                $strings['missingConnectionTitle']   = 'Nessuna connessione a PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Nessuna connessione al server PackshotPhoto AI. Si prega di connettersi al nostro servizio nella pagina delle impostazioni per utilizzare la generazione AI. Riceverai 10 crediti gratuiti per iniziare!';
                $strings['insufficientCreditsTitle'] = 'Crediti AI insufficienti';
                $strings['insufficientCreditsMessage'] = 'Hai esaurito i tuoi crediti iniziali gratuiti o non hai abbastanza fondi nel tuo account. Puoi acquistare un pacchetto di crediti aggiuntivi nella pagina delle impostazioni.';
                $strings['buyCredits']               = 'Acquista crediti';
                $strings['cancel']                   = 'Annulla';
                $strings['settings']                 = 'Impostazioni';
                break;
            case 'nl':
                $strings['missingConnectionTitle']   = 'Geen verbinding met PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Geen verbinding met de PackshotPhoto AI-server. Maak verbinding met onze service op de instellingenpagina om AI-generatie te gebruiken. U ontvangt 10 gratis credits om te starten!';
                $strings['insufficientCreditsTitle'] = 'Onvoldoende AI-credits';
                $strings['insufficientCreditsMessage'] = 'U heeft uw gratis startcredits opgebruikt of heeft onvoldoende saldo op uw account. U kunt een pakket met extra credits kopen op de instellingenpagina.';
                $strings['buyCredits']               = 'Credits kopen';
                $strings['cancel']                   = 'Annuleren';
                $strings['settings']                 = 'Instellingen';
                break;
            case 'pt':
                $strings['missingConnectionTitle']   = 'Sem conexão com o PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Sem conexão com o servidor PackshotPhoto AI. Conecte-se ao nosso serviço na página de configurações para usar a geração de IA. Você receberá 10 créditos grátis para começar!';
                $strings['insufficientCreditsTitle'] = 'Créditos de IA insuficientes';
                $strings['insufficientCreditsMessage'] = 'Você esgotou seus créditos iniciais gratuitos ou não tem saldo suficiente em sua conta. Você pode comprar um pacote de créditos adicionais na página de configurações.';
                $strings['buyCredits']               = 'Comprar créditos';
                $strings['cancel']                   = 'Cancelar';
                $strings['settings']                 = 'Configurações';
                break;
            case 'ru':
                $strings['missingConnectionTitle']   = 'Нет соединения с PackshotPhoto AI';
                $strings['missingConnectionMessage'] = 'Нет соединения с сервером PackshotPhoto AI. Пожалуйста, подключитесь к нашему сервису на странице настроек, чтобы использовать генерацию ИИ. Вы получите 10 бесплатных кредитов для начала!';
                $strings['insufficientCreditsTitle'] = 'Недостаточно кредитов ИИ';
                $strings['insufficientCreditsMessage'] = 'Вы исчерпали свои бесплатные стартовые кредиты или на вашем счету недостаточно средств. Вы можете приобрести пакет дополнительных кредитов на странице настроек.';
                $strings['buyCredits']               = 'Купить кредиты';
                $strings['cancel']                   = 'Отмена';
                $strings['settings']                 = 'Настройки';
                break;
            case 'zh':
                $strings['missingConnectionTitle']   = '无PackshotPhoto AI连接';
                $strings['missingConnectionMessage'] = '未连接到 PackshotPhoto AI 服务器。请在设置页面中连接我们的服务以使用 AI 生成。您将获得 10 个免费点数作为开始！';
                $strings['insufficientCreditsTitle'] = 'AI 点数不足';
                $strings['insufficientCreditsMessage'] = '您的免费体验点数已用完，或您的账户余额不足。您可以在设置页面购买额外的点数包。';
                $strings['buyCredits']               = '购买点数';
                $strings['cancel']                   = '取消';
                $strings['settings']                 = '设置';
                break;
            case 'ja':
                $strings['missingConnectionTitle']   = 'PackshotPhoto AIへの接続がありません';
                $strings['missingConnectionMessage'] = 'PackshotPhoto AIサーバーへの接続がありません。AI生成を使用するには、設定ページでサービスに接続してください。開始時に10個の無料クレジットが提供されます！';
                $strings['insufficientCreditsTitle'] = 'AIクレジットが不足しています';
                $strings['insufficientCreditsMessage'] = '無料のスタータークレジットを使い切ったか、アカウントの残高が不足しています。設定ページで追加クレジットのパッケージを購入できます。';
                $strings['buyCredits']               = 'クレジットを購入';
                $strings['cancel']                   = 'キャンセル';
                $strings['settings']                 = '設定';
                break;
            case 'ko':
                $strings['missingConnectionTitle']   = 'PackshotPhoto AI 연결 없음';
                $strings['missingConnectionMessage'] = 'PackshotPhoto AI 서버에 연결되어 있지 않습니다. AI 생성을 사용하려면 설정 페이지에서 서비스에 연결하십시오. 시작 시 10개의 무료 크레딧을 받을 수 있습니다!';
                $strings['insufficientCreditsTitle'] = 'AI 크레딧 부족';
                $strings['insufficientCreditsMessage'] = '무료 시작 크레딧을 모두 사용했거나 계정에 잔액이 부족합니다. 설정 페이지에서 추가 크레딧 패키지를 구매할 수 있습니다.';
                $strings['buyCredits']               = '크레딧 구매';
                $strings['cancel']                   = '취소';
                $strings['settings']                 = '설정';
                break;
        }

        return $strings;
    }

    /**
     * AJAX: Log deactivation survey details and forward to central server
     */
    public function ajax_log_deactivation_survey(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');

        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $reason   = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : 'other';
        $details  = isset($_POST['details']) ? sanitize_textarea_field(wp_unslash($_POST['details'])) : '';
        $site_url = home_url('/');
        $api_key  = \PackshotPhotoAI\Core\Encryption::decrypt(get_option('packshotphoto_api_key', ''));

        // Forward to central Supabase edge function
        $endpoint = 'https://duubkqjowabuevqudtbk.supabase.co/functions/v1/deactivation-survey';
        
        $response = wp_remote_post($endpoint, [
            'method'    => 'POST',
            'headers'   => [
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ],
            'body'      => json_encode([
                'reason'   => $reason,
                'details'  => $details,
                'site_url' => $site_url,
                'version'  => PACKSHOTPHOTO_AI_VERSION
            ]),
            'timeout'   => 10,
        ]);

        if (is_wp_error($response)) {
            Core\Logger::error('Deactivation Survey: Failed to forward to SaaS', ['error' => $response->get_error_message()]);
        }

        wp_send_json_success();
    }

    /**
     * Filter attachment image src to bust browser cache in admin
     */
    public function filter_attachment_image_src_cache_bust($image, $attachment_id, $size, $icon) {
        if (!is_admin() || empty($image) || !is_array($image) || empty($image[0])) {
            return $image;
        }
        $mtime = get_post_modified_time('U', false, $attachment_id);
        if ($mtime) {
            $image[0] = add_query_arg('v', $mtime, $image[0]);
        }
        return $image;
    }

    /**
     * Filter attachment image HTML attributes to bust cache on src and srcset
     */
    public function filter_attachment_image_attrs_cache_bust(array $attr, \WP_Post $attachment, $size): array {
        if (!is_admin() || empty($attachment->ID)) {
            return $attr;
        }
        $mtime = get_post_modified_time('U', false, $attachment->ID);
        if ($mtime) {
            if (!empty($attr['src'])) {
                $attr['src'] = add_query_arg('v', $mtime, $attr['src']);
            }
            if (!empty($attr['srcset'])) {
                // Remove srcset in admin list table to prevent modern browsers from loading stale cached srcset versions
                unset($attr['srcset']);
            }
        }
        return $attr;
    }

    /**
     * Run the plugin
     */
    public function run(): void {
        $this->loader->run();
    }
}
