<?php
/**
 * Database Actions Admin Handler
 *
 * Handles AJAX requests for database optimization tasks including
 * running tasks, getting counts, and retrieving overview data.
 *
 * @package Mamba\Modules\DB\Services\Admin
 * @since   1.0.0
 */

namespace Mamba\Modules\DB\Services\Admin;

use Mamba\Modules\DB\Services\DatabaseOptimizer;

/**
 * Class DbActions
 *
 * AJAX handler for database optimization admin actions including
 * task execution, count retrieval, and overview data generation.
 *
 * @since 1.0.0
 */
final class DbActions {
        public static function handleRunTask(): void {
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(__('Insufficient permissions.', 'mamba-cache-for-woocommerce'));
        }

        check_ajax_referer('mamba_db_optimize', 'nonce');

        $taskId = sanitize_key(wp_unslash($_POST['task_id'] ?? ''));
        if (empty($taskId)) {
            wp_send_json_error(__('Invalid task ID.', 'mamba-cache-for-woocommerce'));
        }

        try {
            $optimizer = new DatabaseOptimizer();
            $affected = $optimizer->executeTask($taskId);

            wp_send_json_success([
                'affected' => $affected,
                'message' => sprintf(
                    __('Task completed successfully. %d rows affected.', 'mamba-cache-for-woocommerce'),
                    $affected
                )
            ]);
        } catch (\Exception $e) {
            // Log error for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("Mamba DB Optimizer AJAX Error: " . $e->getMessage());
            }
            wp_send_json_error(__('Task failed. Please check the error logs for details.', 'mamba-cache-for-woocommerce'));
        }
    }

        public static function handleGetCounts(): void {
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(__('Insufficient permissions.', 'mamba-cache-for-woocommerce'));
        }

        check_ajax_referer('mamba_db_optimize', 'nonce');

        try {
            $optimizer = new DatabaseOptimizer();
            $counts = $optimizer->calculateCounts();

            wp_send_json_success($counts);
        } catch (\Exception $e) {
            // Log error for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("Mamba DB Optimizer AJAX Error: " . $e->getMessage());
            }
            wp_send_json_error(__('Failed to get counts. Please check the error logs for details.', 'mamba-cache-for-woocommerce'));
        }
    }

    public static function handleGetOverview(): void {
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(__('Insufficient permissions.', 'mamba-cache-for-woocommerce'));
        }

        check_ajax_referer('mamba_db_optimize', 'nonce');

        try {
            $optimizer = new DatabaseOptimizer();
            $tasks = $optimizer->getTasks();
            $settings = get_option('mamba_db_optimizer_settings', []);

            // Calculate overview stats
            $totalTasks = count($tasks);
            $enabledTasks = 0;
            $totalAffected = 0;
            $lastRunTime = 0;

            foreach ($tasks as $taskId => $task) {
                $taskSettings = $settings[$taskId] ?? [];
                if (!empty($taskSettings['enabled'])) {
                    $enabledTasks++;
                }
                if (!empty($taskSettings['last'])) {
                    $lastRunTime = max($lastRunTime, $taskSettings['last']);
                    if (!empty($taskSettings['last_rows'])) {
                        $totalAffected += $taskSettings['last_rows'];
                    }
                }
            }

            // Generate the HTML for stats
            ob_start();
            ?>
            <div class="mamba-execution-stat">
                <span class="mamba-execution-label"><?php echo esc_html( __('Scheduled Tasks', 'mamba-cache-for-woocommerce') ); ?></span>
                <span class="mamba-execution-value"><?php echo esc_html($enabledTasks); ?>/<?php echo esc_html($totalTasks); ?></span>
            </div>
            <div class="mamba-execution-stat">
                <span class="mamba-execution-label"><?php echo esc_html( __('Last Cleanup', 'mamba-cache-for-woocommerce') ); ?></span>
                <span class="mamba-execution-value">
                    <?php echo $lastRunTime ? esc_html(date_i18n('M j, g:i A', $lastRunTime)) : esc_html( __('Never', 'mamba-cache-for-woocommerce') ); ?>
                </span>
            </div>
            <div class="mamba-execution-stat">
                <span class="mamba-execution-label"><?php echo esc_html( __('Total Cleaned', 'mamba-cache-for-woocommerce') ); ?></span>
                <span class="mamba-execution-value"><?php echo esc_html(number_format_i18n($totalAffected)); ?> rows</span>
            </div>
            <?php
            $html = ob_get_clean();

            wp_send_json_success(['html' => $html]);
        } catch (\Exception $e) {
            // Log error for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("Mamba DB Optimizer AJAX Error: " . $e->getMessage());
            }
            wp_send_json_error(__('Failed to get overview. Please check the error logs for details.', 'mamba-cache-for-woocommerce'));
        }
    }
}
