<?php
namespace AIFI;

/**
 * Handles the post editor UI for AI image generation.
 *
 * @package AIFI
 */
class Meta_Box {
    /**
     * Settings instance.
     *
     * @var Settings
     */
    private $settings;

    /**
     * Initialize meta box.
     */
    public function __construct($settings) {
        $this->settings = $settings;
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('init', array($this, 'register_meta'));
        add_action('save_post', array($this, 'save_custom_prompt'), 10, 2);
    }

    /**
     * Register _aifi_custom_prompt post meta so it is accessible in the REST API
     * (needed for Block Editor persistence).
     */
    public function register_meta() {
        register_post_meta('', '_aifi_custom_prompt', array(
            'show_in_rest'      => true,
            'single'            => true,
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
            'auth_callback'     => function() {
                return current_user_can('edit_posts');
            },
        ));
    }

    /**
     * Save the custom prompt from the Classic Editor meta box form submission.
     *
     * @param int      $post_id Post ID.
     * @param \WP_Post $post    Post object.
     */
    public function save_custom_prompt($post_id, $post) {
        // Skip autosaves and revisions
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (wp_is_post_revision($post_id)) {
            return;
        }
        // Verify nonce
        if (!isset($_POST['aifi_meta_box_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aifi_meta_box_nonce'])), 'aifi_meta_box')) {
            return;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        if (isset($_POST['aifi_custom_prompt'])) {
            update_post_meta($post_id, '_aifi_custom_prompt', sanitize_textarea_field(wp_unslash($_POST['aifi_custom_prompt'])));
        }
    }

    /**
     * Add meta box to post editor.
     */
    public function add_meta_box() {
        // Get enabled post types from settings
        $post_types = $this->settings->get_enabled_post_types();
        
        // Add meta box for each enabled post type
        foreach ($post_types as $post_type) {
            // Verify the post type exists and supports featured images
            if (!post_type_exists($post_type)) {
                continue;
            }
            
            add_meta_box(
                'aifi_meta_box',
                __('AI Featured Image', 'ai-featured-image-generator'),
                array($this, 'render_meta_box'),
                $post_type,
                'side',
                'high'
            );
        }
    }

    /**
     * Enqueue admin scripts and styles.
     *
     * @param string $hook Current admin page.
     */
    public function enqueue_scripts($hook) {
        // Check if we're on a post edit screen
        if (!in_array($hook, array('post.php', 'post-new.php'))) {
            return;
        }
        
        // Get the current post type from the screen
        $screen = get_current_screen();
        if (!$screen || empty($screen->post_type)) {
            return;
        }
        
        // Get enabled post types and check if current post type is enabled
        $enabled_post_types = $this->settings->get_enabled_post_types();
        if (!in_array($screen->post_type, $enabled_post_types, true)) {
            return;
        }
        
        // Also check if we're in Classic Editor mode
        $is_classic_editor = false;
        if (function_exists('classic_editor_replace') && classic_editor_replace()) {
            $is_classic_editor = true;
        }
        
        // Check for Classic Editor plugin
        if (class_exists('Classic_Editor')) {
            $is_classic_editor = true;
        }

        wp_enqueue_style(
            'aifi-admin',
            AIFI_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            AIFI_VERSION
        );

        wp_enqueue_script(
            'aifi-admin',
            AIFI_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery'),
            AIFI_VERSION,
            true
        );

        $settings_data = $this->settings->get_settings();
        $provider       = isset($settings_data['ai_provider']) ? $settings_data['ai_provider'] : 'openai';

        wp_localize_script('aifi-admin', 'aifiData', array(
            'nonce'               => wp_create_nonce('wp_rest'),
            'restUrl'             => rest_url('aifi/v1/generate'),
            'upscaleUrl'          => rest_url('aifi/v1/upscale'),
            'removeBgUrl'         => rest_url('aifi/v1/remove-background'),
            'generatePromptUrl'   => rest_url('aifi/v1/generate-prompt'),
            'savePromptUrl'       => rest_url('aifi/v1/save-prompt'),
            'isClassicEditor'     => $is_classic_editor,
            'provider'            => $provider,
            'i18n' => array(
                'generating'          => __('Generating image...', 'ai-featured-image-generator'),
                'success'             => __('Image generated successfully!', 'ai-featured-image-generator'),
                'error'               => __('Error generating image. Please try again.', 'ai-featured-image-generator'),
                'noApiKey'            => __('Please configure your API key in the settings.', 'ai-featured-image-generator'),
                'confirmOverwrite'    => __('This will replace your current featured image. Continue?', 'ai-featured-image-generator'),
                'upscaling'           => __('Upscaling image...', 'ai-featured-image-generator'),
                'upscaleSuccess'      => __('Image upscaled successfully!', 'ai-featured-image-generator'),
                'upscaleError'        => __('Error upscaling image. Please try again.', 'ai-featured-image-generator'),
                'removingBg'          => __('Removing background...', 'ai-featured-image-generator'),
                'removeBgSuccess'     => __('Background removed successfully!', 'ai-featured-image-generator'),
                'removeBgError'       => __('Error removing background. Please try again.', 'ai-featured-image-generator'),
                'generatingPrompt'    => __('Generating prompt from content...', 'ai-featured-image-generator'),
                'promptGenerated'     => __('Prompt generated and saved!', 'ai-featured-image-generator'),
                'promptError'         => __('Error generating prompt. Please try again.', 'ai-featured-image-generator'),
                'stabilityNoText'     => __('Stability AI does not support text generation. Please switch to OpenAI, Gemini, or Grok in the settings.', 'ai-featured-image-generator'),
                'emptyContent'        => __('This post has no content to generate a prompt from.', 'ai-featured-image-generator'),
            ),
        ));
    }

    /**
     * Render meta box content.
     *
     * @param \WP_Post $post Post object.
     */
    public function render_meta_box($post) {
        if (!current_user_can('edit_post', $post->ID)) {
            return;
        }

        $settings_data = $this->settings->get_settings();
        $default_style = isset($settings_data['default_style']) ? $settings_data['default_style'] : 'realistic';
        $allow_text = isset($settings_data['allow_text']) ? (bool)$settings_data['allow_text'] : false;

        // Check if appropriate API key is configured based on provider
        $provider = isset($settings_data['ai_provider']) ? $settings_data['ai_provider'] : 'openai';
        
        // Check if user can use premium features
        $can_use_premium = function_exists('afig_fs') && afig_fs()->can_use_premium_code();
        
        // If non-premium user has Gemini selected, show upgrade notice and force OpenAI
        if ( ! $can_use_premium && $provider === 'gemini' ) {
            printf(
                '<p class="aifi-error"><span class="dashicons dashicons-star-filled" style="color: #f0ad4e;"></span> %s <a href="%s">%s</a></p>',
                esc_html__('Google Gemini is a Pro feature.', 'ai-featured-image-generator'),
                esc_url( afig_fs()->get_upgrade_url() ),
                esc_html__('Upgrade to Pro', 'ai-featured-image-generator')
            );
            // Force provider to OpenAI for the rest of this render
            $provider = 'openai';
        }

        // Map provider to API key field
        $api_key_fields = array(
            'openai'    => 'openai_api_key',
            'gemini'    => 'gemini_api_key',
            'stability' => 'stability_api_key',
            'grok'      => 'grok_api_key',
        );
        $api_key_field = isset($api_key_fields[$provider]) ? $api_key_fields[$provider] : 'openai_api_key';

        // Support legacy 'api_key' field for backward compatibility
        if ($provider === 'openai' && empty($settings_data['openai_api_key']) && !empty($settings_data['api_key'])) {
            $api_key_field = 'api_key';
        }

        $provider_labels = array(
            'openai' => 'OpenAI',
            'gemini' => 'Google Gemini',
            'stability' => 'Stability AI',
            'grok' => 'Grok / xAI',
        );
        $provider_label = isset($provider_labels[$provider]) ? $provider_labels[$provider] : $provider;

        if (empty($settings_data[$api_key_field])) {
            printf(
                '<p class="aifi-error">%s <a href="%s">%s</a></p>',
                sprintf(
                    esc_html__('API key not configured for %s.', 'ai-featured-image-generator'),
                    $provider_label
                ),
                esc_url(admin_url('admin.php?page=ai-featured-image-generator')),
                esc_html__('Configure now', 'ai-featured-image-generator')
            );
            return;
        }

        wp_nonce_field('aifi_meta_box', 'aifi_meta_box_nonce');
        ?>
        <div class="aifi-meta-box">
            <!-- Custom text field (if enabled) -->
            <?php if ($allow_text): ?>
            <div class="aifi-field-group">
                <label for="aifi-custom-text"><?php esc_html_e('Custom Text for Image (optional):', 'ai-featured-image-generator'); ?></label>
                <input type="text" 
                       id="aifi-custom-text" 
                       class="widefat" 
                       placeholder="<?php esc_attr_e('Add text to your image ...', 'ai-featured-image-generator'); ?>">
                <p class="description"><?php esc_html_e('Leave empty to use the post title as text on the image.', 'ai-featured-image-generator'); ?></p>
            </div>
            <?php endif; ?>

            <!-- Custom prompt field -->
            <div class="aifi-field-group">
                <label for="aifi-prompt"><?php esc_html_e('Custom Prompt (optional):', 'ai-featured-image-generator'); ?></label>
                <textarea id="aifi-prompt"
                          name="aifi_custom_prompt"
                          class="widefat"
                          rows="3"
                          placeholder="<?php esc_attr_e('Leave empty to generate from your post title, or describe the image you want...', 'ai-featured-image-generator'); ?>"><?php echo esc_textarea(get_post_meta($post->ID, '_aifi_custom_prompt', true)); ?></textarea>
                <div class="aifi-generate-prompt-wrap">
                    <button type="button" id="aifi-generate-prompt" class="button button-secondary aifi-generate-prompt-btn">
                        <span class="dashicons dashicons-edit-large"></span>
                        <?php esc_html_e('Generate Prompt from Content', 'ai-featured-image-generator'); ?>
                    </button>
                    <span id="aifi-prompt-spinner" class="spinner" style="float:none; margin:0 4px;"></span>
                </div>
                <div id="aifi-prompt-message" class="aifi-message" style="display:none; margin-top:6px;"></div>
            </div>

            <!-- Style selection -->
            <div class="aifi-field-group">
                <label for="aifi-style"><?php esc_html_e('Style:', 'ai-featured-image-generator'); ?></label>
                <select id="aifi-style" class="widefat">
                    <optgroup label="<?php esc_attr_e('Common', 'ai-featured-image-generator'); ?>">
                        <option value="none" <?php selected($default_style, 'none'); ?>><?php esc_html_e('None (No Style)', 'ai-featured-image-generator'); ?></option>
                        <option value="realistic" <?php selected($default_style, 'realistic'); ?>><?php esc_html_e('Realistic', 'ai-featured-image-generator'); ?></option>
                        <option value="artistic" <?php selected($default_style, 'artistic'); ?>><?php esc_html_e('Artistic', 'ai-featured-image-generator'); ?></option>
                        <option value="cartoon" <?php selected($default_style, 'cartoon'); ?>><?php esc_html_e('Cartoon', 'ai-featured-image-generator'); ?></option>
                        <option value="minimalist" <?php selected($default_style, 'minimalist'); ?>><?php esc_html_e('Minimalist', 'ai-featured-image-generator'); ?></option>
                    </optgroup>
                    <optgroup label="<?php esc_attr_e('Creative', 'ai-featured-image-generator'); ?>">
                        <option value="sketch" <?php selected($default_style, 'sketch'); ?>><?php esc_html_e('Sketch', 'ai-featured-image-generator'); ?></option>
                        <option value="watercolor" <?php selected($default_style, 'watercolor'); ?>><?php esc_html_e('Watercolor', 'ai-featured-image-generator'); ?></option>
                        <option value="3d" <?php selected($default_style, '3d'); ?>><?php esc_html_e('3D Render', 'ai-featured-image-generator'); ?></option>
                        <option value="pixel" <?php selected($default_style, 'pixel'); ?>><?php esc_html_e('Pixel Art', 'ai-featured-image-generator'); ?></option>
                        <option value="cyberpunk" <?php selected($default_style, 'cyberpunk'); ?>><?php esc_html_e('Cyberpunk', 'ai-featured-image-generator'); ?></option>
                        <option value="fantasy" <?php selected($default_style, 'fantasy'); ?>><?php esc_html_e('Fantasy', 'ai-featured-image-generator'); ?></option>
                        <option value="anime" <?php selected($default_style, 'anime'); ?>><?php esc_html_e('Anime', 'ai-featured-image-generator'); ?></option>
                        <option value="technicolor" <?php selected($default_style, 'technicolor'); ?>><?php esc_html_e('Technicolor', 'ai-featured-image-generator'); ?></option>
                    </optgroup>
                    <?php if ($provider === 'stability') : ?>
                    <optgroup label="<?php esc_attr_e('Stability Presets', 'ai-featured-image-generator'); ?>">
                        <option value="sp_photographic" <?php selected($default_style, 'sp_photographic'); ?>><?php esc_html_e('Photographic', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_cinematic" <?php selected($default_style, 'sp_cinematic'); ?>><?php esc_html_e('Cinematic', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_anime" <?php selected($default_style, 'sp_anime'); ?>><?php esc_html_e('Anime', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_digital-art" <?php selected($default_style, 'sp_digital-art'); ?>><?php esc_html_e('Digital Art', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_comic-book" <?php selected($default_style, 'sp_comic-book'); ?>><?php esc_html_e('Comic Book', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_fantasy-art" <?php selected($default_style, 'sp_fantasy-art'); ?>><?php esc_html_e('Fantasy Art', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_3d-model" <?php selected($default_style, 'sp_3d-model'); ?>><?php esc_html_e('3D Model', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_analog-film" <?php selected($default_style, 'sp_analog-film'); ?>><?php esc_html_e('Analog Film', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_enhance" <?php selected($default_style, 'sp_enhance'); ?>><?php esc_html_e('Enhance', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_isometric" <?php selected($default_style, 'sp_isometric'); ?>><?php esc_html_e('Isometric', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_line-art" <?php selected($default_style, 'sp_line-art'); ?>><?php esc_html_e('Line Art', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_low-poly" <?php selected($default_style, 'sp_low-poly'); ?>><?php esc_html_e('Low Poly', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_neon-punk" <?php selected($default_style, 'sp_neon-punk'); ?>><?php esc_html_e('Neon Punk', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_origami" <?php selected($default_style, 'sp_origami'); ?>><?php esc_html_e('Origami', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_pixel-art" <?php selected($default_style, 'sp_pixel-art'); ?>><?php esc_html_e('Pixel Art', 'ai-featured-image-generator'); ?></option>
                        <option value="sp_tile-texture" <?php selected($default_style, 'sp_tile-texture'); ?>><?php esc_html_e('Tile Texture', 'ai-featured-image-generator'); ?></option>
                    </optgroup>
                    <?php endif; ?>
                    <?php $custom_styles = $this->settings->get_custom_styles(); ?>
                    <?php if ( ! empty($custom_styles) ) : ?>
                    <optgroup label="<?php esc_attr_e('Custom', 'ai-featured-image-generator'); ?>">
                        <?php foreach ($custom_styles as $i => $cs) : ?>
                        <option value="custom_<?php echo $i; ?>" <?php selected($default_style, 'custom_' . $i); ?>>
                            <?php echo esc_html($cs['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </optgroup>
                    <?php endif; ?>
                </select>
            </div>

            <!-- Generate button and loading spinner -->
            <div class="aifi-actions">
                <button type="button" 
                        id="aifi-generate" 
                        class="button button-primary button-large">
                    <?php esc_html_e('Generate Featured Image', 'ai-featured-image-generator'); ?>
                </button>
                <div id="aifi-loading-spinner" class="aifi-loading-spinner" style="display: none;">
                    <div class="aifi-spinner" role="img" aria-label="<?php esc_attr_e('Loading', 'ai-featured-image-generator'); ?>"></div>
                </div>
            </div>

            <!-- Preview and message areas -->
            <div id="aifi-preview" class="aifi-preview" style="display: none;">
                <img src="" alt="<?php esc_attr_e('Generated image preview', 'ai-featured-image-generator'); ?>">

            </div>

            <div id="aifi-message" class="aifi-message" style="display: none;"></div>

            <?php
            // Upscale & Remove Background section
            // Visible when: featured image exists AND Stability API key is configured
            $has_stability_key = !empty($settings_data['stability_api_key']);
            $has_featured_image = has_post_thumbnail($post->ID);
            if ($has_stability_key) :
            ?>
            <div id="aifi-stability-tools" class="aifi-stability-tools<?php echo ! $can_use_premium ? ' aifi-stability-tools-locked' : ''; ?>" style="<?php echo !$has_featured_image ? 'display:none;' : ''; ?>">
                <hr style="margin: 12px 0;">
                <p class="aifi-section-label"><strong><?php esc_html_e('Stability AI Tools', 'ai-featured-image-generator'); ?></strong> <span class="aifi-pro-badge-tab">Pro</span></p>

                <?php if ( ! $can_use_premium ) : ?>
                <p class="aifi-tools-upgrade-hint">
                    <span class="dashicons dashicons-star-filled" style="color: #f0ad4e; font-size: 14px; vertical-align: text-bottom;"></span>
                    <?php
                    printf(
                        esc_html__('%s to use upscaling and background removal.', 'ai-featured-image-generator'),
                        '<a href="' . esc_url(afig_fs()->get_upgrade_url()) . '">' . esc_html__('Upgrade to Pro', 'ai-featured-image-generator') . '</a>'
                    );
                    ?>
                </p>
                <?php endif; ?>

                <!-- Upscale -->
                <div class="aifi-field-group">
                    <label for="aifi-upscale-mode"><?php esc_html_e('Upscale Mode:', 'ai-featured-image-generator'); ?></label>
                    <select id="aifi-upscale-mode" class="widefat" <?php disabled( ! $can_use_premium ); ?>>
                        <option value="conservative"><?php esc_html_e('Conservative (Faithful 4x)', 'ai-featured-image-generator'); ?></option>
                        <option value="creative"><?php esc_html_e('Creative (Enhanced 4K)', 'ai-featured-image-generator'); ?></option>
                        <option value="fast"><?php esc_html_e('Fast (Quick 4x)', 'ai-featured-image-generator'); ?></option>
                    </select>
                </div>
                <div class="aifi-actions" style="margin-bottom: 8px;">
                    <button type="button" id="aifi-upscale" class="button button-secondary" <?php disabled( ! $can_use_premium ); ?>>
                        <span class="dashicons dashicons-image-crop" style="margin-top:3px;"></span>
                        <?php esc_html_e('Upscale Image', 'ai-featured-image-generator'); ?>
                    </button>
                </div>

                <!-- Remove Background -->
                <div class="aifi-actions">
                    <button type="button" id="aifi-remove-bg" class="button button-secondary" <?php disabled( ! $can_use_premium ); ?>>
                        <span class="dashicons dashicons-image-filter" style="margin-top:3px;"></span>
                        <?php esc_html_e('Remove Background', 'ai-featured-image-generator'); ?>
                    </button>
                </div>

                <div id="aifi-stability-loading" class="aifi-loading-spinner" style="display: none;">
                    <div class="aifi-spinner" role="img" aria-label="<?php esc_attr_e('Processing', 'ai-featured-image-generator'); ?>"></div>
                </div>
                <div id="aifi-stability-message" class="aifi-message" style="display: none;"></div>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }
}