<?php
/**
 * Bulk Actions Handler
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\Admin;

use PackshotPhotoAI\Core\Logger;

defined('ABSPATH') || exit;

/**
 * Handles bulk actions for media library
 */
class BulkActions {

    /**
     * Add custom bulk actions to media dropdown
     *
     * @param array $actions Existing actions
     * @return array Modified actions
     */
    public function add_bulk_actions(array $actions): array {
        $actions['packshotphoto_bulk_ai']     = __('🤖 AI - Generate descriptions', 'packshotphoto-ai');
        $actions['packshotphoto_bulk_eu_ai']  = __('🇪🇺 EU AI - Label as AI image', 'packshotphoto-ai');
        $actions['packshotphoto_bulk_webp']   = __('🖼️ Convert to WebP', 'packshotphoto-ai');
        $actions['packshotphoto_bulk_avif']   = __('🖼️ Convert to AVIF', 'packshotphoto-ai');
        $actions['packshotphoto_bulk_resize'] = __('📐 Resize (Max Image Size)', 'packshotphoto-ai');

        return $actions;
    }

    /**
     * Handle bulk action processing
     *
     * @param string $redirect_url Redirect URL
     * @param string $action       Action name
     * @param array  $post_ids     Selected post IDs
     * @return string Modified redirect URL
     */
    public function handle_bulk_action(string $redirect_url, string $action, array $post_ids): string {
        if (!in_array($action, ['packshotphoto_bulk_ai', 'packshotphoto_bulk_eu_ai', 'packshotphoto_bulk_webp', 'packshotphoto_bulk_avif', 'packshotphoto_bulk_resize'], true)) {
            return $redirect_url;
        }

        // Map bulk actions to queue actions
        $action_map = [
            'packshotphoto_bulk_ai'     => 'ai',
            'packshotphoto_bulk_eu_ai'  => 'eu_ai',
            'packshotphoto_bulk_webp'   => 'webp',
            'packshotphoto_bulk_avif'   => 'avif',
            'packshotphoto_bulk_resize' => 'resize',
        ];

        $queue_action = $action_map[$action];
        $queue        = new \PackshotPhotoAI\Core\QueueManager();
        
        $queue->push($post_ids, $queue_action);

        return add_query_arg([
            'packshotphoto_bulk_queued' => 1,
            'packshotphoto_bulk_count'  => count($post_ids),
        ], $redirect_url);
    }
    public function show_bulk_notice(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!empty($_GET['packshotphoto_bulk_queued'])) {
            // Check if queue is still active in background. If already idle/completed, don't show stale notice on F5 refresh.
            $queue_data   = get_option('packshotphoto_bulk_queue', []);
            $queue_status = $queue_data['status'] ?? 'idle';
            if ('processing' !== $queue_status) {
                return;
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $count = isset($_GET['packshotphoto_bulk_count']) ? absint(wp_unslash($_GET['packshotphoto_bulk_count'])) : 0;
            ?>
            <div class="notice notice-info is-dismissible packshotphoto-queue-notice" data-count="<?php echo esc_attr($count); ?>">
                <p>
                    <strong>⏳ PackshotPhoto AI:</strong>
                    <?php
                    printf(
                        /* translators: %d: number of images */
                        esc_html__('Queue started for %d images. Processing in background...', 'packshotphoto-ai'),
                        absint($count)
                    ); ?>
                    <span class="packshotphoto-queue-live-status"></span>
                </p>
            </div>
            <?php
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (empty($_GET['packshotphoto_bulk_action'])) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $action = isset($_GET['packshotphoto_bulk_action']) ? sanitize_key(wp_unslash($_GET['packshotphoto_bulk_action'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $processed = isset($_GET['packshotphoto_processed']) ? absint(wp_unslash($_GET['packshotphoto_processed'])) : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $errors = isset($_GET['packshotphoto_errors']) ? absint(wp_unslash($_GET['packshotphoto_errors'])) : 0;

        $action_labels = [
            'packshotphoto_bulk_ai'     => __('AI descriptions', 'packshotphoto-ai'),
            'packshotphoto_bulk_eu_ai'  => __('EU AI Act Watermark', 'packshotphoto-ai'),
            'packshotphoto_bulk_webp'   => __('WebP conversion', 'packshotphoto-ai'),
            'packshotphoto_bulk_avif'   => __('AVIF conversion', 'packshotphoto-ai'),
            'packshotphoto_bulk_resize' => __('Image resizing', 'packshotphoto-ai'),
        ];

        $label = $action_labels[$action] ?? $action;
        $class = $errors > 0 ? 'notice-warning' : 'notice-success';

        /* translators: 1: CSS class name, 2: action label, 3: processed count, 4: errors count */
        printf(
            '<div class="notice %1$s is-dismissible"><p><strong>%2$s:</strong> Processed: %3$d, Errors: %4$d</p></div>',
            esc_attr($class),
            esc_html($label),
            absint($processed),
            absint($errors)
        );
    }

    /**
     * Show PRO required notice
     */
    public function show_pro_notice(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (empty($_GET['packshotphoto_pro_required'])) {
            return;
        }

        $settings_url = admin_url('tools.php?page=packshotphoto-ai');
        ?>
        <div class="notice notice-warning is-dismissible">
            <p>
                <strong>🚀 PackshotPhoto AI:</strong>
                <?php esc_html_e('Bulk actions are a PRO feature. Activate your license to unlock mass optimization.', 'packshotphoto-ai'); ?>
                <a href="<?php echo esc_url($settings_url); ?>">
                    <?php esc_html_e('Settings & Licensing →', 'packshotphoto-ai'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * AJAX: Process a batch of items
     */
    public function ajax_process_batch(): void {
        check_ajax_referer('packshotphoto_global_nonce', 'nonce');

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

        $post_ids = [];
        if (isset($_POST['ids'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $ids_raw = wp_unslash($_POST['ids']);
            if (is_array($ids_raw)) {
                $post_ids = array_map('absint', $ids_raw);
            } else {
                // Sanitize string before json_decode to fully satisfy security checkers
                $ids_sanitized = sanitize_text_field($ids_raw);
                $decoded = json_decode($ids_sanitized, true);
                if (is_array($decoded)) {
                    $post_ids = array_map('absint', $decoded);
                }
            }
        }
        $action   = isset($_POST['batch_action']) ? sanitize_key(wp_unslash($_POST['batch_action'])) : '';
        $args     = isset($_POST['args']) ? sanitize_text_field(wp_unslash($_POST['args'])) : null;

        if (empty($post_ids) || !in_array($action, ['ai', 'eu_ai', 'webp', 'avif', 'resize'], true)) {
            wp_send_json_error(['message' => __('Invalid request', 'packshotphoto-ai')], 400);
        }

        $results = [];
        foreach ($post_ids as $post_id) {
            // Check individual permission
            if (!current_user_can('edit_post', $post_id)) {
                $results[$post_id] = ['success' => false, 'message' => __('No permission', 'packshotphoto-ai')];
                continue;
            }

            $success = false;
            $message = __('Failed', 'packshotphoto-ai');
            $data    = [];

            switch ($action) {
                case 'ai':
                    $result = \PackshotPhotoAI\Core\AIProcessor::generate($post_id);
                    $success = $result['success'];
                    $message = $success ? __('AI generated', 'packshotphoto-ai') : ($result['message'] ?? __('AI failed', 'packshotphoto-ai'));
                    $data = $result['data'] ?? [];
                    break;
                case 'eu_ai':
                    $labeller = new \PackshotPhotoAI\Core\EuAiActLabeller();
                    $result = $labeller->apply_label($post_id);
                    $success = $result['success'];
                    $message = $result['message'] ?? ($success ? __('EU AI label applied', 'packshotphoto-ai') : __('EU AI labeling failed', 'packshotphoto-ai'));
                    $data = $result;
                    break;
                case 'webp':
                    $result = $this->process_webp($post_id);
                    $success = $result['success'];
                    $message = $result['message'] ?? ($success ? __('WebP converted', 'packshotphoto-ai') : __('WebP failed', 'packshotphoto-ai'));
                    $data = $result['data'] ?? [];
                    break;
                case 'avif':
                    $result = $this->process_avif($post_id);
                    $success = $result['success'];
                    $message = $result['message'] ?? ($success ? __('AVIF converted', 'packshotphoto-ai') : __('AVIF failed', 'packshotphoto-ai'));
                    $data = $result['data'] ?? [];
                    break;
                case 'resize':
                    $processor = new \PackshotPhotoAI\Core\ImageProcessor();
                    $width = $args ? (int)$args : (int)get_option('packshotphoto_max_image_size', 2000);
                    $result = $processor->resize($post_id, $width);
                    $success = $result['success'];
                    $message = $result['message'] ?? ($success ? __('Resized', 'packshotphoto-ai') : __('Resize failed', 'packshotphoto-ai'));
                    $data = $result['data'] ?? [];
                    
                    // Log failure details for debugging
                    if (!$success) {
                        Logger::error('Bulk resize failed', [
                            'post_id' => $post_id,
                            'target_width' => $width,
                            'result' => $result
                        ]);
                    }
                    break;
            }

            $results[$post_id] = [
                'success' => $success,
                'message' => $message,
                'data'    => $data
            ];
        }

        wp_send_json_success($results);
    }

    /**
     * Process WebP conversion for single attachment
     *
     * @param int $post_id Attachment ID
     * @return array Result
     */
    private function process_webp(int $post_id): array {
        $converter = new \PackshotPhotoAI\Core\WebPConverter();
        return $converter->convert($post_id, true);
    }

    /**
     * Process AVIF conversion for single attachment
     *
     * @param int $post_id Attachment ID
     * @return array Result
     */
    private function process_avif(int $post_id): array {
        $converter = new \PackshotPhotoAI\Core\AvifConverter();
        return $converter->convert($post_id, true);
    }

 }
