<?php
/**
 * Registration AJAX Handlers
 *
 * Handles all AJAX requests for Media Registration.
 * Thin wrappers around SQMedia_Registration_Handler (extends SQMedia_Batch_Processor).
 * Response format matches the legacy batch-based API so zero JS changes are needed.
 *
 * @package StaticQ
 * @since 3.2.0
 */

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

class SQMedia_Registration_Ajax {

    /**
     * Initialize AJAX handlers
     */
    public static function init(): void {
        add_action('wp_ajax_sqmedia_preview_registration', [self::class, 'preview']);
        add_action('wp_ajax_sqmedia_start_registration', [self::class, 'start']);
        add_action('wp_ajax_sqmedia_process_registration_batch', [self::class, 'process_batch']);
        add_action('wp_ajax_sqmedia_cancel_registration', [self::class, 'cancel']);

        // Legacy action aliases
        add_action('wp_ajax_sqmedia_preview_migration', [self::class, 'preview']);
        add_action('wp_ajax_sqmedia_start_migration', [self::class, 'start']);
        add_action('wp_ajax_sqmedia_process_migration_batch', [self::class, 'process_batch']);
    }

    /**
     * Preview: count unregistered attachments
     */
    public static function preview(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');

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

        $filters = [];
        if (!empty($_POST['start_date'])) {
            $filters['start_date'] = sanitize_text_field(wp_unslash($_POST['start_date']));
        }
        if (!empty($_POST['end_date'])) {
            $filters['end_date'] = sanitize_text_field(wp_unslash($_POST['end_date']));
        }

        $handler = new SQMedia_Registration_Handler();
        $count = $handler->count_unregistered($filters);

        $html = '<p>' . sprintf(
            // translators: %d is the number of attachments
            __('%d attachments will be registered.', 'staticq-media'),
            $count
        ) . '</p>';

        wp_send_json_success(['html' => $html, 'count' => $count]);
    }

    /**
     * Start registration
     */
    public static function start(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');

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

        $filters = [];
        if (!empty($_POST['start_date'])) {
            $filters['start_date'] = sanitize_text_field(wp_unslash($_POST['start_date']));
        }
        if (!empty($_POST['end_date'])) {
            $filters['end_date'] = sanitize_text_field(wp_unslash($_POST['end_date']));
        }

        $handler = new SQMedia_Registration_Handler();
        $result = $handler->start($filters);

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

    /**
     * Process next batch
     * Translates scan_id-based response to legacy batch_id format for the JS polling loop
     */
    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'));
        }

        $batch_id = sanitize_text_field(wp_unslash($_POST['batch_id'] ?? ''));

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

        $handler = new SQMedia_Registration_Handler();
        $result = $handler->process_batch($batch_id);

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

        // Extract registration counters from results JSON into top-level keys
        // so the JS polling loop gets them without changes
        $results = $result['results'] ?? [];
        $reg = $results['registration'] ?? [];

        $result['registered'] = $reg['registered'] ?? 0;
        $result['skipped'] = $reg['skipped'] ?? 0;
        $result['errors'] = $reg['errors'] ?? 0;
        $result['recent'] = $reg['recent'] ?? [];

        // Map completed status for the JS check: data.status === 'completed'
        if (!empty($result['done'])) {
            $result['status'] = 'completed';

            // Add completion message
            $result['message'] = sprintf(
                /* translators: %d: number of registered attachments */
                __('Registration completed. %d attachments registered. Run Health Check to verify file states.', 'staticq-media'),
                $result['registered']
            );
        }

        wp_send_json_success($result);
    }

    /**
     * Cancel registration
     */
    public static function cancel(): void {
        check_ajax_referer('sqmedia_admin_nonce', 'nonce');

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

        $batch_id = sanitize_text_field(wp_unslash($_POST['batch_id'] ?? ''));

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

        $handler = new SQMedia_Registration_Handler();
        $result = $handler->cancel($batch_id);

        wp_send_json_success($result);
    }
}