<?php
/**
 * Image Boost — AJAX Handlers
 */

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

class ImgBoost_Ajax {

    /**
     * Register AJAX actions.
     */
    public static function init() {
        add_action('wp_ajax_imgboost_bulk_optimize', [__CLASS__, 'handle_bulk_optimize']);
        add_action('wp_ajax_imgboost_single_optimize', [__CLASS__, 'handle_single_optimize']);
        add_action('wp_ajax_imgboost_restore_image', [__CLASS__, 'handle_restore']);
        add_action('wp_ajax_imgboost_get_stats', [__CLASS__, 'handle_get_stats']);
        add_action('wp_ajax_imgboost_save_settings', [__CLASS__, 'handle_save_settings']);
        add_action('wp_ajax_imgboost_save_level', [__CLASS__, 'handle_save_level']);
        add_action('wp_ajax_imgboost_quick_toggle', [__CLASS__, 'handle_quick_toggle']);
        add_action('wp_ajax_imgboost_scan_library', [__CLASS__, 'handle_scan_library']);
    }

    /**
     * Bulk optimize batch.
     */
    public static function handle_bulk_optimize() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }
        
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $level = isset($_POST['level']) ? sanitize_text_field(wp_unslash($_POST['level'])) : get_option('imgboost_compression_level', 'pro');
        if (!in_array($level, ['normal', 'pro'])) $level = 'pro';
        // phpcs:enable
        $batch_size = (int) get_option('imgboost_batch_size', 5);

        $result = ImgBoost_Bulk_Optimizer::process_batch($batch_size, $level);

        wp_send_json_success($result);
    }

    /**
     * Optimize a single image.
     */
    public static function handle_single_optimize() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        // Rate Limiting via Object Cache (zero DB writes, in-memory only)
        $rate_key = 'imgbst_rl_sgl_' . get_current_user_id();
        $requests = (int) wp_cache_get($rate_key, 'imgboost_rate');
        if ($requests >= 10) {
            wp_send_json_error(['message' => __('Rate limit exceeded. Please slow down.', 'image-boost')]);
        }
        wp_cache_set($rate_key, $requests + 1, 'imgboost_rate', 2);

        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $attachment_id = isset($_POST['attachment_id']) ? (int) $_POST['attachment_id'] : 0;
        $level = isset($_POST['level']) ? sanitize_text_field(wp_unslash($_POST['level'])) : get_option('imgboost_compression_level', 'pro');
        if (!in_array($level, ['normal', 'pro'])) $level = 'pro';
        // phpcs:enable

        if (!$attachment_id) {
            wp_send_json_error(['message' => __('Invalid attachment ID.', 'image-boost')]);
        }


        $result = ImgBoost_Bulk_Optimizer::optimize_single($attachment_id, $level);

        if (isset($result['status']) && $result['status'] === 'error') {
            wp_send_json_error($result);
        }

        wp_send_json_success($result);
    }

    /**
     * Restore an image from backup.
     */
    public static function handle_restore() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $attachment_id = isset($_POST['attachment_id']) ? (int) $_POST['attachment_id'] : 0;

        if (!$attachment_id) {
            wp_send_json_error(['message' => __('Invalid attachment ID.', 'image-boost')]);
        }

        $result = ImgBoost_Backup::restore($attachment_id);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        wp_send_json_success([
            'message' => __('Image restored successfully.', 'image-boost'),
            'id'      => $attachment_id,
        ]);
    }

    /**
     * Get dashboard statistics.
     */
    public static function handle_get_stats() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        $stats = ImgBoost_Stats::get_dashboard_stats();
        wp_send_json_success($stats);
    }

    /**
     * Save plugin settings.
     */
    public static function handle_save_settings() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $raw_level = sanitize_text_field(wp_unslash($_POST['compression_level'] ?? 'pro'));
        $settings = [
            'imgboost_compression_level' => in_array($raw_level, ['normal', 'pro']) ? $raw_level : 'pro',
            'imgboost_auto_optimize'     => isset($_POST['auto_optimize']) ? 1 : 0,
            'imgboost_webp_enabled'      => isset($_POST['webp_enabled']) ? 1 : 0,
            'imgboost_max_width'         => (int) sanitize_text_field(wp_unslash($_POST['max_width'] ?? '2560')),
            'imgboost_strip_metadata'    => isset($_POST['strip_metadata']) ? 1 : 0,
            'imgboost_backup_enabled'    => isset($_POST['backup_enabled']) ? 1 : 0,
            'imgboost_backup_days'       => (int) sanitize_text_field(wp_unslash($_POST['backup_days'] ?? '30')),
            'imgboost_lazy_loading'      => isset($_POST['lazy_loading']) ? 1 : 0,
            'imgboost_convert_png'       => isset($_POST['convert_png']) ? 1 : 0,
            'imgboost_resize_enabled'    => isset($_POST['resize_enabled']) ? 1 : 0,
            'imgboost_batch_size'        => max(1, min(20, (int) sanitize_text_field(wp_unslash($_POST['batch_size'] ?? '5')))),
            'imgboost_remove_data_on_uninstall' => isset($_POST['remove_data_on_uninstall']) ? 1 : 0,
        ];
        // phpcs:enable

        foreach ($settings as $key => $value) {
            update_option($key, $value);
        }

        wp_send_json_success(['message' => __('Settings saved successfully.', 'image-boost')]);
    }

    /**
     * Save only the compression level (from dashboard cards).
     */
    public static function handle_save_level() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $level = isset($_POST['compression_level']) ? sanitize_text_field(wp_unslash($_POST['compression_level'])) : 'pro';
        update_option('imgboost_compression_level', $level);

        wp_send_json_success();
    }

    /**
     * Handle quick toggles from the dashboard.
     */
    public static function handle_quick_toggle() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $setting = isset($_POST['setting']) ? sanitize_text_field(wp_unslash($_POST['setting'])) : '';
        $value   = isset($_POST['value']) && $_POST['value'] === '1' ? 1 : 0;

        $allowed_settings = ['imgboost_auto_optimize', 'imgboost_backup_enabled', 'imgboost_webp_enabled'];

        if (in_array($setting, $allowed_settings)) {
            update_option($setting, $value);
            wp_send_json_success();
        } else {
            wp_send_json_error(['message' => __('Invalid setting.', 'image-boost')]);
        }
    }

    /**
     * Scan media library and return count.
     */
    public static function handle_scan_library() {
        check_ajax_referer('imgboost_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'image-boost')]);
        }

        $total = ImgBoost_Stats::count_all_images();
        $unoptimized = ImgBoost_Stats::count_unoptimized();

        wp_send_json_success([
            'total'       => $total,
            'unoptimized' => $unoptimized,
            'optimized'   => $total - $unoptimized,
        ]);
    }
}
