<?php
/**
 * Post Content Scanner AJAX Handlers
 *
 * Thin wrappers around SQMedia_Post_Content_Scanner methods.
 *
 * @package StaticQ
 * @since 3.3.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class SQMedia_Post_Content_Scanner_Ajax {

    /**
     * Initialize AJAX handlers
     */
    public static function init(): void {
        // Scan operations
        add_action('wp_ajax_sqmedia_start_post_content_scan', [self::class, 'start_scan']);
        add_action('wp_ajax_sqmedia_process_post_content_batch', [self::class, 'process_batch']);
        add_action('wp_ajax_sqmedia_cancel_post_content_scan', [self::class, 'cancel_scan']);
        add_action('wp_ajax_sqmedia_pause_post_content_scan', [self::class, 'pause_scan']);
        add_action('wp_ajax_sqmedia_resume_post_content_scan', [self::class, 'resume_scan']);

        // Fix operations
        add_action('wp_ajax_sqmedia_start_post_content_fix', [self::class, 'start_fix']);
        add_action('wp_ajax_sqmedia_process_post_content_fix_batch', [self::class, 'process_fix_batch']);
        add_action('wp_ajax_sqmedia_stop_post_content_fix', [self::class, 'stop_fix']);

        // Details + single fix
        add_action('wp_ajax_sqmedia_get_post_content_scan_details', [self::class, 'get_details']);
        add_action('wp_ajax_sqmedia_fix_single_post_content', [self::class, 'fix_single_post']);

        // Table backup
        add_action('wp_ajax_sqmedia_backup_pcs_tables', [self::class, 'backup_tables']);
    }

    /**
     * Start a new scan
     */
    public static function start_scan(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        $result = $scanner->start();

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['error']);
        }
    }

    /**
     * Process a batch
     */
    public static function process_batch(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        $result = $scanner->process_batch($scan_id);

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['error'] ?? __('Batch processing failed.', 'staticq-media'));
        }
    }

    /**
     * Cancel scan
     */
    public static function cancel_scan(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        wp_send_json_success($scanner->cancel($scan_id));
    }

    /**
     * Pause scan
     */
    public static function pause_scan(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        wp_send_json_success($scanner->pause($scan_id));
    }

    /**
     * Resume scan
     */
    public static function resume_scan(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        wp_send_json_success($scanner->resume($scan_id));
    }

    /**
     * Start fix
     */
    public static function start_fix(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        $result = $scanner->start_fix($scan_id);

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['error']);
        }
    }

    /**
     * Process fix batch
     */
    public static function process_fix_batch(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        $result = $scanner->process_fix_batch($scan_id);

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['error'] ?? __('Fix processing failed.', 'staticq-media'));
        }
    }

    /**
     * Stop fix
     */
    public static function stop_fix(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        wp_send_json_success($scanner->stop_fix($scan_id));
    }

    /**
     * Get scan details grouped by post (one row per post, expandable)
     */
    public static function get_details(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        $category = sanitize_text_field(wp_unslash($_POST['category'] ?? ''));
        $page = max(1, absint(wp_unslash($_POST['page'] ?? 1)));
        $per_page = 20;
        $offset = ($page - 1) * $per_page;

        if (empty($scan_id)) {
            wp_send_json_error(__('No scan ID provided.', 'staticq-media'));
        }

        $db = sqmedia()->get_database();
        $cat_filter = !empty($category) ? $category : null;

        // Get paginated distinct post IDs
        $post_ids = $db->get_scan_distinct_items_paginated($scan_id, $cat_filter, $per_page, $offset);
        $total_posts = $db->count_scan_distinct_items($scan_id, $cat_filter);

        $fixable_cats = [SQMedia_Post_Content_Scanner::CAT_WRONG_DOMAIN, SQMedia_Post_Content_Scanner::CAT_STALE_SIZE];

        $items = [];
        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);

            // Get ALL scan items for this post (show everything when expanded)
            $scan_items = $db->get_scan_items_for_id($scan_id, $post_id);

            $badges = [];
            $issues = [];
            $has_fixable = false;

            foreach ($scan_items as $scan_item) {
                $cat = $scan_item->action_type;
                $details = $scan_item->details ? json_decode($scan_item->details, true) : [];
                $item_list = $details['items'] ?? [$details];

                $is_fixable = in_array($cat, $fixable_cats, true);
                if ($is_fixable) {
                    $has_fixable = true;
                }

                $badges[] = [
                    'category' => $cat,
                    'count' => count($item_list),
                    'fixable' => $is_fixable,
                ];

                // Build issue details for expansion
                if ($cat === SQMedia_Post_Content_Scanner::CAT_WRONG_DOMAIN) {
                    // Group wrong domain — show once with count and unique domains
                    $domains = [];
                    foreach ($item_list as $detail) {
                        $domain = $detail['domain'] ?? '';
                        if ($domain && !in_array($domain, $domains, true)) {
                            $domains[] = $domain;
                        }
                    }
                    $issues[] = [
                        'category' => $cat,
                        'count' => count($item_list),
                        'domains' => $domains,
                    ];
                } else {
                    // Show each individually
                    foreach ($item_list as $detail) {
                        $issues[] = [
                            'category' => $cat,
                            'count' => 1,
                            'detail' => $detail,
                        ];
                    }
                }
            }

            $items[] = [
                'post_id' => $post_id,
                'post_title' => $post ? $post->post_title : __('(deleted)', 'staticq-media'),
                'edit_url' => $post ? get_edit_post_link($post_id, 'raw') : '',
                'badges' => $badges,
                'issues' => $issues,
                'has_fixable' => $has_fixable,
            ];
        }

        wp_send_json_success([
            'items' => $items,
            'total' => $total_posts,
            'page' => $page,
            'pages' => (int) ceil($total_posts / $per_page),
        ]);
    }

    /**
     * Fix a single post's content issues
     */
    public static function fix_single_post(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $scan_id = sanitize_text_field(wp_unslash($_POST['scan_id'] ?? ''));
        $post_id = absint(wp_unslash($_POST['post_id'] ?? 0));

        if (empty($scan_id) || !$post_id) {
            wp_send_json_error(__('Missing parameters.', 'staticq-media'));
        }

        $scanner = new SQMedia_Post_Content_Scanner();
        $result = $scanner->fix_post($post_id, $scan_id);

        if ($result['fixed']) {
            wp_send_json_success([
                'post_id' => $post_id,
                'fixed_count' => $result['fixed_count'],
            ]);
        } else {
            wp_send_json_error($result['error'] ?? __('No changes were needed.', 'staticq-media'));
        }
    }

    /**
     * Create backup of wp_posts table
     */
    public static function backup_tables(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Insufficient permissions.', 'staticq-media'));
        }

        $result = SQMedia_Database::create_table_backup('pcs');

        if ($result['success']) {
            $now = current_time('mysql');
            wp_send_json_success([
                'message' => sprintf(
                    /* translators: %s: date and time of backup */
                    __('Backup exists from %s', 'staticq-media'),
                    wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($now))
                ),
                'tables'  => $result['tables'],
            ]);
        } else {
            wp_send_json_error($result['error']);
        }
    }
}
