<?php

// Prevent direct call
if ( ! defined('ABSPATH') ) {
    die('Not allowed!');
}

require_once 'spbct-sync-react.php';

function spbc_admin_add_react_page()
{
    add_options_page(
        __(' Settings via React', 'security-malware-firewall'),
        'SPBC Settings via React',
        'manage_options',
        'spbct',
        function () {
            echo "<div id='spbct_root'
                data-nonce='" . esc_attr(wp_create_nonce('spbc_secret_nonce')) . "' 
                data-ajaxurl='" . esc_attr(admin_url('admin-ajax.php')) . "'
            ></div>";
        }
    );
}

add_action('wp_ajax_spbct_get_tab_data', 'spbct_get_tab_data');
function spbct_get_tab_data()
{
    spbc_check_ajax_referer('spbc_secret_nonce', 'security');

    $tab_name = sanitize_text_field($_POST['tab_name']);
    $function_name = "spbct_get_tab_data_{$tab_name}";

    if ( function_exists($function_name) ) {
        $res = $function_name();
    } else {
        $res = [
            'request_malware_removal' => false,
            'data_type' => 'text',
            'data' => $tab_name,
            'tab_settings' => []
        ];
    }

    wp_send_json($res);
}
function spbct_get_tab_data_firewall()
{
    global $wpdb, $spbc;
    $request_per = isset($spbc->settings['traffic_control__autoblock_timeframe'])
        ? (int)$spbc->settings['traffic_control__autoblock_timeframe'] / 60
        : 5;
    $columns = [
        'ip_entry'        => esc_html__('IP', 'security-malware-firewall'),
        'country_code'    => esc_html__('Country', 'security-malware-firewall'),
        'entry_timestamp' => esc_html__('Last Request', 'security-malware-firewall'),
        'status'          => esc_html__('Status', 'security-malware-firewall'),
        'requests'        => esc_html__('Requests and attempts', 'security-malware-firewall'),
        'requests_per'    => sprintf(esc_html__('Requests per %s minutes', 'security-malware-firewall'), $request_per),
        'page_url'        => esc_html__('Page', 'security-malware-firewall'),
        'http_user_agent' => esc_html__('User Agent', 'security-malware-firewall')
    ];
    $query = 'SELECT ' . trim(implode(',', array_keys($columns)), ',')
           . ' FROM ' . SPBC_TBL_FIREWALL_LOG
           . ' ORDER BY entry_timestamp desc '
           . ' LIMIT %d ';
    $prepared_query = $wpdb->prepare($query, [SPBC_LAST_ACTIONS_TO_VIEW]);
    $results = $wpdb->get_results($prepared_query);
    $table_data = [
        'columns' => $columns,
        'rows' => $results
    ];
    $output = [
        'request_malware_removal' => false,
        'data_type' => 'table',
        'data' => $table_data,
        'tab_settings' => [],
    ];
    return $output;
}
