<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WP_REST_Request;
use WP_REST_Response;
use WPUltimateSecurity\UltimateSecurity\Modules\TestMode\TestModeService;

class TestModeController
{
    /**
     * Get test mode data including settings, stats, and available roles
     */
    public static function get_test_mode_data(WP_REST_Request $request): WP_REST_Response
    {
        return new WP_REST_Response([
            'settings' => TestModeService::getSettings(),
            'stats' => [
                'today' => TestModeService::getSimulationCount('today'),
                'week' => TestModeService::getSimulationCount('week'),
                'month' => TestModeService::getSimulationCount('month'),
                'total' => TestModeService::getTotalSimulationCount(),
                'by_module' => TestModeService::getSimulationsByModule('today'),
            ],
            'available_roles' => TestModeService::getAvailableRoles(),
        ], 200);
    }

    /**
     * Get paginated simulation logs
     */

    // public static function get_simulation_logs(WP_REST_Request $request): WP_REST_Response
    // {
    //     $page = max(1, (int) $request->get_param('page'));
    //     $perPage = max(1, min(100, (int) ($request->get_param('per_page') ?: 50)));
    //     $offset = ($page - 1) * $perPage;

    //     $total = TestModeService::getTotalSimulationCount();
    //     $logs = TestModeService::getRecentSimulations($perPage, $offset);

    //     return new WP_REST_Response([
    //         'data' => $logs,
    //         'total' => $total,
    //         'pages' => (int) ceil($total / $perPage),
    //         'current_page' => $page,
    //         'per_page' => $perPage,
    //     ], 200);
    // }
    public static function get_simulation_logs(WP_REST_Request $request): WP_REST_Response
    {
        if (!current_user_can('manage_options')) {
            return new WP_REST_Response([
                'error_message' => esc_html__('You do not have permission to access this resource.', 'ultimate-security')
            ], 403);
        }

        global $wpdb;

        // Input params
        $page = max(1, (int) $request->get_param('page'));
        $per_page = max(1, min(100, (int) ($request->get_param('per_page') ?: 50)));
        $offset = ($page - 1) * $per_page;
        $search = trim($request->get_param('search') ?? '');
        $sort_field = $request->get_param('sort_field') ?: 'created_at';
        $sort_order = strtoupper($request->get_param('sort_order') ?: 'DESC');

        // Validate sort order
        $sort_order = in_array($sort_order, ['ASC', 'DESC'], true) ? $sort_order : 'DESC';

        // Valid sortable fields
        $valid_sort_fields = ['id', 'created_at', 'module', 'action'];
        if (!in_array($sort_field, $valid_sort_fields, true)) {
            $sort_field = 'created_at';
        }

        // Use dedicated testmode_simulations table
        $table = $wpdb->prefix . 'ultimate_security_testmode_simulations';

        // Build WHERE clause for search
        $where_clause = '1=1';
        $prepare_args = [];

        if ($search !== '') {
            $like = '%' . $wpdb->esc_like($search) . '%';
            $where_clause = "(module LIKE %s OR action LIKE %s OR reason LIKE %s OR user_role LIKE %s)";
            $prepare_args = [$like, $like, $like, $like];
        }

        // Count total results
        $count_sql = "SELECT COUNT(*) FROM {$table} WHERE {$where_clause}";

        if (!empty($prepare_args)) {
            $count_sql = $wpdb->prepare($count_sql, ...$prepare_args);
        }

        $total = (int) $wpdb->get_var($count_sql);

        // Main query - build safely
        $query_sql = "SELECT * FROM {$table} WHERE {$where_clause} ORDER BY {$sort_field} {$sort_order} LIMIT %d OFFSET %d";

        // Add LIMIT and OFFSET to prepare args
        $query_prepare_args = array_merge($prepare_args, [$per_page, $offset]);

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $query_sql = $wpdb->prepare($query_sql, ...$query_prepare_args);

        $rows = $wpdb->get_results($query_sql, ARRAY_A);

        // Format data using direct columns
        $data = [];
        if (!empty($rows)) {
            $data = array_map(function ($row) {
                return [
                    'id' => (int) $row['id'],
                    'created_at' => $row['created_at'],
                    'message' => [
                        'module' => $row['module'] ?? 'unknown',
                        'action' => $row['action'] ?? 'unknown',
                        'reason' => $row['reason'] ?? '',
                        'user_role' => $row['user_role'] ?? 'N/A',
                    ]
                ];
            }, $rows);
        }

        // Final response
        return new WP_REST_Response([
            'data' => $data,
            'total' => $total,
            'pages' => (int) ceil($total / $per_page),
            'current_page' => $page,
            'per_page' => $per_page,
        ], 200);
    }

    /**
     * Clear all simulation logs
     */
    public static function clear_logs(WP_REST_Request $request): WP_REST_Response
    {
        $deleted = TestModeService::clearSimulationLogs();
        return new WP_REST_Response([
            'success' => true,
            'deleted' => $deleted,
            'message' => sprintf(
                /* translators: %d: number of deleted log entries */
                __('Cleared %d simulation log entries.', 'ultimate-security'),
                $deleted
            ),
        ], 200);
    }
}
