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

function moesec_schedule_signature_update() {
    if (!wp_next_scheduled('moesec_daily_signature_update')) {
        wp_schedule_event(time(), 'daily', 'moesec_daily_signature_update');
    }
}

add_action('moesec_daily_signature_update', 'moesec_update_signatures');

function moesec_update_signatures() {
    $file_patterns_url = 'https://moesec.com/plugin/patterns-files.txt';
    $db_patterns_url = 'https://moesec.com/plugin/patterns-dbs.txt';
    
    $file_patterns_response = wp_remote_get($file_patterns_url);
    $db_patterns_response = wp_remote_get($db_patterns_url);
    
    $update_success = true;
    
    if (!is_wp_error($file_patterns_response)) {
        $file_patterns_content = wp_remote_retrieve_body($file_patterns_response);
        $file_patterns_path = plugin_dir_path(__FILE__) . '../assets/patterns-files.txt';
        if (file_put_contents($file_patterns_path, $file_patterns_content) === false) {
            //moesec_log('Failed to write file patterns to file.');
            $update_success = false;
        }
    } else {
        //moesec_log('Failed to download file patterns:');
        $update_success = false;
    }
    
    if (!is_wp_error($db_patterns_response)) {
        $db_patterns_content = wp_remote_retrieve_body($db_patterns_response);
        $db_patterns_path = plugin_dir_path(__FILE__) . '../assets/patterns-dbs.txt';
        if (file_put_contents($db_patterns_path, $db_patterns_content) === false) {
            //moesec_log('Failed to write database patterns to file.');
            $update_success = false;
        }
    } else {
        //moesec_log('Failed to download database patterns: ' . $db_patterns_response->get_error_message());
        $update_success = false;
    }
    
    if ($update_success) {
        update_option('moesec_last_signature_update', current_time('mysql'));
        moesec_log('Signatures updated successfully.');
    } else {
        moesec_log('Signature update failed.');
    }
    
    return $update_success;
}

function moesec_signature_update_tab() {
    if (isset($_POST['moesec_manual_signature_update'])) {
        check_admin_referer('moesec_signature_update', 'moesec_signature_update_nonce');
        $result = moesec_update_signatures();
        if ($result) {
            echo '<div class="updated"><p>Signatures updated successfully.</p></div>';
        } else {
            echo '<div class="error"><p>Failed to update signatures. Please try again or contact support.</p></div>';
        }
    }

    $last_update = get_option('moesec_last_signature_update');
    $last_update = $last_update ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_update)) : 'Never';
    ?>
    <h3>Signature Update</h3>
    <p>Last update: <?php echo esc_html($last_update); ?></p>
    <form method="post" action="">
        <?php wp_nonce_field('moesec_signature_update', 'moesec_signature_update_nonce'); ?>
        <input type="submit" name="moesec_manual_signature_update" class="button button-primary" value="Update Signatures Now">
    </form>
    <?php
}

add_action('admin_init', 'moesec_check_signature_update');

function moesec_check_signature_update() {
    if (isset($_GET['moesec_update_signatures']) && $_GET['moesec_update_signatures'] === 'true') {
        moesec_update_signatures();
        wp_redirect(admin_url('admin.php?page=moesec&tab=signature-update&updated=true'));
        exit;
    }
}

function moesec_get_last_signature_update() {
    $last_update = get_option('moesec_last_signature_update');
    return $last_update ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_update)) : 'Never';
}
