<?php
/**
 * Custom Media Columns Handler
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\Admin;

defined('ABSPATH') || exit;

/**
 * Manages custom columns in Media Library
 */
class Columns {

    /**
     * Add custom columns to media library
     *
     * @param array $columns Existing columns
     * @return array Modified columns
     */
    public function add_columns(array $columns): array {
        // Remove unwanted columns
        unset($columns['author'], $columns['parent'], $columns['comments']);

        $new_columns = [];

        foreach ($columns as $key => $title) {
            $new_columns[$key] = $title;

            // Add our columns after title
            if ('title' === $key) {
                $new_columns['packshotphoto_slug']    = __('Filename', 'packshotphoto-ai');
                $new_columns['packshotphoto_alt']     = __('Alt', 'packshotphoto-ai');
                $new_columns['packshotphoto_caption'] = __('Caption', 'packshotphoto-ai');
                $new_columns['packshotphoto_desc']    = __('Description', 'packshotphoto-ai');
                $new_columns['packshotphoto_tools']   = __('Tools', 'packshotphoto-ai');
            }
        }

        return $new_columns;
    }

    /**
     * Render column content
     *
     * @param string $column  Column name
     * @param int    $post_id Attachment ID
     */
    public function render_column(string $column, int $post_id): void {
        // Only process our columns
        if (!in_array($column, ['packshotphoto_alt', 'packshotphoto_caption', 'packshotphoto_desc', 'packshotphoto_slug', 'packshotphoto_tools'], true)) {
            return;
        }

        // Security: Create nonce for this specific attachment
        $nonce = wp_create_nonce('packshotphoto_edit_' . $post_id);

        if ('packshotphoto_tools' === $column) {
            $this->render_tools_column($post_id, $nonce);
            return;
        }

        if ('packshotphoto_slug' === $column) {
            $this->render_filename_column($post_id, $nonce);
            return;
        }

        $this->render_editable_column($column, $post_id, $nonce);
    }

    /**
     * Render tools column (Generate Metadata, WebP, Resize, Compare)
     * OPTIMIZED: No filesystem operations on page load!
     *
     * @param int    $post_id Attachment ID
     * @param string $nonce   Security nonce
     */
    private function render_tools_column(int $post_id, string $nonce): void {
        $is_processing = static::is_processing($post_id);
        if ($is_processing) {
            $queued_at = 0;
            $opts = get_post_meta($post_id, '_pmm_upload_opts', true);
            if (is_array($opts)) {
                $queued_at = $opts['queued_at'] ?? 0;
            }
            $elapsed = $queued_at > 0 ? (time() - $queued_at) : 0;
            $status_text = $elapsed > 60
                ? esc_html__('⏳ AI Queued (waiting...)', 'packshotphoto-ai')
                : esc_html__('⏳ AI Processing...', 'packshotphoto-ai');
            ?>
            <div class="packshotphoto-tools-actions" style="display: flex; flex-direction: column; gap: 4px; align-items: stretch;">
                <div class="packshotphoto-processing-badge"><?php echo esc_html($status_text); ?></div>
            </div>
            <?php
            return;
        }

        $mime_type = get_post_mime_type($post_id);
        $is_webp = 'image/webp' === $mime_type;
        
        // FAST: Only check post meta (no filesystem!)
        $has_ai_backup = get_post_meta($post_id, '_pmm_ai_backup', true);
        $has_original_filename = get_post_meta($post_id, '_pmm_original_filename', true);
        
        // Use cached flag if available (updated by ImageProcessor/WebPConverter on backup creation)
        // This avoids 8 filesystem calls per row!
        $has_file_backup = get_post_meta($post_id, '_pmm_has_file_backup', true);
        
        // If meta backup exists, show restore button (filesystem check happens on click via AJAX)
        if ($has_file_backup) {
            $backup_meta = get_post_meta($post_id, '_pmm_original_backup', true);
            if (!$backup_meta) {
                // Meta was lost but flag exists — still show restore, AJAX will find backup
                $has_file_backup = '1';
            }
        }
        
        $show_restore = $has_ai_backup || $has_file_backup || $has_original_filename;
        ?>
        <div class="packshotphoto-tools-actions" style="display: flex; flex-direction: column; gap: 4px; align-items: stretch;">
            <?php 
            $settings = get_option('packshotphoto_settings', []);
            $language = $settings['language'] ?? 'auto';
            ?>
            <button type="button" 
                    class="button button-small packshotphoto-ai-btn"
                    data-id="<?php echo esc_attr($post_id); ?>" 
                    data-nonce="<?php echo esc_attr($nonce); ?>"
                    data-language="<?php echo esc_attr($language); ?>">
                <span class="packshotphoto-ai-text"><?php esc_html_e('Generate', 'packshotphoto-ai'); ?></span>
            </button>
            
            <?php 
            $is_webp = 'image/webp' === $mime_type;
            $is_avif = 'image/avif' === $mime_type;
            $is_convertible = wp_attachment_is_image($post_id) && in_array($mime_type, ['image/jpeg', 'image/png', 'image/gif'], true);
            
            if ($is_webp || $is_avif || $is_convertible) :
                $file_path = get_attached_file($post_id);
                $filesize = 0;
                if ($file_path && file_exists($file_path)) {
                    $filesize = filesize($file_path);
                }
                $target_format = $is_webp ? 'avif' : 'webp';
            ?>
                <button type="button" 
                        class="button button-small packshotphoto-convert-btn"
                        data-id="<?php echo esc_attr($post_id); ?>"
                        data-nonce="<?php echo esc_attr($nonce); ?>"
                        data-filesize="<?php echo esc_attr($filesize); ?>"
                        data-target-format="<?php echo esc_attr($target_format); ?>">
                    <span class="packshotphoto-btn-text"><?php esc_html_e('Convert', 'packshotphoto-ai'); ?></span>
                </button>
            <?php endif; ?>

            <button type="button" 
                    class="button button-small packshotphoto-manual-resize-trigger" 
                    data-id="<?php echo esc_attr($post_id); ?>"
                    data-nonce="<?php echo esc_attr($nonce); ?>">
                <span class="packshotphoto-btn-text"><?php esc_html_e('Resize', 'packshotphoto-ai'); ?></span>
            </button>

            <button type="button" 
                    class="button button-small packshotphoto-eu-ai-btn" 
                    data-id="<?php echo esc_attr($post_id); ?>"
                    data-nonce="<?php echo esc_attr($nonce); ?>"
                    style="border-color: #3b82f6; color: #2563eb;">
                <span class="packshotphoto-btn-text">🇪🇺 <?php esc_html_e('Label AI', 'packshotphoto-ai'); ?></span>
            </button>

            <?php if ($show_restore) : ?>
                <button type="button" 
                        class="button button-small packshotphoto-restore-btn"
                        data-id="<?php echo esc_attr($post_id); ?>"
                        data-nonce="<?php echo esc_attr($nonce); ?>"
                        data-has-ai-backup="<?php echo $has_ai_backup ? '1' : '0'; ?>"
                        data-has-file-backup="<?php echo $has_file_backup ? '1' : '0'; ?>"
                        data-has-original-filename="<?php echo $has_original_filename ? '1' : '0'; ?>">
                    <span class="packshotphoto-btn-text"><?php esc_html_e('Restore', 'packshotphoto-ai'); ?></span>
                </button>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render filename column with inline edit
     *
     * @param int    $post_id Attachment ID
     * @param string $nonce   Security nonce
     */
    private function render_filename_column(int $post_id, string $nonce): void {
        $file_path = get_attached_file($post_id);
        $filename = $file_path ? basename($file_path) : '';
        $is_processing = static::is_processing($post_id);
        $wrapper_class = 'packshotphoto-cell-wrapper packshotphoto-filename-wrapper';
        if ($is_processing) {
            $wrapper_class .= ' packshotphoto-loading';
        }
        ?>
        <div class="<?php echo esc_attr($wrapper_class); ?>">
            <div class="packshotphoto-filename-edit-group">
                <input 
                    type="text" 
                    class="packshotphoto-editable packshotphoto-filename-input" 
                    data-id="<?php echo esc_attr($post_id); ?>" 
                    data-field="filename" 
                    data-nonce="<?php echo esc_attr($nonce); ?>"
                    value="<?php echo esc_attr($filename); ?>"
                    placeholder="<?php esc_attr_e('filename.jpg', 'packshotphoto-ai'); ?>"
                    <?php disabled($is_processing); ?>
                />
            </div>
            
            <span class="packshotphoto-skeleton"></span>
            <span class="packshotphoto-save-indicator"><?php esc_html_e('Saving...', 'packshotphoto-ai'); ?></span>
        </div>
        <?php
    }

    /**
     * Render editable text column
     *
     * @param string $column  Column name
     * @param int    $post_id Attachment ID
     * @param string $nonce   Security nonce
     */
    private function render_editable_column(string $column, int $post_id, string $nonce): void {
        $field_map = [
            'packshotphoto_alt'     => 'alt',
            'packshotphoto_caption' => 'caption',
            'packshotphoto_desc'    => 'description',
        ];

        $field = $field_map[$column];
        $value = $this->get_field_value($post_id, $field);
        
        $placeholder_map = [
            'alt'         => __('Alt text...', 'packshotphoto-ai'),
            'caption'     => __('Caption...', 'packshotphoto-ai'),
            'description' => __('Description/Context...', 'packshotphoto-ai'),
        ];
        $is_processing = static::is_processing($post_id);
        $wrapper_class = 'packshotphoto-cell-wrapper';
        if ($is_processing) {
            $wrapper_class .= ' packshotphoto-loading';
        }
        ?>
        <div class="<?php echo esc_attr($wrapper_class); ?>">
            <textarea 
                class="packshotphoto-editable" 
                data-id="<?php echo esc_attr($post_id); ?>" 
                data-field="<?php echo esc_attr($field); ?>" 
                data-nonce="<?php echo esc_attr($nonce); ?>"
                placeholder="<?php echo esc_attr($placeholder_map[$field]); ?>"
                <?php disabled($is_processing); ?>
            ><?php echo esc_textarea($value); ?></textarea>
            <span class="packshotphoto-skeleton"></span>
            <span class="packshotphoto-save-indicator"><?php esc_html_e('Saving...', 'packshotphoto-ai'); ?></span>
        </div>
        <?php
    }

    /**
     * Get field value for attachment
     *
     * @param int    $post_id Attachment ID
     * @param string $field   Field name
     * @return string Field value
     */
    private function get_field_value(int $post_id, string $field): string {
        switch ($field) {
            case 'alt':
                return get_post_meta($post_id, '_wp_attachment_image_alt', true) ?: '';
            
            case 'caption':
                $post = get_post($post_id);
                return $post ? $post->post_excerpt : '';
            
            case 'description':
                $post = get_post($post_id);
                return $post ? $post->post_content : '';

            case 'slug':
                $post = get_post($post_id);
                return $post ? $post->post_name : '';
            
            default:
                return '';
        }
    }

    /**
     * Check if an attachment is currently being processed by the background workers
     *
     * @param int $post_id Attachment ID
     * @return bool True if processing
     */
    public static function is_processing(int $post_id): bool {
        // 1. Check if the auto-processing options meta exists (set on upload, deleted after async processing finishes)
        $opts = get_post_meta($post_id, '_pmm_upload_opts', true);
        if (is_array($opts)) {
            $do_ai   = isset($opts['auto_ai'])   && $opts['auto_ai']   === '1';
            $do_webp = isset($opts['auto_webp']) && $opts['auto_webp'] === '1';
            $do_avif = isset($opts['auto_avif']) && $opts['auto_avif'] === '1';

            if ($do_ai || $do_webp || $do_avif) {
                // Stuck detection: if queued more than 5 minutes ago, cron was likely lost or crashed
                $queued_at   = $opts['queued_at'] ?? 0;
                $retry_count = (int) ($opts['retry_count'] ?? 0);

                if ($queued_at > 0 && (time() - $queued_at) > 300) {
                    if ($retry_count >= 1) {
                        // Failed twice: drop the queued flag to release UI for manual user retry
                        delete_post_meta($post_id, '_pmm_upload_opts');
                        \PackshotPhotoAI\Core\Logger::warning('Columns::is_processing: item #' . $post_id . ' stuck twice, removing queued flag.');
                        return false;
                    }

                    // Reschedule the main chain checker/worker if not scheduled already
                    if (!wp_next_scheduled('packshotphoto_async_chain')) {
                        wp_schedule_single_event(time() + 5, 'packshotphoto_async_chain');
                        $opts['queued_at']   = time();
                        $opts['retry_count'] = $retry_count + 1;
                        update_post_meta($post_id, '_pmm_upload_opts', $opts);
                        \PackshotPhotoAI\Core\Logger::warning('Columns::is_processing: rescheduled stuck item #' . $post_id . ' trigger via chain scheduler.');
                    }
                }
                return true;
            }
        }

        // 2. Check if the item is pending in the background bulk worker queue
        $queue = get_option('packshotphoto_bulk_queue', []);
        if (!empty($queue) && 'processing' === ($queue['status'] ?? '')) {
            $items = $queue['items'] ?? [];
            $processed = (int)($queue['processed'] ?? 0);
            $pending = array_slice($items, $processed);
            if (in_array($post_id, $pending, true)) {
                return true;
            }
        }

        return false;
    }
}
