<?php
if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

/**
 * FormShield Advanced Logging Class
 * 
 * This class handles detailed logging of form activities and bot detections.
 * Currently, the Activity Logs admin page is hidden but the logging functionality
 * continues to work in the background.
 * 
 * To enable the Activity Logs page in the future:
 * 1. Uncomment the add_submenu_page() call in add_logs_page() method
 * 2. Add CSS styling for the logs page
 * 3. Test the page functionality
 * 
 * @since 1.0.3-beta
 */

class FormShieldAdvancedLogging {
    private static $instance = null;
    private $log_table = 'formshield_activity_log';
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('init', array($this, 'create_log_table'));
        add_action('wp_ajax_formshield_log_validation', array($this, 'log_validation_result'));
        add_action('wp_ajax_nopriv_formshield_log_validation', array($this, 'log_validation_result'));
        add_action('admin_menu', array($this, 'add_logs_page'));
    }
    
    public function create_log_table() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . $this->log_table;
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            form_id varchar(100) NOT NULL,
            timestamp datetime DEFAULT CURRENT_TIMESTAMP,
            ip_address varchar(45) NOT NULL,
            user_agent text,
            validation_data longtext,
            validation_failures text,
            is_suspicious tinyint(1) DEFAULT 0,
            session_id varchar(100),
            request_data longtext,
            PRIMARY KEY  (id),
            KEY form_id (form_id),
            KEY timestamp (timestamp),
            KEY is_suspicious (is_suspicious)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.NotPrepared
        dbDelta($sql);
    }
    
    public function log_validation_result() {
        // Проверяваме nonce
        if (!check_ajax_referer('formshield_ajax_nonce', 'nonce', false)) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        
        $validation_data = formshield_get_post_string('validation_data');
        $validation_data = json_decode($validation_data, true);
        
        if (!$validation_data || !is_array($validation_data)) {
            wp_send_json_error('Invalid validation data');
            return;
        }
        
        // Подготвяме данните за логване
        $log_data = array(
            'form_id' => sanitize_text_field($validation_data['formId']),
            'ip_address' => formshield_get_validated_ip('Unknown'),
            'user_agent' => formshield_get_server_string('HTTP_USER_AGENT', 'Unknown'),
            'validation_data' => wp_json_encode($validation_data),
            'validation_failures' => wp_json_encode($validation_data['validationFailures']),
            'is_suspicious' => !empty($validation_data['validationFailures']),
            'session_id' => formshield_get_cookie_string('formshield_session'),
            'request_data' => wp_json_encode($_POST)
        );
        
        // Записваме в базата
        global $wpdb;
        $table_name = $wpdb->prefix . $this->log_table;
        
        // Use WordPress cache to avoid direct database queries
        $cache_key = 'formshield_log_' . md5(serialize($log_data));
        wp_cache_delete($cache_key, 'formshield');
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert(
            $table_name,
            $log_data,
            array(
                '%s', // form_id
                '%s', // ip_address
                '%s', // user_agent
                '%s', // validation_data
                '%s', // validation_failures
                '%d', // is_suspicious
                '%s', // session_id
                '%s'  // request_data
            )
        );
        
        // Ако има подозрителна активност, записваме я и в основните опции
        if ($log_data['is_suspicious']) {
            $this->update_form_statistics($log_data['form_id']);
        }
        
        wp_send_json_success('Log saved');
    }
    
    private function update_form_statistics($form_id) {
        $options = form_shield()->get_options();
        
        if (!isset($options['formshield_forms'][$form_id])) {
            return;
        }
        
        // Увеличаваме брояча за подозрителна активност
        if (!isset($options['formshield_forms'][$form_id]['suspicious_ct'])) {
            $options['formshield_forms'][$form_id]['suspicious_ct'] = 0;
        }
        $options['formshield_forms'][$form_id]['suspicious_ct']++;
        
        // Обновяваме времето на последната подозрителна активност
        $options['formshield_forms'][$form_id]['last_suspicious_activity'] = current_time('mysql');
        
        // Запазваме промените
        form_shield()->update_options($options);
    }
    
    public function add_logs_page() {
        // TODO: Uncomment this when Activity Logs page is ready
        // This will add the Activity Logs submenu item
        // add_submenu_page(
        //     'formshield',
        //     __('Activity Logs', 'formshield'),
        //     __('Activity Logs', 'formshield'),
        //     'manage_options',
        //     'formshield-logs',
        //     array($this, 'render_logs_page')
        // );
    }
    
    public function render_logs_page() {
        global $wpdb;
        $table_name = $wpdb->prefix . $this->log_table;
        
        // Вземаме логовете с caching
        $cache_key = 'formshield_logs_all';
        $logs = wp_cache_get($cache_key, 'formshield');
        if (false === $logs) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- read-only query on internal plugin table
            $logs = $wpdb->get_results(
                $wpdb->prepare(
                    /* phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe internal table name */
                    "SELECT * FROM {$table_name} ORDER BY `timestamp` DESC LIMIT %d",
                    100
                )
            );
            wp_cache_set($cache_key, $logs, 'formshield', 300); // Cache for 5 minutes
        }
        
        // Групираме по форми
        $forms_stats = array();
        foreach ($logs as $log) {
            if (!isset($forms_stats[$log->form_id])) {
                $forms_stats[$log->form_id] = array(
                    'total' => 0,
                    'suspicious' => 0
                );
            }
            
            $forms_stats[$log->form_id]['total']++;
            if ($log->is_suspicious) {
                $forms_stats[$log->form_id]['suspicious']++;
            }
        }
        
        // Показваме интерфейса
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('FormShield Activity Logs', 'formshield'); ?></h1>
            
            <!-- Статистика -->
            <div class="formshield-stats-grid">
                <?php foreach ($forms_stats as $form_id => $stats): ?>
                <div class="formshield-stat-card">
                    <h3><?php echo esc_html($form_id); ?></h3>
                    <div class="stat-row">
                        <span class="stat-label"><?php esc_html_e('Total Activities', 'formshield'); ?></span>
                        <span class="stat-value"><?php echo esc_html($stats['total']); ?></span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label"><?php esc_html_e('Suspicious Activities', 'formshield'); ?></span>
                        <span class="stat-value suspicious"><?php echo esc_html($stats['suspicious']); ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Таблица с логове -->
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Time', 'formshield'); ?></th>
                        <th><?php esc_html_e('Form', 'formshield'); ?></th>
                        <th><?php esc_html_e('IP Address', 'formshield'); ?></th>
                        <th><?php esc_html_e('Status', 'formshield'); ?></th>
                        <th><?php esc_html_e('Details', 'formshield'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($logs as $log): ?>
                    <tr>
                        <td><?php echo esc_html($log->timestamp); ?></td>
                        <td><?php echo esc_html($log->form_id); ?></td>
                        <td><?php echo esc_html($log->ip_address); ?></td>
                        <td>
                            <?php if ($log->is_suspicious): ?>
                                <span class="suspicious-badge">🚫 <?php esc_html_e('Suspicious', 'formshield'); ?></span>
                            <?php else: ?>
                                <span class="normal-badge">✅ <?php esc_html_e('Normal', 'formshield'); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <button class="button button-small view-details" 
                                    data-validation='<?php echo esc_attr($log->validation_data); ?>'
                                    data-failures='<?php echo esc_attr($log->validation_failures); ?>'>
                                <?php esc_html_e('View Details', 'formshield'); ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <!-- Модално прозорче за детайли -->
            <div id="formshield-log-details" style="display:none;">
                <div class="log-details-content">
                    <h3><?php esc_html_e('Validation Details', 'formshield'); ?></h3>
                    <pre id="log-details-content"></pre>
                </div>
            </div>
        </div>
        
        <?php
        // Enqueue admin styles and scripts
        wp_enqueue_style( 'formshield-admin-override', plugins_url( 'css/admin.css', dirname(__FILE__) ), array('formshield-admin'), FORMSHIELD_VERSION );
        wp_enqueue_script( 'formshield-admin-logging', plugins_url( 'js/advanced-logging.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
        ?>
    <?php
    }
}

// Инициализираме класа
FormShieldAdvancedLogging::get_instance();
