<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

function moesec_create_log_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'moesec_logs';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        message text NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

function moesec_log($message) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'moesec_logs';
    
    $wpdb->insert(
        $table_name,
        array(
            'time' => current_time('mysql'),
            'message' => $message
        )
    );
}

function moesec_get_logs($limit = 100) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'moesec_logs';
    
    $query = "SELECT * FROM $table_name ORDER BY time DESC LIMIT %d";
    return $wpdb->get_results($wpdb->prepare($query, $limit));
}

function moesec_get_recent_logs($limit = 5) {
    return moesec_get_logs($limit);
}

function moesec_logs_tab() {
    $logs = moesec_get_logs();
    ?>
    <h3>Security Logs</h3>
    <table class="widefat">
        <thead>
            <tr>
                <th>Time</th>
                <th>Message</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($logs as $log): ?>
            <tr>
                <td><?php echo esc_html($log->time); ?></td>
                <td><?php echo esc_html($log->message); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php
}
