<?php
namespace PackshotPhotoAI\Admin;

use PackshotPhotoAI\Core\Logger;

defined('ABSPATH') || exit;

class SettingsPage {
    private const PAGE_SLUG = 'packshotphoto-ai';
    private const OPTION_GROUP = 'packshotphoto_options';


    public function add_menu_page(): void {
        add_management_page(
            __('PackshotPhoto AI', 'packshotphoto-ai'),
            __('PackshotPhoto AI', 'packshotphoto-ai'),
            'manage_options',
            self::PAGE_SLUG,
            [$this, 'render_page']
        );
    }

    /**
     * Register settings
     */
    public function register_settings(): void {
        // API Key (our service)
        register_setting(self::OPTION_GROUP, 'packshotphoto_api_key', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitize_encrypted'],
            'default'           => '',
        ]);

        // General settings (model, language, sync_slug)
        register_setting(self::OPTION_GROUP, 'packshotphoto_settings', [
            'type'              => 'array',
            'sanitize_callback' => [$this, 'sanitize_settings'],
            'default'           => ['model' => 'gemini-1.5-flash', 'language' => 'auto', 'sync_slug' => '1'],
        ]);

        // Site context
        register_setting(self::OPTION_GROUP, 'packshotphoto_site_context', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
            'default'           => '',
        ]);

        // Max image size
        register_setting(self::OPTION_GROUP, 'packshotphoto_max_image_size', [
            'type'              => 'integer',
            'sanitize_callback' => function($value) {
                // Verify settings page submit nonce
                if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), self::OPTION_GROUP . '-options')) {
                    return absint($value);
                }
                $select_val = isset($_POST['packshotphoto_max_image_size_select']) ? (int)sanitize_text_field(wp_unslash($_POST['packshotphoto_max_image_size_select'])) : 0;
                if ($select_val === -1) {
                    return isset($_POST['packshotphoto_max_image_size_custom']) ? absint(sanitize_text_field(wp_unslash($_POST['packshotphoto_max_image_size_custom']))) : 0;
                }
                return isset($_POST['packshotphoto_max_image_size_select']) ? absint(sanitize_text_field(wp_unslash($_POST['packshotphoto_max_image_size_select']))) : absint($value);
            },
            'default' => 0,
        ]);

        // Delete mode
        register_setting(self::OPTION_GROUP, 'packshotphoto_delete_mode', [
            'type'              => 'string',
            'sanitize_callback' => function($val) {
                return in_array($val, ['trash', 'delete'], true) ? $val : 'trash';
            },
            'default' => 'trash',
        ]);

        // EU AI Act Global Settings
        register_setting(self::OPTION_GROUP, 'packshotphoto_auto_eu_ai', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val === '1' ? '1' : '0'; },
            'default'           => '0',
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_mode', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return in_array($val, ['preset', 'custom'], true) ? $val : 'preset'; },
            'default'           => 'preset',
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_preset', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return array_key_exists($val, \PackshotPhotoAI\Core\EuAiActLabeller::ICONS) ? $val : 'generated-white-trans'; },
            'default'           => 'generated-white-trans',
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_custom_image', [
            'type'              => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default'           => '',
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_position', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return in_array($val, ['bottom-right', 'bottom-left', 'top-right', 'top-left', 'center'], true) ? $val : 'bottom-right'; },
            'default'           => 'bottom-right',
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_scale', [
            'type'              => 'integer',
            'sanitize_callback' => function($val) { return max(5, min(60, absint($val))); },
            'default'           => 15,
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_opacity', [
            'type'              => 'integer',
            'sanitize_callback' => function($val) { return max(10, min(100, absint($val))); },
            'default'           => 100,
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_padding_top', [
            'type'              => 'integer',
            'sanitize_callback' => function($val) { return max(0, min(200, absint($val))); },
            'default'           => 15,
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_padding_right', [
            'type'              => 'integer',
            'sanitize_callback' => function($val) { return max(0, min(200, absint($val))); },
            'default'           => 15,
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_padding_bottom', [
            'type'              => 'integer',
            'sanitize_callback' => function($val) { return max(0, min(200, absint($val))); },
            'default'           => 15,
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_eu_ai_padding_left', [
            'type'              => 'integer',
            'sanitize_callback' => function($val) { return max(0, min(200, absint($val))); },
            'default'           => 15,
        ]);


        // --- DEV tab settings ---

        // Connection type: 'our_service' or 'custom_api'
        register_setting(self::OPTION_GROUP, 'packshotphoto_connection_type', [
            'type'              => 'string',
            'sanitize_callback' => function($val) {
                return in_array($val, ['our_service', 'custom_api'], true) ? $val : 'our_service';
            },
            'default' => 'our_service',
        ]);

        // Custom API endpoint URL
        register_setting(self::OPTION_GROUP, 'packshotphoto_dev_api_endpoint', [
            'type'              => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default'           => '',
        ]);

        // Custom API key
        register_setting(self::OPTION_GROUP, 'packshotphoto_dev_api_key', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitize_encrypted'],
            'default'           => '',
        ]);

        // Custom model name
        register_setting(self::OPTION_GROUP, 'packshotphoto_dev_model', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => 'gpt-4o',
        ]);

        // Stripe Webhook Secret
        register_setting(self::OPTION_GROUP, 'packshotphoto_stripe_webhook_secret', [
            'type'              => 'string',
            'sanitize_callback' => [$this, 'sanitize_encrypted'],
            'default'           => '',
        ]);

        // Custom user prompt
        register_setting(self::OPTION_GROUP, 'packshotphoto_custom_prompt', [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
            'default'           => '',
        ]);

        // Auto-process on upload
        register_setting(self::OPTION_GROUP, 'packshotphoto_auto_process', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val ? '1' : '0'; },
            'default'           => '1',
        ]);

        // Auto-WebP on upload
        register_setting(self::OPTION_GROUP, 'packshotphoto_auto_webp', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val ? '1' : '0'; },
            'default'           => '1',
        ]);

        // Auto-AVIF on upload
        register_setting(self::OPTION_GROUP, 'packshotphoto_auto_avif', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val ? '1' : '0'; },
            'default'           => '1',
        ]);

        // Auto-rename on upload
        register_setting(self::OPTION_GROUP, 'packshotphoto_auto_rename', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val ? '1' : '0'; },
            'default'           => '1',
        ]);

        // Logging
        register_setting(self::OPTION_GROUP, 'packshotphoto_enable_logging', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val ? 'yes' : 'no'; },
            'default'           => 'yes',
        ]);

        register_setting(self::OPTION_GROUP, 'packshotphoto_debug_logging', [
            'type'              => 'string',
            'sanitize_callback' => function($val) { return $val ? 'yes' : 'no'; },
            'default'           => 'no',
        ]);
    }

    /**
     * Sanitize settings array
     */
    public function sanitize_settings(?array $input): array {
        if (!is_array($input)) {
            return [];
        }
        $output = [];

        $output['model'] = sanitize_text_field($input['model'] ?? 'gemini-1.5-flash');

        $allowed_langs = ['auto', 'pl', 'en', 'es', 'de', 'fr', 'it', 'pt', 'nl', 'ru', 'zh', 'ja', 'ko'];
        $output['language'] = in_array($input['language'] ?? 'auto', $allowed_langs, true)
            ? $input['language']
            : 'auto';

        $output['sync_slug'] = isset($input['sync_slug']) ? '1' : '0';

        return $output;
    }

    /**
     * Sanitize and encrypt sensitive fields
     *
     * @param string $value
     * @return string
     */
    public function sanitize_encrypted(?string $value): string {
        // Helper: get the currently stored encrypted value for this option
        $get_stored = function(): string {
            $filter   = current_filter(); // e.g. "sanitize_option_pmm_api_key"
            $opt_name = str_replace('sanitize_option_', '', $filter);
            $known    = ['packshotphoto_api_key', 'packshotphoto_dev_api_key', 'packshotphoto_stripe_webhook_secret'];
            if (in_array($opt_name, $known, true)) {
                return (string) get_option($opt_name, '');
            }
            return '';
        };

        // Field was NOT submitted at all (other tab was active) — preserve stored value
        if ($value === null) {
            return $get_stored();
        }

        $value = sanitize_text_field($value);

        // Field was submitted but left empty — preserve stored value
        if (empty($value)) {
            return $get_stored();
        }

        // Only encrypt if it's not already encrypted (prevents double encryption)
        if (\PackshotPhotoAI\Core\Encryption::is_encrypted($value)) {
            return $value;
        }

        return \PackshotPhotoAI\Core\Encryption::encrypt($value);
    }

    /**
     * Render settings page — tabbed layout
     */
    public function render_page(): void {
        
        // Allow access in dev mode or if user can manage options
        if (!defined('PACKSHOTPHOTO_AI_DEV_MODE') || !PACKSHOTPHOTO_AI_DEV_MODE) {
            if (!current_user_can('manage_options')) {
                return;
            }
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $active_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'main';
        $page_url   = admin_url('tools.php?page=' . self::PAGE_SLUG);
        ?>
        <div class="wrap packshotphoto-settings-page">
            <h1 class="wp-heading-inline">
                <?php echo esc_html(get_admin_page_title()); ?>
            </h1>
            <hr class="wp-header-end">

            <nav class="nav-tab-wrapper" style="margin-bottom: 20px;">
                <a href="<?php echo esc_url($page_url . '&tab=main'); ?>" class="nav-tab <?php echo $active_tab === 'main' ? 'nav-tab-active' : ''; ?>">
                    ⚙️ <?php esc_html_e('General Settings', 'packshotphoto-ai'); ?>
                </a>
                <a href="<?php echo esc_url($page_url . '&tab=dev'); ?>" class="nav-tab <?php echo $active_tab === 'dev' ? 'nav-tab-active' : ''; ?>">
                    🛠️ <?php esc_html_e('AI Source', 'packshotphoto-ai'); ?>
                </a>
            </nav>

            <form action="options.php" method="post" id="packshotphoto-main-form">
                <?php settings_fields(self::OPTION_GROUP); ?>

                <?php if ($active_tab === 'main') : ?>
                    <?php $this->render_main_tab(); ?>
                <?php elseif ($active_tab === 'dev') : ?>
                    <?php $this->render_dev_tab(); ?>
                <?php endif; ?>

                <div style="margin-top: 30px;">
                    <?php submit_button(__('Save Settings', 'packshotphoto-ai')); ?>
                </div>
            </form>

            <?php
            $locale = function_exists('get_user_locale') ? get_user_locale() : 'en_US';
            $lang_code = strtolower(substr($locale, 0, 2));
            
            switch ($lang_code) {
                case 'pl':
                    $footer_text = 'Pomoc i dokumentacja: %s';
                    break;
                case 'de':
                    $footer_text = 'Hilfe & Dokumentation: %s';
                    break;
                case 'es':
                    $footer_text = 'Soporte y documentación: %s';
                    break;
                case 'fr':
                    $footer_text = 'Support & Documentation: %s';
                    break;
                case 'it':
                    $footer_text = 'Supporto e documentazione: %s';
                    break;
                case 'nl':
                    $footer_text = 'Ondersteuning & documentatie: %s';
                    break;
                case 'pt':
                    $footer_text = 'Suporte e documentação: %s';
                    break;
                case 'ru':
                    $footer_text = 'Поддержка и документация: %s';
                    break;
                case 'zh':
                    $footer_text = '支持与文档: %s';
                    break;
                case 'ja':
                    $footer_text = 'サポートとドキュメント: %s';
                    break;
                case 'ko':
                    $footer_text = '지원 및 문서: %s';
                    break;
                default:
                    $footer_text = 'Support & Documentation: %s';
                    break;
            }
            ?>
            <div class="packshotphoto-settings-footer" style="margin-top: 40px; border-top: 1px solid #ccd0d4; padding-top: 15px; text-align: center; color: #646970; font-size: 13px;">
                <p><?php printf(esc_html($footer_text), '<a href="https://packshotphoto.com" target="_blank" rel="noopener noreferrer" style="color: #2271b1; text-decoration: none; font-weight: 600;">packshotphoto.com</a>'); ?></p>
            </div>

        </div>
        <?php
    }

    /**
     * Render a tooltip icon with text
     */
    private function render_tooltip(string $text): void {
        ?>
        <span class="packshotphoto-tooltip-container">
            <span class="packshotphoto-help-icon">?</span>
            <span class="packshotphoto-tooltip-text"><?php echo esc_html($text); ?></span>
        </span>
        <?php
    }

    /**
     * Render the Main tab
     */
    private function render_main_tab(): void {
        ?>
            <div class="packshotphoto-settings-grid">
                <div class="packshotphoto-main-settings">

                    <!-- Context section -->
                    <h2>
                        <?php esc_html_e('Site Context (SEO)', 'packshotphoto-ai'); ?>
                        <?php $this->render_tooltip(__('Describe what your site does (e.g., "Sports shoe store"). AI will use this to match keywords and description style to your industry.', 'packshotphoto-ai')); ?>
                    </h2>
                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row"><?php esc_html_e('Site Description', 'packshotphoto-ai'); ?></th>
                            <td><?php $this->render_site_context_field(); ?></td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('Description Language', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('Choose a fixed language or "Automatic", which will match your site settings.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_language_field(); ?></td>
                        </tr>
                    </table>

                    <!-- Image processing -->
                    <h2><?php esc_html_e('Auto Upload Conversion', 'packshotphoto-ai'); ?></h2>
                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('Max Image Size', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('All uploaded images larger than this limit will be automatically resized, saving disk space and speeding up the site.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_max_size_field(); ?></td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('Meta Descriptions (Auto-Process)', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('When enabled, every new image added to the library will be automatically processed by AI in the background.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_auto_process_field(); ?></td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('WebP Conversion', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('Automatically convert every newly uploaded image to WebP format.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_auto_webp_field(); ?></td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('AVIF Conversion', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('Automatically convert every newly uploaded image to AVIF format.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_auto_avif_field(); ?></td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('File Rename & URL Sync', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('Automatically rename uploaded files and sync their URLs.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_auto_rename_field(); ?></td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <?php esc_html_e('Original File Backup', 'packshotphoto-ai'); ?>
                                <?php $this->render_tooltip(__('When enabled, the original file is moved to a backup folder instead of being deleted. Backups are automatically removed after 30 days to save disk space.', 'packshotphoto-ai')); ?>
                            </th>
                            <td><?php $this->render_delete_mode_field(); ?></td>
                        </tr>
                    </table>

                    <!-- EU AI Act Transparency Section -->
                    <?php $this->render_eu_ai_act_section(); ?>

                    <!-- Credits / Pricing section -->
                    <?php $this->render_credits_section(); ?>
                </div>

                <div class="packshotphoto-sidebar">
                    <div class="packshotphoto-info-box packshotphoto-info-box-sidebar" style="border-left-color: #3b82f6;">
                        <h3>💡 <?php esc_html_e('Quick Start Guide', 'packshotphoto-ai'); ?></h3>
                        <ul>
                            <li><strong>1. <?php esc_html_e('Context', 'packshotphoto-ai'); ?></strong>: <?php esc_html_e('Enter your business description. AI will stop writing generalities and start using your keywords.', 'packshotphoto-ai'); ?></li>
                            <li><strong>2. <?php esc_html_e('Auto-Pilot', 'packshotphoto-ai'); ?></strong>: <?php esc_html_e('Enable Auto-Processing. From now on, every uploaded image will receive SEO automatically.', 'packshotphoto-ai'); ?></li>
                            <li><strong>3. <?php esc_html_e('WebP', 'packshotphoto-ai'); ?></strong>: <?php esc_html_e('Go to the media library and use "Convert to WebP" to drastically speed up your site.', 'packshotphoto-ai'); ?></li>
                        </ul>
                    </div>

                    <div class="packshotphoto-info-box packshotphoto-info-box-sidebar">
                        <h3>🚀 <?php esc_html_e('Pro Tips', 'packshotphoto-ai'); ?></h3>
                        <ul>
                            <li><?php esc_html_e('You can edit multiple fields at once in the library — changes are saved automatically (debouncing).', 'packshotphoto-ai'); ?></li>
                            <li><?php esc_html_e('Bulk actions are best performed after selecting files in the list and choosing "🤖 AI - Generate descriptions".', 'packshotphoto-ai'); ?></li>
                        </ul>
                    </div>

                    <div class="packshotphoto-info-box packshotphoto-info-box-sidebar" style="border-left-color: var(--packshotphoto-success);">
                        <h3>🤖 <?php esc_html_e('AI Insights', 'packshotphoto-ai'); ?></h3>
                        <p style="font-size: 12px; color: var(--packshotphoto-text-muted);">
                            <?php esc_html_e('Our AI analyzes not only image content, but also its composition and textures to create descriptions that Google robots consider most helpful for users.', 'packshotphoto-ai'); ?>
                        </p>
                    </div>

                    <div class="packshotphoto-info-box packshotphoto-info-box-sidebar" style="border-left-color: #f59e0b; background: #fffbeb;">
                        <h3 style="color: #d97706;">❤️ <?php esc_html_e('Thank You!', 'packshotphoto-ai'); ?></h3>
                        <p style="font-size: 12px; color: #92400e; margin-top: 10px;">
                            <?php esc_html_e('Thank you for your trust and support! We are committed to continuously developing and improving our plugin to make working with media even easier for you.', 'packshotphoto-ai'); ?>
                        </p>
                    </div>

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

    /**
     * Render the DEV tab
     */
    private function render_dev_tab(): void {
        $connection_type  = get_option('packshotphoto_connection_type', 'our_service');
        $dev_endpoint     = get_option('packshotphoto_dev_api_endpoint', '');
        $dev_model        = get_option('packshotphoto_dev_model', 'gpt-4o');
        $dev_key          = \PackshotPhotoAI\Core\Encryption::decrypt(get_option('packshotphoto_dev_api_key', ''));
        $custom_prompt    = get_option('packshotphoto_custom_prompt', '');
        ?>
            <div class="packshotphoto-settings-grid">
                <div class="packshotphoto-main-settings">

                    <!-- Connection type -->
                    <h2>
                        <?php esc_html_e('AI Source', 'packshotphoto-ai'); ?>
                        <?php $this->render_tooltip(__('Choose whether to use our cloud (credits), or connect your own AI model (e.g., OpenAI, Groq, Ollama).', 'packshotphoto-ai')); ?>
                    </h2>
                    <p><?php esc_html_e('Choose AI provider. "Our Service" uses your purchased credits. "Custom API" requires your own OpenAI-compatible endpoint.', 'packshotphoto-ai'); ?></p>

                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row"><?php esc_html_e('Connection', 'packshotphoto-ai'); ?></th>
                            <td>
                                <fieldset>
                                    <label>
                                        <input type="radio" name="packshotphoto_connection_type" value="our_service"
                                               <?php checked($connection_type, 'our_service'); ?>>
                                        <?php esc_html_e('Our Service (Credits)', 'packshotphoto-ai'); ?>
                                    </label>
                                    <br><br>
                                    <label>
                                        <input type="radio" name="packshotphoto_connection_type" value="custom_api"
                                               <?php checked($connection_type, 'custom_api'); ?>>
                                        <?php esc_html_e('Custom API (OpenAI-compatible)', 'packshotphoto-ai'); ?>
                                    </label>
                                </fieldset>
                            </td>
                        </tr>
                    </table>

                    <!-- Our service settings -->
                    <div id="packshotphoto-section-our-service" style="<?php echo 'our_service' !== $connection_type ? 'display:none' : ''; ?>">
                        <h3><?php esc_html_e('Our Service', 'packshotphoto-ai'); ?></h3>
                        <p class="description"><?php esc_html_e('Using our high-performance AI infrastructure (intermediary service).', 'packshotphoto-ai'); ?></p>
                        
                        <input type="hidden" name="packshotphoto_api_key" 
                               value="<?php echo esc_attr(\PackshotPhotoAI\Core\Encryption::decrypt(get_option('packshotphoto_api_key', ''))); ?>" />

                        <!-- Embed Billing Tab here inside Our Service -->
                        <div style="margin-top: 30px;">
                            <?php $this->render_billing_tab(); ?>
                        </div>
                    </div>

                    <!-- Custom API settings -->
                    <div id="packshotphoto-section-custom-api" style="<?php echo 'custom_api' !== $connection_type ? 'display:none' : ''; ?>">
                        <h3><?php esc_html_e('Custom API (OpenAI-compatible)', 'packshotphoto-ai'); ?></h3>
                        <p class="description"><?php esc_html_e('Supports: OpenAI, Groq, Together AI, Ollama, LM Studio and any other provider with /chat/completions endpoint.', 'packshotphoto-ai'); ?></p>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th scope="row"><?php esc_html_e('Endpoint URL', 'packshotphoto-ai'); ?></th>
                                <td>
                                    <input type="url" id="packshotphoto_dev_api_endpoint" name="packshotphoto_dev_api_endpoint"
                                           value="<?php echo esc_attr($dev_endpoint); ?>"
                                           class="large-text"
                                           placeholder="https://api.openai.com/v1"/>
                                    <p class="description"><?php esc_html_e('Provide base URL — plugin will add /chat/completions automatically.', 'packshotphoto-ai'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('Model Name', 'packshotphoto-ai'); ?></th>
                                <td>
                                    <input type="text" id="packshotphoto_dev_model" name="packshotphoto_dev_model"
                                           value="<?php echo esc_attr($dev_model); ?>"
                                           class="regular-text"
                                           placeholder="gpt-4o"/>
                                    <p class="description"><?php esc_html_e('E.g., gpt-4o, llama3, mixtral-8x7b. Model must support vision/multimodal.', 'packshotphoto-ai'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e('API Key', 'packshotphoto-ai'); ?></th>
                                <td>
                                    <input type="password" id="packshotphoto_dev_api_key" name="packshotphoto_dev_api_key"
                                           value="<?php echo esc_attr($dev_key); ?>"
                                           class="regular-text" autocomplete="off"/>
                                    <p class="description"><?php esc_html_e('Optional for local endpoints (Ollama, LM Studio).', 'packshotphoto-ai'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">&nbsp;</th>
                                <td>
                                    <button type="button" class="button button-secondary" id="packshotphoto-test-custom-api">
                                        <?php esc_html_e('Test Connection', 'packshotphoto-ai'); ?>
                                    </button>
                                    <span class="packshotphoto-custom-test-result"></span>
                                </td>
                            </tr>
                            <!-- Webhook secret removed -->
                        </table>
                    </div>

                    <hr>

                    <hr>
 
                     <?php /*
                     <!-- Logging -->
                     <h2><?php esc_html_e('System Logs', 'packshotphoto-ai'); ?></h2>
                     <table class="form-table" role="presentation">
                         <tr>
                             <th scope="row"><?php esc_html_e('Enable Logging', 'packshotphoto-ai'); ?></th>
                             <td><?php $this->render_logging_field(); ?></td>
                         </tr>
                         <tr>
                             <th scope="row"><?php esc_html_e('Debug Mode (Verbose)', 'packshotphoto-ai'); ?></th>
                             <td><?php $this->render_debug_logging_field(); ?></td>
                         </tr>
                     </table>
                     */ ?>
                     <?php /* ... Logging ... */ ?>
                </div>

                <div class="packshotphoto-sidebar">
                    <div class="packshotphoto-info-box packshotphoto-info-box-sidebar" style="border-left-color: #a855f7;">
                        <h3>🔌 <?php esc_html_e('Connecting Custom API', 'packshotphoto-ai'); ?></h3>
                        <p style="font-size: 12px; color: var(--packshotphoto-text-muted);">
                            <?php esc_html_e('Supports any OpenAI-compatible API including Groq, Anthropic (via proxy), and local models like Ollama or LM Studio.', 'packshotphoto-ai'); ?>
                        </p>
                    </div>

                    <div class="packshotphoto-info-box packshotphoto-info-box-sidebar" style="border-left-color: #ec4899;">
                        <h3>🛡️ <?php esc_html_e('Security', 'packshotphoto-ai'); ?></h3>
                        <p style="font-size: 11px; color: var(--packshotphoto-text-muted);">
                            <?php esc_html_e('API keys are encrypted in the WordPress database using standard security mechanisms. Never share your keys with third parties.', 'packshotphoto-ai'); ?>
                        </p>
                    </div>

                    <!-- Danger Zone removed -->
                </div>
            </div>
        <?php
        wp_enqueue_script(
            'packshotphoto-settings-dev-js',
            PACKSHOTPHOTO_AI_URL . 'assets/js/packshotphoto-settings-dev.js',
            [],
            PACKSHOTPHOTO_AI_VERSION,
            true
        );
        ?>
        <?php
    }

    /**
     * Render the credits / pricing section
     */
    private function render_credits_section(): void {
        // Legacy — now handled by render_billing_tab()
    }

    /**
     * Render the new Billing tab — real-time balance, history, Stripe Checkout
     */
    private function render_billing_tab(): void {
        $balance     = (int)get_option('packshotphoto_credits_balance', 0);
        $max_credits = 5000; // For progress bar reference
        $pct         = $max_credits > 0 ? min(100, round($balance / $max_credits * 100)) : 0;
        $bar_color   = $balance > 500 ? '#22c55e' : ($balance > 50 ? '#f59e0b' : '#ef4444');
        
        wp_enqueue_style(
            'packshotphoto-settings-billing-css',
            PACKSHOTPHOTO_AI_URL . 'assets/css/packshotphoto-settings-billing.css',
            [],
            PACKSHOTPHOTO_AI_VERSION
        );
        wp_enqueue_script(
            'packshotphoto-settings-billing-js',
            PACKSHOTPHOTO_AI_URL . 'assets/js/packshotphoto-settings-billing.js',
            [],
            PACKSHOTPHOTO_AI_VERSION,
            true
        );
        ?>
        <div class="packshotphoto-billing-panel" id="packshotphoto-billing-panel">

            <!-- Header -->
            <h2 style="display:flex; align-items:center; gap:10px; margin-bottom:24px;">
                💳 <?php esc_html_e('Credits & Billing', 'packshotphoto-ai'); ?>
            </h2>

            <div class="packshotphoto-billing-grid">

                <!-- ─── Balance widget ─────────────────────────── -->
                <div class="packshotphoto-billing-card packshotphoto-balance-card">
                    <div class="packshotphoto-balance-header">
                        <span class="packshotphoto-balance-icon">🪙</span>
                        <div>
                            <div class="packshotphoto-balance-number" id="packshotphoto-balance-number"><?php echo esc_html(number_format_i18n($balance)); ?></div>
                            <div class="packshotphoto-balance-label"><?php esc_html_e('AI Credits remaining', 'packshotphoto-ai'); ?></div>
                        </div>
                        <div style="margin-left: auto; text-align: right;">
                             <!-- Manual Sync button removed per user request -->
                        </div>
                    </div>
                    <div class="packshotphoto-progress-bar-track">
                        <div class="packshotphoto-progress-bar-fill" id="packshotphoto-balance-bar"
                             style="width:<?php echo esc_attr($pct); ?>%; background:<?php echo esc_attr($bar_color); ?>;"></div>
                    </div>
                    <div class="packshotphoto-balance-meta" id="packshotphoto-balance-meta">
                        <?php
                        printf(
                            /* translators: 1: explainer text, 2: percent value */
                            esc_html__('%1$s &bull; %2$d%% of max plan', 'packshotphoto-ai'),
                            /* translators: credit to AI generation equivalence description */
                            esc_html__('1 credit = 1 AI generation', 'packshotphoto-ai'),
                            absint($pct)
                        );
                        ?>
                    </div>
                </div>

                <!-- ─── Buy credits ────────────────────────────── -->
                <div class="packshotphoto-billing-card">
                    <?php
                    $promo = \PackshotPhotoAI\Core\CreditManager::get_welcome_promo_status();
                    $is_promo = $promo['active'];
                    ?>

                    <?php if ($is_promo): ?>
                    <div class="packshotphoto-welcome-promo-banner" id="packshotphoto-welcome-promo" data-expire="<?php echo esc_attr($promo['expire_timestamp']); ?>">
                        <div class="packshotphoto-promo-left">
                            <span class="packshotphoto-promo-tag">🔥 <?php esc_html_e('Special Welcome Offer', 'packshotphoto-ai'); ?></span>
                            <h4 class="packshotphoto-promo-title">🎉 <?php esc_html_e('50% OFF All Packages!', 'packshotphoto-ai'); ?></h4>
                            <p class="packshotphoto-promo-sub"><?php esc_html_e('Special introductory discount for new installations. Limited time offer!', 'packshotphoto-ai'); ?></p>
                        </div>
                        <div class="packshotphoto-promo-timer-wrap">
                            <span class="packshotphoto-timer-label"><?php esc_html_e('Ends in:', 'packshotphoto-ai'); ?></span>
                            <span class="packshotphoto-timer-digits" id="packshotphoto-promo-countdown">12:00:00</span>
                        </div>
                    </div>
                    <?php endif; ?>

                    <h3 style="margin-top:0;"><?php esc_html_e('Buy Credits', 'packshotphoto-ai'); ?></h3>
                    <p class="description" style="margin-bottom:16px;">
                        <?php esc_html_e('Credits are assigned to this site automatically after payment. No manual key entry needed.', 'packshotphoto-ai'); ?>
                    </p>

                    <div class="packshotphoto-package-grid">

                        <div class="packshotphoto-package-card" data-package="starter">
                            <div class="packshotphoto-pkg-name"><?php esc_html_e('Starter', 'packshotphoto-ai'); ?></div>
                            <div class="packshotphoto-pkg-credits">200 cr</div>
                            <div class="packshotphoto-pkg-price" style="margin-bottom: 12px;">
                                <?php if ($is_promo): ?>
                                    <div style="display:flex; align-items:center; justify-content:center; gap:8px;">
                                        <s style="color:#94a3b8; font-size:13px; text-decoration:line-through;">2 USD</s>
                                        <strong style="color:#16a34a; font-size:16px; font-weight:800;">1 USD</strong>
                                        <span style="background:#dcfce7; color:#166534; font-size:11px; font-weight:700; padding:2px 6px; border-radius:4px;">-50%</span>
                                    </div>
                                <?php else: ?>
                                    <strong style="font-size:15px; color:#475569;">2 USD</strong>
                                <?php endif; ?>
                            </div>
                            <a href="<?php echo esc_url(wp_nonce_url(admin_url('tools.php?page=packshotphoto-ai&packshotphoto_buy=starter'), 'packshotphoto_buy_package')); ?>" class="button packshotphoto-buy-btn"><?php esc_html_e('Buy →', 'packshotphoto-ai'); ?></a>
                        </div>

                        <div class="packshotphoto-package-card packshotphoto-package-featured" data-package="pro">
                            <div class="packshotphoto-pkg-badge"><?php esc_html_e('Best value', 'packshotphoto-ai'); ?></div>
                            <div class="packshotphoto-pkg-name"><?php esc_html_e('Pro', 'packshotphoto-ai'); ?></div>
                            <div class="packshotphoto-pkg-credits">1250 cr</div>
                            <div class="packshotphoto-pkg-price" style="margin-bottom: 12px;">
                                <?php if ($is_promo): ?>
                                    <div style="display:flex; align-items:center; justify-content:center; gap:8px;">
                                        <s style="color:#94a3b8; font-size:13px; text-decoration:line-through;">10 USD</s>
                                        <strong style="color:#16a34a; font-size:16px; font-weight:800;">5 USD</strong>
                                        <span style="background:#dcfce7; color:#166534; font-size:11px; font-weight:700; padding:2px 6px; border-radius:4px;">-50%</span>
                                    </div>
                                <?php else: ?>
                                    <strong style="font-size:15px; color:#475569;">10 USD</strong>
                                <?php endif; ?>
                            </div>
                            <a href="<?php echo esc_url(wp_nonce_url(admin_url('tools.php?page=packshotphoto-ai&packshotphoto_buy=pro'), 'packshotphoto_buy_package')); ?>" class="button button-primary packshotphoto-buy-btn"><?php esc_html_e('Buy →', 'packshotphoto-ai'); ?></a>
                        </div>

                        <div class="packshotphoto-package-card" data-package="business">
                            <div class="packshotphoto-pkg-name"><?php esc_html_e('Business', 'packshotphoto-ai'); ?></div>
                            <div class="packshotphoto-pkg-credits">5500 cr</div>
                            <div class="packshotphoto-pkg-price" style="margin-bottom: 12px;">
                                <?php if ($is_promo): ?>
                                    <div style="display:flex; align-items:center; justify-content:center; gap:8px;">
                                        <s style="color:#94a3b8; font-size:13px; text-decoration:line-through;">50 USD</s>
                                        <strong style="color:#16a34a; font-size:16px; font-weight:800;">25 USD</strong>
                                        <span style="background:#dcfce7; color:#166534; font-size:11px; font-weight:700; padding:2px 6px; border-radius:4px;">-50%</span>
                                    </div>
                                <?php else: ?>
                                    <strong style="font-size:15px; color:#475569;">50 USD</strong>
                                <?php endif; ?>
                            </div>
                            <a href="<?php echo esc_url(wp_nonce_url(admin_url('tools.php?page=packshotphoto-ai&packshotphoto_buy=business'), 'packshotphoto_buy_package')); ?>" class="button packshotphoto-buy-btn"><?php esc_html_e('Buy →', 'packshotphoto-ai'); ?></a>
                        </div>

                    </div>

                    <div id="packshotphoto-checkout-status" style="display:none; margin-top:16px;" class="packshotphoto-checkout-status">
                        <span class="packshotphoto-spinner-inline"></span>
                        <span id="packshotphoto-checkout-msg"><?php esc_html_e('Waiting for payment confirmation...', 'packshotphoto-ai'); ?></span>
                    </div>

                    <p class="description" style="margin-top:12px; font-size:11px; color:#888;">
                        ✅ <?php esc_html_e('Secure payment via Stripe · Credits assigned automatically · Email confirmation', 'packshotphoto-ai'); ?>
                    </p>
                </div>

            </div><!-- .packshotphoto-billing-grid -->


        </div><!-- .packshotphoto-billing-panel -->

        <div style="margin-top: 40px; text-align: center;">
            <div style="display:flex; gap:10px; align-items:center; justify-content: center; margin-bottom: 15px;">
                <button type="button" class="button button-secondary" id="packshotphoto-test-api">
                    <?php esc_html_e('Test Connection', 'packshotphoto-ai'); ?>
                </button>
                <button type="button" id="packshotphoto-refresh-balance" class="button button-secondary">
                    ↻ <?php esc_html_e('Refresh Credits', 'packshotphoto-ai'); ?>
                </button>
                <span class="packshotphoto-test-result"></span>
            </div>
            <p style="color: var(--packshotphoto-text-muted);">
                <?php esc_html_e('Test your connection to our servers. If you encounter errors, contact us at:', 'packshotphoto-ai'); ?> 
                <a href="mailto:support@packshotphoto.com">support@packshotphoto.com</a>
            </p>
        </div>
        <?php
    }

    // ─── Field renderers ───────────────────────────────────────────────────────

    public function render_api_section(): void {
        echo '<p>';
        printf(
            /* translators: %s: Google AI Studio link */
            esc_html__('Configure connection to Google Gemini AI. You can generate API key in %s.', 'packshotphoto-ai'),
            /* translators: link anchor text for Google AI Studio website */
            '<a href="https://aistudio.google.com/apikey" target="_blank">' . esc_html__('Google AI Studio', 'packshotphoto-ai') . '</a>'
        );
        echo '</p>';
    }

    public function render_api_key_field(): void {
        $value = \PackshotPhotoAI\Core\Encryption::decrypt(get_option('packshotphoto_api_key', ''));
        ?>
        <div class="packshotphoto-api-key-wrapper">
            <input type="password" id="packshotphoto_api_key" name="packshotphoto_api_key"
                   value="<?php echo esc_attr($value); ?>"
                   class="regular-text" autocomplete="off"/>
            <button type="button" class="button button-secondary" id="packshotphoto-test-api">
                <?php esc_html_e('Test Connection', 'packshotphoto-ai'); ?>
            </button>
            <span class="packshotphoto-test-result"></span>
        </div>
        <p class="description"><?php esc_html_e('Key is securely stored in WordPress database.', 'packshotphoto-ai'); ?></p>
        <?php
    }

    public function render_model_field(): void {
        $settings = get_option('packshotphoto_settings', []);
        $current  = $settings['model'] ?? 'gemini-1.5-flash';

        $models = [
            'gemini-1.5-flash' => 'Gemini 1.5 Flash (Fast)',
            'gemini-2.0-flash' => 'Gemini 2.0 Flash (Latest)',
            'gemini-1.5-pro'   => 'Gemini 1.5 Pro (High Accuracy)',
        ];
        ?>
        <select name="packshotphoto_settings[model]" id="packshotphoto_model">
            <?php foreach ($models as $value => $label) : ?>
                <option value="<?php echo esc_attr($value); ?>" <?php selected($current, $value); ?>>
                    <?php echo esc_html($label); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php
    }

    public function render_language_field(): void {
        $settings = get_option('packshotphoto_settings', []);
        $current  = $settings['language'] ?? 'auto';

        $langs = [
            'auto' => __('Automatic (Site Language)', 'packshotphoto-ai'),
            'pl'   => 'Polski',
            'en'   => 'English',
            'es'   => 'Español',
            'de'   => 'Deutsch',
            'fr'   => 'Français',
            'it'   => 'Italiano',
            'pt'   => 'Português',
            'nl'   => 'Nederlands',
            'ru'   => 'Русский',
            'zh'   => 'Chinese (Simplified)',
            'ja'   => 'Japanese',
            'ko'   => 'Korean',
        ];
        ?>
        <select name="packshotphoto_settings[language]" id="packshotphoto_language">
            <?php foreach ($langs as $code => $label) : ?>
                <option value="<?php echo esc_attr($code); ?>" <?php selected($current, $code); ?>>
                    <?php echo esc_html($label); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <p class="description"><?php esc_html_e('Language for AI-generated SEO descriptions.', 'packshotphoto-ai'); ?></p>
        <?php
    }




    public function render_auto_process_field(): void {
        $value = get_option('packshotphoto_auto_process', '1');
        ?>
        <label>
            <input type="checkbox" name="packshotphoto_auto_process" value="1" <?php checked($value, '1'); ?>>
            <?php esc_html_e('Automatically generate AI descriptions on every image upload.', 'packshotphoto-ai'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Processing happens in background (WP Cron) ~1 second after upload.', 'packshotphoto-ai'); ?>
        </p>
        <?php
    }

    public function render_auto_webp_field(): void {
        $value  = get_option('packshotphoto_auto_webp', '1');
        ?>
        <label>
            <input type="checkbox" name="packshotphoto_auto_webp" value="1" <?php checked($value, '1'); ?>>
            <?php esc_html_e('Automatically convert uploaded images to WebP.', 'packshotphoto-ai'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Speeds up your site by reducing file size. Recommended for performance.', 'packshotphoto-ai'); ?>
        </p>
        <?php
    }

    public function render_auto_avif_field(): void {
        $value  = get_option('packshotphoto_auto_avif', '0');
        ?>
        <label>
            <input type="checkbox" name="packshotphoto_auto_avif" value="1" <?php checked($value, '1'); ?>>
            <?php esc_html_e('Automatically convert uploaded images to AVIF.', 'packshotphoto-ai'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Provides even better compression than WebP, but may be slower to generate and requires modern browser support.', 'packshotphoto-ai'); ?>
        </p>
        <?php
    }

    public function render_auto_rename_field(): void {
        $auto_rename = get_option('packshotphoto_auto_rename', '1');
        $settings    = get_option('packshotphoto_settings', []);
        $sync_slug   = isset($settings['sync_slug']) ? $settings['sync_slug'] : '1';
        ?>
        <div style="margin-bottom: 12px;">
            <label>
                <input type="checkbox" name="packshotphoto_auto_rename" value="1" <?php checked($auto_rename, '1'); ?>>
                <strong><?php esc_html_e('Auto-Rename on Upload', 'packshotphoto-ai'); ?></strong>
            </label>
            <p class="description" style="margin-top: 4px; margin-left: 24px;">
                <?php esc_html_e('Automatically generates an AI-optimized file name for newly uploaded media.', 'packshotphoto-ai'); ?>
            </p>
        </div>

        <div>
            <label>
                <input type="checkbox" name="packshotphoto_settings[sync_slug]" value="1" <?php checked($sync_slug, '1'); ?>>
                <strong><?php esc_html_e('Sync Slug & Title on Rename', 'packshotphoto-ai'); ?></strong>
            </label>
            <p class="description" style="margin-top: 4px; margin-left: 24px;">
                <?php esc_html_e('If you manually change a file name, its URL (slug) and Title will update automatically to match. Note: While this works seamlessly for new uploads, please use caution when renaming older, published images, as you may need to update their links on your website to prevent 404 errors.', 'packshotphoto-ai'); ?>
            </p>
        </div>
        <?php
    }

    public function render_logging_field(): void {
        $value = get_option('packshotphoto_enable_logging', 'yes');
        ?>
        <label>
            <input type="checkbox" name="packshotphoto_enable_logging" value="yes" <?php checked($value, 'yes'); ?>>
            <?php esc_html_e('Save key events to WordPress error log.', 'packshotphoto-ai'); ?>
        </label>
        <p class="description"><?php esc_html_e('Enabling logging helps diagnose API connection issues.', 'packshotphoto-ai'); ?></p>
        <?php
    }

    public function render_debug_logging_field(): void {
        $value = get_option('packshotphoto_debug_logging', 'no');
        ?>
        <label>
            <input type="checkbox" name="packshotphoto_debug_logging" value="yes" <?php checked($value, 'yes'); ?>>
            <?php esc_html_e('Log detailed AI requests and responses (Payload).', 'packshotphoto-ai'); ?>
        </label>
        <p class="description"><?php esc_html_e('⚠️ Not recommended on production due to log size and data privacy.', 'packshotphoto-ai'); ?></p>
        <?php
    }

    public function render_context_section(): void {
        echo '<p>' . esc_html__('Describe your site niche. AI uses this context for better SEO relevance.', 'packshotphoto-ai') . '</p>';
    }

    public function render_site_context_field(): void {
        $value = get_option('packshotphoto_site_context', '');
        ?>
        <div class="packshotphoto-context-wrapper">
            <textarea id="packshotphoto_site_context" name="packshotphoto_site_context" rows="4" class="large-text"
                      placeholder="<?php esc_attr_e('e.g., Product photography, packshot, e-commerce, professional photos for online stores', 'packshotphoto-ai'); ?>"
            ><?php echo esc_textarea($value); ?></textarea>
            <p class="description">
                <button type="button" class="button button-secondary" id="packshotphoto-fetch-context">
                    <?php esc_html_e('Generate Context with AI', 'packshotphoto-ai'); ?>
                </button>
            </p>
        </div>
        <?php
    }

    public function render_max_size_field(): void {
        $value   = (int) get_option('packshotphoto_max_image_size', 0);
        $options = [
            0    => __('No limit', 'packshotphoto-ai'),
            800  => '800 px',
            1200 => '1200 px',
            1600 => '1600 px',
            1920 => '1920 px',
            2000 => '2000 px',
            2500 => '2500 px',
            -1   => __('Custom...', 'packshotphoto-ai'),
        ];

        $selected     = isset($options[$value]) && $value !== -1 ? $value : -1;
        $custom_style = $selected === -1 ? 'display:inline-block; margin-left:10px;' : 'display:none; margin-left:10px;';
        $custom_val   = $selected === -1 ? $value : '';
        ?>
        <select name="packshotphoto_max_image_size_select" id="packshotphoto_max_image_size_select">
            <?php foreach ($options as $val => $label) : ?>
                <option value="<?php echo esc_attr($val); ?>" <?php selected($selected, $val); ?>>
                    <?php echo esc_html($label); ?>
                </option>
            <?php endforeach; ?>
        </select>

        <input type="number" name="packshotphoto_max_image_size_custom" id="packshotphoto_max_image_size_custom"
               value="<?php echo esc_attr($custom_val); ?>" placeholder="<?php esc_attr_e('e.g. 1500', 'packshotphoto-ai'); ?>"
               style="width: 100px; <?php echo esc_attr($custom_style); ?>"
               min="100" max="9999">

        <p class="description"><?php esc_html_e('Images larger than this limit will be automatically resized upon upload.', 'packshotphoto-ai'); ?></p>

        <?php
        wp_add_inline_script('packshotphoto-admin-js', '(function() {
            var select = document.getElementById("packshotphoto_max_image_size_select");
            var customInput = document.getElementById("packshotphoto_max_image_size_custom");
            if (select && customInput) {
                select.addEventListener("change", function() {
                    customInput.style.display = parseInt(this.value) === -1 ? "inline-block" : "none";
                    if (parseInt(this.value) === -1) customInput.focus();
                });
            }
        })();');
        ?>
        <?php
    }

    public function render_delete_mode_field(): void {
        $value = get_option('packshotphoto_delete_mode', 'trash');
        ?>
        <select name="packshotphoto_delete_mode" id="packshotphoto_delete_mode">
            <option value="trash"  <?php selected($value, 'trash'); ?>><?php esc_html_e('Keep as backup (30 days)', 'packshotphoto-ai'); ?></option>
            <option value="delete" <?php selected($value, 'delete'); ?>><?php esc_html_e('Delete original after processing', 'packshotphoto-ai'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Backups are stored in wp-content/uploads/packshotphoto-trash/ and auto-deleted after 30 days. You can also restore the original file from the Media Library.', 'packshotphoto-ai'); ?></p>
        <?php
    }

    // ─── AJAX handlers ─────────────────────────────────────────────────────────

    public function ajax_test_api(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $api_key_raw = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';

        if ( ! empty( $api_key_raw ) ) {
            // Key sent directly from JS form field — use as-is (plaintext)
            $api_key = $api_key_raw;
        } else {
            // No key in POST — read from DB and DECRYPT
            $api_key = \PackshotPhotoAI\Core\Encryption::decrypt( get_option( 'packshotphoto_api_key', '' ) );
        }

        if ( empty( $api_key ) ) {
            // Auto-provision a free API key inline if not saved yet
            $sync = \PackshotPhotoAI\Core\CreditManager::force_sync();
            if ($sync['success']) {
                $api_key = \PackshotPhotoAI\Core\Encryption::decrypt( get_option( 'packshotphoto_api_key', '' ) );
            }
        }

        if ( empty( $api_key ) ) {
            wp_send_json_error( __( 'Missing Connection to PackshotPhoto AI. Please connect to our service in the Credits & Billing section.', 'packshotphoto-ai' ) );
            return;
        }

        // CloudClient constructor also decrypts if needed, but we pass plaintext here explicitly
        $client = new \PackshotPhotoAI\API\CloudClient( $api_key );
        $result = $client->test_connection();

        if ( $result['success'] ) {
            // Auto-save key with encryption when it was provided via POST
            if ( ! empty( $api_key_raw ) ) {
                update_option( 'packshotphoto_api_key', \PackshotPhotoAI\Core\Encryption::encrypt( $api_key ) );
            }
            wp_send_json_success( $result['message'] );
        } else {
            wp_send_json_error( $result['message'] );
        }
    }

    /**
     * AJAX: Test custom OpenAI-compatible API connection
     */
    public function ajax_test_custom_api(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $endpoint = isset($_POST['endpoint']) ? esc_url_raw(wp_unslash($_POST['endpoint'])) : '';
        $model    = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : 'gpt-4o';
        $api_key  = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';

        if (empty($endpoint)) {
            wp_send_json_error(__('Provide endpoint URL', 'packshotphoto-ai'));
        }

        $client = new \PackshotPhotoAI\API\OpenAIClient($endpoint, $model, $api_key);
        $result = $client->test_connection();

        if ($result['success']) {
            // Auto-save on success
            update_option('packshotphoto_dev_api_endpoint', $endpoint);
            update_option('packshotphoto_dev_model', $model);
            update_option('packshotphoto_dev_api_key', \PackshotPhotoAI\Core\Encryption::encrypt($api_key));
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }

    public function ajax_fetch_context(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $site_url = home_url('/');
        
        // Bypass SSL verification for local development (Local by Flywheel, etc.)
        $http_args = [
            'timeout'    => 15,
            'sslverify'  => false,
            'redirection' => 5,
        ];
        $response = wp_remote_get($site_url, $http_args);

        if (is_wp_error($response)) {
            $error_msg = $response->get_error_message();
            Logger::error('Fetch Context: wp_remote_get failed', ['url' => $site_url, 'error' => $error_msg]);
            wp_send_json_error(__('Could not fetch website: ', 'packshotphoto-ai') . $error_msg);
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code !== 200) {
            Logger::error('Fetch Context: HTTP error', ['code' => $code, 'url' => $site_url]);
            /* translators: %d: HTTP status code */
            wp_send_json_error(sprintf(__('HTTP error %d fetching homepage', 'packshotphoto-ai'), $code));
        }

        $html = wp_remote_retrieve_body($response);
        $text = wp_strip_all_tags($html);
        $text = preg_replace('/\s+/', ' ', $text);
        $text = trim(substr($text, 0, 3000));

        if (empty($text)) {
            wp_send_json_error(__('No content found on homepage', 'packshotphoto-ai'));
        }

        $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';

        $router = new \PackshotPhotoAI\API\ApiRouter();
        $result = $router->summarize_site_context($text, $language);

        if ($result['success']) {
            wp_send_json_success(['context' => $result['data']]);
        } else {
            Logger::error('Fetch Context: AI summarization failed', ['error' => $result['message'] ?? 'unknown']);
            wp_send_json_error($result['message'] ?? __('AI summarization failed', 'packshotphoto-ai'));
        }
    }


    /**
     * AJAX: Save API key with encryption
     */
    public function ajax_save_api_key(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $api_key = isset($_POST['api_key']) ? sanitize_text_field(wp_unslash($_POST['api_key'])) : '';
        $encrypted = \PackshotPhotoAI\Core\Encryption::encrypt($api_key);
        update_option('packshotphoto_api_key', $encrypted);

        wp_send_json_success(__('API key saved', 'packshotphoto-ai'));
    }

    /**
     * AJAX: Save Site Context
     */
    public function ajax_save_site_context(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        $context = isset($_POST['context']) ? sanitize_textarea_field(wp_unslash($_POST['context'])) : '';
        update_option('packshotphoto_site_context', $context);

        wp_send_json_success(__('Site context saved', 'packshotphoto-ai'));
    }

    /**
     * AJAX: Reset all settings
     */
    public function ajax_reset_settings(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions', 'packshotphoto-ai'), 403);
        }

        \PackshotPhotoAI\Core\Activator::reset_plugin();
        wp_send_json_success(__('All settings have been reset to defaults.', 'packshotphoto-ai'));
    }

    /**
     * Render EU AI Act settings section
     */
    private function render_eu_ai_act_section(): void {
        $auto_eu_ai      = get_option('packshotphoto_auto_eu_ai', '0') === '1';
        $mode            = get_option('packshotphoto_eu_ai_mode', 'preset');
        $preset          = get_option('packshotphoto_eu_ai_preset', 'generated-white-trans');
        $custom_image    = get_option('packshotphoto_eu_ai_custom_image', '');
        $position        = get_option('packshotphoto_eu_ai_position', 'bottom-right');
        $scale           = (int) get_option('packshotphoto_eu_ai_scale', 15);
        $opacity         = (int) get_option('packshotphoto_eu_ai_opacity', 100);
        $pad_top         = (int) get_option('packshotphoto_eu_ai_padding_top', 15);
        $pad_right       = (int) get_option('packshotphoto_eu_ai_padding_right', 15);
        $pad_bottom      = (int) get_option('packshotphoto_eu_ai_padding_bottom', 15);
        $pad_left        = (int) get_option('packshotphoto_eu_ai_padding_left', 15);
        $icons_url       = PACKSHOTPHOTO_AI_URL . 'assets/icons/eu-ai/';
        $icons           = \PackshotPhotoAI\Core\EuAiActLabeller::ICONS;
        ?>
        <div class="packshotphoto-eu-ai-section" style="margin-top: 35px; border-top: 1px solid var(--packshotphoto-border); padding-top: 25px;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
                <h2 style="margin: 0; display: flex; align-items: center; gap: 8px;">
                    <span>🇪🇺</span> <?php esc_html_e('EU AI Act Transparency & Watermarks (Art. 50)', 'packshotphoto-ai'); ?>
                </h2>
                <span class="packshotphoto-badge-info" style="font-size: 11px; padding: 3px 8px; border-radius: 4px; background: #eff6ff; color: #1d4ed8; border: 1px solid #bfdbfe; font-weight: 600;">
                    <?php esc_html_e('Compliance Ready', 'packshotphoto-ai'); ?>
                </span>
            </div>
            
            <p class="description" style="margin-bottom: 20px; font-size: 13px; color: var(--packshotphoto-text-muted);">
                <?php esc_html_e('Under the European Union AI Act (Article 50), deployers of AI systems that generate or manipulate image content must ensure that outputs are marked in a machine-readable and visually perceptible manner.', 'packshotphoto-ai'); ?>
            </p>

            <table class="form-table" role="presentation" style="margin-bottom: 10px;">
                <tr>
                    <th scope="row">
                        <?php esc_html_e('Auto-Stamp AI Uploads', 'packshotphoto-ai'); ?>
                        <?php $this->render_tooltip(__('When enabled, every image uploaded and tagged as AI or processed by AI will automatically receive this watermark stamp.', 'packshotphoto-ai')); ?>
                    </th>
                    <td>
                        <label style="font-weight: 500; display: inline-flex; align-items: center; gap: 8px;">
                            <input type="checkbox" name="packshotphoto_auto_eu_ai" id="packshotphoto_auto_eu_ai" value="1" <?php checked($auto_eu_ai); ?>>
                            <?php esc_html_e('Automatically stamp uploaded AI images with the EU AI Act mark', 'packshotphoto-ai'); ?>
                        </label>

                        <div style="margin-top: 12px;">
                            <button type="button" class="button button-secondary" id="packshotphoto-toggle-eu-ai-customization" style="display: inline-flex; align-items: center; gap: 6px; font-weight: 600;">
                                <span>⚙️</span>
                                <span id="packshotphoto-toggle-eu-ai-text"><?php esc_html_e('Customize Label & Appearance', 'packshotphoto-ai'); ?></span>
                                <span class="dashicons dashicons-arrow-down-alt2" id="packshotphoto-toggle-eu-ai-arrow" style="margin-top: 2px;"></span>
                            </button>
                        </div>
                    </td>
                </tr>
            </table>

            <!-- Collapsible Customization Container (Hidden by default) -->
            <div id="packshotphoto-eu-ai-customization-panel" style="display: none; background: #ffffff; border: 1px solid #cbd5e1; border-radius: 8px; padding: 20px; margin-top: 15px; box-shadow: 0 2px 6px rgba(0,0,0,0.04);">
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Label Source / Style', 'packshotphoto-ai'); ?>
                        </th>
                        <td>
                            <div class="packshotphoto-mode-selector" style="display: flex; gap: 20px; margin-bottom: 15px;">
                                <label style="display: inline-flex; align-items: center; gap: 6px; cursor: pointer; font-weight: 600;">
                                    <input type="radio" name="packshotphoto_eu_ai_mode" value="preset" <?php checked($mode, 'preset'); ?> class="packshotphoto-eu-ai-mode-radio">
                                    🏛️ <?php esc_html_e('Official EU AI Act Presets (12 styles)', 'packshotphoto-ai'); ?>
                                </label>
                                <label style="display: inline-flex; align-items: center; gap: 6px; cursor: pointer; font-weight: 600;">
                                    <input type="radio" name="packshotphoto_eu_ai_mode" value="custom" <?php checked($mode, 'custom'); ?> class="packshotphoto-eu-ai-mode-radio">
                                    🎨 <?php esc_html_e('Custom Watermark / Brand Graphic', 'packshotphoto-ai'); ?>
                                </label>
                            </div>

                            <!-- Presets Container -->
                            <div id="packshotphoto-eu-ai-presets-container" style="<?php echo $mode !== 'preset' ? 'display:none;' : ''; ?>">
                                <div class="packshotphoto-preset-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; margin-top: 10px;">
                                    <?php foreach ($icons as $key => $info) : 
                                        $is_white = strpos($info['style'], 'white') !== false;
                                        $bg_color = $is_white ? '#1e293b' : '#f8fafc';
                                        $border_color = $is_white ? '#334155' : '#cbd5e1';
                                        $text_color = $is_white ? '#f8fafc' : '#0f172a';
                                        $is_selected = ($preset === $key);
                                    ?>
                                        <label class="packshotphoto-preset-card <?php echo $is_selected ? 'selected' : ''; ?>" 
                                               style="border: 2px solid <?php echo $is_selected ? '#2271b1' : $border_color; ?>; border-radius: 8px; padding: 10px; cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: space-between; background: <?php echo $bg_color; ?>; transition: all 0.2s ease; position: relative;"
                                               data-key="<?php echo esc_attr($key); ?>"
                                               data-url="<?php echo esc_url($icons_url . $info['file']); ?>">
                                            <div style="width: 100%; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                                <input type="radio" name="packshotphoto_eu_ai_preset" value="<?php echo esc_attr($key); ?>" <?php checked($preset, $key); ?> style="margin: 0;" class="packshotphoto-preset-radio">
                                                <span style="font-size: 10px; text-transform: uppercase; font-weight: 700; color: <?php echo $text_color; ?>; opacity: 0.8;"><?php echo esc_html($info['category']); ?></span>
                                            </div>
                                            <div style="height: 60px; display: flex; align-items: center; justify-content: center; padding: 5px 0;">
                                                <img src="<?php echo esc_url($icons_url . $info['file']); ?>" alt="<?php echo esc_attr($info['label']); ?>" style="max-height: 48px; max-width: 100%; object-fit: contain;">
                                            </div>
                                            <div style="font-size: 11px; font-weight: 600; text-align: center; color: <?php echo $text_color; ?>; margin-top: 6px; line-height: 1.3;">
                                                <?php echo esc_html($info['label']); ?>
                                            </div>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Custom Image Container -->
                            <div id="packshotphoto-eu-ai-custom-container" style="<?php echo $mode !== 'custom' ? 'display:none;' : ''; ?> background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px; margin-top: 10px;">
                                <div style="display: flex; gap: 15px; align-items: center;">
                                    <div id="packshotphoto-custom-image-preview" style="width: 80px; height: 80px; border: 2px dashed #cbd5e1; border-radius: 6px; display: flex; align-items: center; justify-content: center; background: #ffffff; overflow: hidden;">
                                        <?php if (!empty($custom_image)) : ?>
                                            <img src="<?php echo esc_url($custom_image); ?>" style="max-width: 100%; max-height: 100%; object-fit: contain;" alt="Custom watermark preview">
                                        <?php else : ?>
                                            <span style="font-size: 24px; color: #94a3b8;">🖼️</span>
                                        <?php endif; ?>
                                    </div>
                                    <div style="flex: 1;">
                                        <div style="display: flex; gap: 8px; margin-bottom: 6px;">
                                            <input type="text" name="packshotphoto_eu_ai_custom_image" id="packshotphoto_eu_ai_custom_image" value="<?php echo esc_attr($custom_image); ?>" class="regular-text" placeholder="https://.../my-custom-badge.png" style="width: 320px;">
                                            <button type="button" class="button button-secondary" id="packshotphoto-upload-custom-badge">
                                                📁 <?php esc_html_e('Choose from Media', 'packshotphoto-ai'); ?>
                                            </button>
                                            <button type="button" class="button button-link-delete" id="packshotphoto-clear-custom-badge" style="<?php echo empty($custom_image) ? 'display:none;' : ''; ?> color: #d63638;">
                                                ✕ <?php esc_html_e('Remove', 'packshotphoto-ai'); ?>
                                            </button>
                                        </div>
                                        <p class="description" style="margin: 0; font-size: 12px;">
                                            <?php esc_html_e('Recommended: Transparent PNG, WebP or SVG format with clear visibility.', 'packshotphoto-ai'); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Placement, Scale & Opacity', 'packshotphoto-ai'); ?>
                        </th>
                        <td>
                            <div style="display: flex; flex-wrap: wrap; gap: 25px; align-items: flex-start;">
                                <!-- Position Selector -->
                                <div>
                                    <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 6px;">
                                        📍 <?php esc_html_e('Position', 'packshotphoto-ai'); ?>
                                    </label>
                                    <div class="packshotphoto-position-grid" style="display: grid; grid-template-columns: repeat(3, 40px); gap: 6px;">
                                        <?php
                                        $positions = [
                                            'top-left'     => '↖️',
                                            'top-center'   => '',
                                            'top-right'    => '↗️',
                                            'center-left'  => '',
                                            'center'       => '⏺️',
                                            'center-right' => '',
                                            'bottom-left'  => '↙️',
                                            'bottom-center'=> '',
                                            'bottom-right' => '↘️',
                                        ];
                                        foreach ($positions as $pos_key => $pos_icon) :
                                            if (empty($pos_icon)) {
                                                echo '<div style="width:40px; height:40px;"></div>';
                                                continue;
                                            }
                                            $is_active = ($position === $pos_key);
                                        ?>
                                            <label class="packshotphoto-pos-btn <?php echo $is_active ? 'active' : ''; ?>" 
                                                   style="width: 40px; height: 40px; border: 1px solid <?php echo $is_active ? '#2271b1' : '#cbd5e1'; ?>; background: <?php echo $is_active ? '#2271b1' : '#ffffff'; ?>; color: <?php echo $is_active ? '#ffffff' : '#334155'; ?>; border-radius: 6px; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 16px; transition: all 0.2s ease;">
                                                <input type="radio" name="packshotphoto_eu_ai_position" value="<?php echo esc_attr($pos_key); ?>" <?php checked($position, $pos_key); ?> style="display: none;" class="packshotphoto-pos-radio">
                                                <?php echo esc_html($pos_icon); ?>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <!-- Scale Slider -->
                                <div style="min-width: 150px;">
                                    <label for="packshotphoto_eu_ai_scale" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 6px;">
                                        📐 <?php esc_html_e('Scale / Size', 'packshotphoto-ai'); ?>: <span id="packshotphoto-scale-val"><?php echo esc_html($scale); ?>%</span>
                                    </label>
                                    <input type="range" id="packshotphoto_eu_ai_scale" name="packshotphoto_eu_ai_scale" min="5" max="50" step="1" value="<?php echo esc_attr($scale); ?>" style="width: 100%;">
                                    <div style="display: flex; justify-content: space-between; font-size: 10px; color: #64748b;">
                                        <span>5%</span>
                                        <span>15%</span>
                                        <span>50%</span>
                                    </div>
                                </div>

                                <!-- Opacity Slider -->
                                <div style="min-width: 150px;">
                                    <label for="packshotphoto_eu_ai_opacity" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 6px;">
                                        👁️ <?php esc_html_e('Opacity', 'packshotphoto-ai'); ?>: <span id="packshotphoto-opacity-val"><?php echo esc_html($opacity); ?>%</span>
                                    </label>
                                    <input type="range" id="packshotphoto_eu_ai_opacity" name="packshotphoto_eu_ai_opacity" min="10" max="100" step="5" value="<?php echo esc_attr($opacity); ?>" style="width: 100%;">
                                    <div style="display: flex; justify-content: space-between; font-size: 10px; color: #64748b;">
                                        <span>10%</span>
                                        <span>100%</span>
                                    </div>
                                </div>

                                <!-- Live Visual Preview Box -->
                                <div style="margin-left: auto;">
                                    <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 6px;">
                                        ✨ <?php esc_html_e('Live Preview', 'packshotphoto-ai'); ?>
                                    </label>
                                    <div id="packshotphoto-live-preview-box" style="width: 200px; height: 150px; border-radius: 8px; overflow: hidden; position: relative; border: 1px solid #cbd5e1; background: linear-gradient(135deg, #1e293b 0%, #334155 100%); box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);">
                                        <div style="position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: rgba(255,255,255,0.25); font-size: 11px; font-weight: 600; user-select: none;">
                                            📷 SAMPLE IMAGE
                                        </div>
                                        <img id="packshotphoto-preview-stamp" 
                                             src="<?php echo esc_url($mode === 'custom' && !empty($custom_image) ? $custom_image : $icons_url . ($icons[$preset]['file'] ?? 'ai-generated-white-trans.png')); ?>" 
                                             alt="Live Preview Stamp"
                                             style="position: absolute; pointer-events: none; transition: all 0.2s ease; max-width: 90%; max-height: 90%;">
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <?php esc_html_e('Margins & Padding', 'packshotphoto-ai'); ?>
                            <?php $this->render_tooltip(__('Offset in pixels from image edges for precise positioning.', 'packshotphoto-ai')); ?>
                        </th>
                        <td>
                            <div class="packshotphoto-padding-grid" style="display: flex; gap: 15px; align-items: center; max-width: 450px;">
                                <div>
                                    <label for="packshotphoto_eu_ai_padding_top" style="display:block; font-size:11px; font-weight:600; color:#475569; margin-bottom:3px;">
                                        ⬆️ <?php esc_html_e('Top', 'packshotphoto-ai'); ?> (px)
                                    </label>
                                    <input type="number" id="packshotphoto_eu_ai_padding_top" name="packshotphoto_eu_ai_padding_top" value="<?php echo esc_attr($pad_top); ?>" min="0" max="200" step="1" style="width: 75px; text-align: center;">
                                </div>
                                <div>
                                    <label for="packshotphoto_eu_ai_padding_right" style="display:block; font-size:11px; font-weight:600; color:#475569; margin-bottom:3px;">
                                        ➡️ <?php esc_html_e('Right', 'packshotphoto-ai'); ?> (px)
                                    </label>
                                    <input type="number" id="packshotphoto_eu_ai_padding_right" name="packshotphoto_eu_ai_padding_right" value="<?php echo esc_attr($pad_right); ?>" min="0" max="200" step="1" style="width: 75px; text-align: center;">
                                </div>
                                <div>
                                    <label for="packshotphoto_eu_ai_padding_bottom" style="display:block; font-size:11px; font-weight:600; color:#475569; margin-bottom:3px;">
                                        ⬇️ <?php esc_html_e('Bottom', 'packshotphoto-ai'); ?> (px)
                                    </label>
                                    <input type="number" id="packshotphoto_eu_ai_padding_bottom" name="packshotphoto_eu_ai_padding_bottom" value="<?php echo esc_attr($pad_bottom); ?>" min="0" max="200" step="1" style="width: 75px; text-align: center;">
                                </div>
                                <div>
                                    <label for="packshotphoto_eu_ai_padding_left" style="display:block; font-size:11px; font-weight:600; color:#475569; margin-bottom:3px;">
                                        ⬅️ <?php esc_html_e('Left', 'packshotphoto-ai'); ?> (px)
                                    </label>
                                    <input type="number" id="packshotphoto_eu_ai_padding_left" name="packshotphoto_eu_ai_padding_left" value="<?php echo esc_attr($pad_left); ?>" min="0" max="200" step="1" style="width: 75px; text-align: center;">
                                </div>
                            </div>
                            <p class="description" style="margin-top: 6px; font-size: 12px;">
                                <?php esc_html_e('Default: 15px. Sets the distance between the label and image boundary.', 'packshotphoto-ai'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <?php
    }
}
