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

// Set up scheduled scans
function moesec_setup_scheduled_scans() {
   $scheduled_scans = get_option('moesec_scheduled_scans', false);
   $scan_frequency = get_option('moesec_scan_frequency', 'daily');
   
   wp_clear_scheduled_hook('moesec_daily_scan');
   wp_clear_scheduled_hook('moesec_weekly_scan');
   wp_clear_scheduled_hook('moesec_monthly_scan');
   
   if ($scheduled_scans) {
       switch ($scan_frequency) {
           case 'daily':
               wp_schedule_event(time(), 'daily', 'moesec_daily_scan');
               moesec_log('✓ Scheduled scans ENABLED: Daily frequency - Cron job created');
               break;
           case 'weekly':
               wp_schedule_event(time(), 'weekly', 'moesec_weekly_scan');
               moesec_log('✓ Scheduled scans ENABLED: Weekly frequency - Cron job created');
               break;
           case 'monthly':
               wp_schedule_event(time(), 'monthly', 'moesec_monthly_scan');
               moesec_log('✓ Scheduled scans ENABLED: Monthly frequency - Cron job created');
               break;
           default:
               moesec_log('✗ Scheduled scans: Invalid frequency - ' . $scan_frequency);
       }
   } else {
       moesec_log('✓ Scheduled scans DISABLED - All cron jobs removed');
   }
}

function moesec_add_monthly_schedule($schedules) {
    if (!isset($schedules['weekly'])) {
        $schedules['weekly'] = array(
            'interval' => 604800,
            'display' => __('Once Weekly', 'moesec')
        );
    }
    if (!isset($schedules['monthly'])) {
        $schedules['monthly'] = array(
            'interval' => 2592000,
            'display' => __('Once Monthly', 'moesec')
        );
    }
    return $schedules;
}
add_filter('cron_schedules', 'moesec_add_monthly_schedule');

// Hook into scheduled events
add_action('moesec_daily_scan', 'moesec_run_scheduled_scan');
add_action('moesec_weekly_scan', 'moesec_run_scheduled_scan');
add_action('moesec_monthly_scan', 'moesec_run_scheduled_scan');

// Run scheduled scan
function moesec_run_scheduled_scan() {
    // Log that scheduled scan started
    moesec_log(esc_html__('Scheduled scan started', 'moesec'));
    
    $patterns_file = plugin_dir_path(__FILE__) . '../assets/patterns-files.txt';
    $patterns = file($patterns_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $patterns = array_map('base64_decode', $patterns);

    // DB patterns
    $patterns_dbs = plugin_dir_path(__FILE__) . '../assets/patterns-dbs.txt';
    $patternsdbs = file($patterns_dbs, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $patternsdbs = array_map('base64_decode', $patternsdbs);

    $suspicious_files = moesec_scan_files(ABSPATH, $patterns);
    $suspicious_db_entries = moesec_scan_database($patternsdbs);

    // Update scan results
    $total_threats = count($suspicious_files) + count($suspicious_db_entries);

    update_option('moesec_last_scan_time', current_time('mysql'));
    update_option('moesec_threats_detected', $total_threats);
    update_option('moesec_suspicious_files', $suspicious_files);
    update_option('moesec_suspicious_db_entries', $suspicious_db_entries);
   
    moesec_log(sprintf(
        /* translators: %d: number of threats detected */
        esc_html__('Scheduled scan completed. %d threats detected.', 'moesec'),
        $total_threats
    ));

    if ($total_threats > 0 && get_option('moesec_email_notifications', false)) {
        moesec_send_threat_notification($total_threats, $suspicious_files, $suspicious_db_entries);
    }
}

function moesec_send_threat_notification($total_threats, $suspicious_files, $suspicious_db_entries) {
    $to = get_option('moesec_notification_email', get_option('admin_email'));
    $subject = sprintf(
        /* translators: %d: number of threats detected */
        esc_html__('MoeSec Security Alert: %d Threats Detected', 'moesec'),
        $total_threats
    );

    $message = esc_html__("MoeSec has detected the following threats during a scheduled scan:\n\n", 'moesec');
    $message .= sprintf(
        /* translators: %d: number of suspicious files */
        esc_html__("Suspicious Files (%d)\n", 'moesec'),
        count($suspicious_files)
    );

    $message .= "\n" . sprintf(
        /* translators: %d: number of suspicious database entries */
        esc_html__("Suspicious Database Entries (%d)\n", 'moesec'),
        count($suspicious_db_entries)
    );

    $message .= "\n" . esc_html__('Please log in to your WordPress admin panel and check the MoeSec security plugin for more details.', 'moesec');

    wp_mail($to, $subject, $message);
    
    moesec_log(sprintf(
        /* translators: %d: number of threats */
        esc_html__('Threat notification email sent for %d threats', 'moesec'),
        $total_threats
    ));
}
?>
