<?php
/**
 * Upload Panel — Injects a processing options panel on media-new.php
 *
 * Allows users to set per-session upload options (auto AI, WebP, AVIF, resize)
 * and an optional image context string that is sent to the AI for better descriptions.
 * Settings are NOT saved globally — they revert to saved defaults on page refresh.
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\Admin;

defined('ABSPATH') || exit;

class UploadPanel {

    public static function register_hooks(): void {
        add_action('admin_head-media-new.php',   [static::class, 'inject_styles']);
        add_action('post-upload-ui',             [static::class, 'inject_panel']);
        add_action('wp_ajax_packshotphoto_save_upload_session_opts', [static::class, 'ajax_save_session_opts']);
        add_action('wp_ajax_packshotphoto_check_item_status', [static::class, 'ajax_check_item_status']);
    }

    /**
     * Inject inline CSS for the panel (enqueue externalized file)
     */
    public static function inject_styles(): void {
        wp_enqueue_style(
            'packshotphoto-upload-panel',
            PACKSHOTPHOTO_AI_URL . 'assets/css/packshotphoto-upload-panel.css',
            [],
            PACKSHOTPHOTO_AI_VERSION
        );
    }

    public static function inject_panel(): void {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || 'media' !== $screen->base) {
            return;
        }

        $settings  = get_option('packshotphoto_settings', []);
        $language  = $settings['language'] ?? 'auto';

        // Try loading transient options saved for this user's session
        $user_id      = get_current_user_id();
        $session_opts = get_transient('packshotphoto_upload_session_opts_' . $user_id);
        
        if (is_array($session_opts)) {
            $auto_ai     = ($session_opts['auto_ai'] ?? '0') === '1';
            $auto_eu_ai  = ($session_opts['auto_eu_ai'] ?? '0') === '1';
            $auto_webp   = ($session_opts['auto_webp'] ?? '0') === '1';
            $auto_avif   = ($session_opts['auto_avif'] ?? '0') === '1';
            $auto_resize = ($session_opts['auto_resize'] ?? '0') === '1';
            $max_size    = (int) ($session_opts['resize_width'] ?? 0);
            
            // Clear context from session options on page reload
            $session_opts['context'] = '';
            set_transient('packshotphoto_upload_session_opts_' . $user_id, $session_opts, 2 * HOUR_IN_SECONDS);
            $context     = '';
        } else {
            // Fallback to global saved options (defaults for this session)
            $auto_ai     = get_option('packshotphoto_auto_process', '0') === '1';
            $auto_eu_ai  = get_option('packshotphoto_auto_eu_ai',   '0') === '1';
            $auto_webp   = get_option('packshotphoto_auto_webp',    '0') === '1';
            $auto_avif   = get_option('packshotphoto_auto_avif',    '0') === '1';
            $max_size    = (int) get_option('packshotphoto_max_image_size', 0);
            $auto_resize = $max_size > 0;
            $context     = '';
        }

        $checked = fn(bool $v) => $v ? 'checked' : '';
        ?>
        <div id="packshotphoto-upload-panel">
            <div class="packshotphoto-panel-header">
                <span class="packshotphoto-panel-icon">🖼️</span>
                <div>
                    <div class="packshotphoto-panel-title"><?php esc_html_e('Upload Processing Options', 'packshotphoto-ai'); ?></div>
                    <div class="packshotphoto-panel-subtitle"><?php esc_html_e('Override settings for this upload session only', 'packshotphoto-ai'); ?></div>
                </div>
                <span class="packshotphoto-panel-badge">PackshotPhoto AI</span>
            </div>

             <!-- Auto AI Generation -->
             <div class="packshotphoto-toggle-row" id="packshotphoto-row-ai">
                 <div class="packshotphoto-toggle-label">
                     <span class="packshotphoto-toggle-label-icon">🤖</span>
                     <div>
                         <span class="packshotphoto-toggle-label-text"><?php esc_html_e('Auto AI Descriptions', 'packshotphoto-ai'); ?></span>
                         <span class="packshotphoto-toggle-label-desc"><?php esc_html_e('Automatically generate alt, caption and description for each uploaded image', 'packshotphoto-ai'); ?></span>
                     </div>
                 </div>
                 <label class="packshotphoto-switch">
                     <input type="checkbox" id="packshotphoto-session-auto-ai" name="packshotphoto_session_auto_ai" value="1" <?php echo esc_attr($checked($auto_ai)); ?>>
                     <span class="packshotphoto-switch-slider"></span>
                 </label>
             </div>

             <!-- Auto EU AI Act Watermark -->
             <div class="packshotphoto-toggle-row" id="packshotphoto-row-eu-ai">
                 <div class="packshotphoto-toggle-label">
                     <span class="packshotphoto-toggle-label-icon">🇪🇺</span>
                     <div>
                         <span class="packshotphoto-toggle-label-text"><?php esc_html_e('EU AI Act Watermark', 'packshotphoto-ai'); ?></span>
                         <span class="packshotphoto-toggle-label-desc"><?php esc_html_e('Automatically stamp uploaded files with EU AI mark (Art. 50)', 'packshotphoto-ai'); ?></span>
                     </div>
                 </div>
                 <label class="packshotphoto-switch">
                     <input type="checkbox" id="packshotphoto-session-auto-eu-ai" name="packshotphoto_session_auto_eu_ai" value="1" <?php echo esc_attr($checked($auto_eu_ai)); ?>>
                     <span class="packshotphoto-switch-slider"></span>
                 </label>
             </div>
 
             <!-- Auto WebP -->
             <div class="packshotphoto-toggle-row" id="packshotphoto-row-webp">
                 <div class="packshotphoto-toggle-label">
                     <span class="packshotphoto-toggle-label-icon">🖼️</span>
                     <div>
                         <span class="packshotphoto-toggle-label-text"><?php esc_html_e('Auto Convert to WebP', 'packshotphoto-ai'); ?></span>
                         <span class="packshotphoto-toggle-label-desc"><?php esc_html_e('Convert JPEG/PNG/GIF to WebP automatically after upload', 'packshotphoto-ai'); ?></span>
                     </div>
                 </div>
                 <label class="packshotphoto-switch">
                     <input type="checkbox" id="packshotphoto-session-auto-webp" name="packshotphoto_session_auto_webp" value="1" <?php echo esc_attr($checked($auto_webp)); ?>>
                     <span class="packshotphoto-switch-slider"></span>
                 </label>
             </div>
 
             <!-- Auto AVIF -->
             <div class="packshotphoto-toggle-row" id="packshotphoto-row-avif">
                 <div class="packshotphoto-toggle-label">
                     <span class="packshotphoto-toggle-label-icon">🖼️</span>
                     <div>
                         <span class="packshotphoto-toggle-label-text"><?php esc_html_e('Auto Convert to AVIF', 'packshotphoto-ai'); ?></span>
                         <span class="packshotphoto-toggle-label-desc"><?php esc_html_e('Convert images to AVIF format (best compression) after upload', 'packshotphoto-ai'); ?></span>
                     </div>
                 </div>
                 <label class="packshotphoto-switch">
                     <input type="checkbox" id="packshotphoto-session-auto-avif" name="packshotphoto_session_auto_avif" value="1" <?php echo esc_attr($checked($auto_avif)); ?>>
                     <span class="packshotphoto-switch-slider"></span>
                 </label>
             </div>
 
             <!-- Auto Resize -->
             <div class="packshotphoto-toggle-row" id="packshotphoto-row-resize">
                 <div class="packshotphoto-toggle-label">
                     <span class="packshotphoto-toggle-label-icon">📐</span>
                     <div>
                         <span class="packshotphoto-toggle-label-text"><?php esc_html_e('Auto Resize', 'packshotphoto-ai'); ?></span>
                         <span class="packshotphoto-toggle-label-desc"><?php esc_html_e('Resize images to max width/height after upload', 'packshotphoto-ai'); ?></span>
                     </div>
                 </div>
                 <div class="packshotphoto-resize-inline">
                     <input type="number"
                            id="packshotphoto-session-resize-width"
                            name="packshotphoto_session_resize_width"
                            value="<?php echo esc_attr($max_size ?: 1920); ?>"
                            min="100" max="9999" step="10"
                            placeholder="px">
                     <span>px</span>
                     <label class="packshotphoto-switch">
                         <input type="checkbox" id="packshotphoto-session-auto-resize" name="packshotphoto_session_auto_resize" value="1"
                             <?php echo esc_attr($checked($auto_resize)); ?>>
                         <span class="packshotphoto-switch-slider"></span>
                     </label>
                 </div>
             </div>
 
             <!-- Upload Context -->
             <div class="packshotphoto-context-section">
                 <div class="packshotphoto-context-label">
                     💬 <?php esc_html_e('AI Image Context', 'packshotphoto-ai'); ?>
                 </div>
                 <div class="packshotphoto-context-label-hint">
                     <?php esc_html_e('Describe what these images are about. This context helps the AI generate more accurate and relevant alt text, captions and descriptions.', 'packshotphoto-ai'); ?>
                 </div>
                 <textarea
                     id="packshotphoto-upload-context"
                     name="packshotphoto_upload_context"
                     placeholder="<?php esc_attr_e('e.g. Product packshots for an e-commerce store selling organic skincare. White background, minimalist style.', 'packshotphoto-ai'); ?>"
                 ><?php echo esc_textarea($context); ?></textarea>
            </div>

             <div class="packshotphoto-panel-note" style="margin-top: 22px; display: flex; align-items: center; justify-content: space-between; gap: 15px; border-top: 1px solid #f0f0f1; padding-top: 16px;">
                 <div class="packshotphoto-panel-note">
                     ℹ️ <?php esc_html_e('Settings are saved automatically and apply to this upload session.', 'packshotphoto-ai'); ?>
                 </div>
                 <div id="packshotphoto-panel-save-indicator" style="font-size: 12px; font-weight: 500; color: #2271b1; opacity: 0; transition: opacity 0.25s ease-in-out; display: flex; align-items: center; gap: 6px; user-select: none;">
                     <span>⏳</span> <?php esc_html_e('Saving settings...', 'packshotphoto-ai'); ?>
                 </div>
             </div>
        </div>
        <?php
        wp_enqueue_script(
            'packshotphoto-upload-panel-js',
            PACKSHOTPHOTO_AI_URL . 'assets/js/packshotphoto-upload-panel.js',
            ['jquery', 'packshotphoto-admin'],
            PACKSHOTPHOTO_AI_VERSION,
            true
        );
        wp_localize_script('packshotphoto-upload-panel-js', 'packshotphotoUploadPanelOpts', [
            'nonce' => wp_create_nonce('packshotphoto_global_nonce')
        ]);
    }

    /**
     * AJAX handler to save upload session settings for the current user
     */
    public static function ajax_save_session_opts(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(['message' => __('Permission denied', 'packshotphoto-ai')]);
        }

        $user_id = get_current_user_id();
        $opts = [
            'auto_ai'      => isset($_POST['auto_ai']) ? sanitize_text_field(wp_unslash($_POST['auto_ai'])) : '0',
            'auto_eu_ai'   => isset($_POST['auto_eu_ai']) ? sanitize_text_field(wp_unslash($_POST['auto_eu_ai'])) : '0',
            'auto_webp'    => isset($_POST['auto_webp']) ? sanitize_text_field(wp_unslash($_POST['auto_webp'])) : '0',
            'auto_avif'    => isset($_POST['auto_avif']) ? sanitize_text_field(wp_unslash($_POST['auto_avif'])) : '0',
            'auto_resize'  => isset($_POST['auto_resize']) ? sanitize_text_field(wp_unslash($_POST['auto_resize'])) : '0',
            'resize_width' => isset($_POST['resize_width']) ? absint(wp_unslash($_POST['resize_width'])) : 1920,
            'context'      => isset($_POST['context']) ? sanitize_textarea_field(wp_unslash($_POST['context'])) : '',
        ];

        // Save session options for this user, expires in 2 hours
        set_transient('packshotphoto_upload_session_opts_' . $user_id, $opts, 2 * HOUR_IN_SECONDS);

        wp_send_json_success(['message' => __('Session settings applied successfully!', 'packshotphoto-ai')]);
    }

    /**
     * AJAX handler to check processing status of an uploaded attachment
     */
    public static function ajax_check_item_status(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(['message' => __('Permission denied', 'packshotphoto-ai')]);
        }

        $post_id = isset($_POST['id']) ? absint($_POST['id']) : 0;
        if (!$post_id) {
            wp_send_json_error(['message' => __('Invalid attachment ID', 'packshotphoto-ai')]);
        }

        $is_processing = \PackshotPhotoAI\Admin\Columns::is_processing($post_id);

        // Fetch current values
        $post = get_post($post_id);
        $alt  = get_post_meta($post_id, '_wp_attachment_image_alt', true) ?: '';
        $caption = $post ? $post->post_excerpt : '';
        $desc = $post ? $post->post_content : '';
        $mime_type = get_post_mime_type($post_id);

        $has_ai_backup = get_post_meta($post_id, '_pmm_ai_backup', true);
        $has_file_backup = get_post_meta($post_id, '_pmm_has_file_backup', true);
        $has_original_filename = get_post_meta($post_id, '_pmm_original_filename', true);
        $show_restore = $has_ai_backup || $has_file_backup || $has_original_filename;

        // Generate nonce for editable inputs
        $edit_nonce = wp_create_nonce('packshotphoto_edit_' . $post_id);

        $file_path = get_attached_file($post_id);
        $filename  = $file_path ? basename($file_path) : '';
        $thumb_url = wp_get_attachment_image_url($post_id, 'thumbnail') ?: wp_get_attachment_url($post_id);

        wp_send_json_success([
            'processing'   => $is_processing,
            'alt'          => $alt,
            'caption'      => $caption,
            'desc'         => $desc,
            'filename'     => $filename,
            'mime_type'    => $mime_type,
            'thumb_url'    => $thumb_url,
            'show_restore' => (bool)$show_restore,
            'edit_nonce'   => $edit_nonce,
        ]);
    }
}
