<?php
/**
 * CVE Auto-Sync and Scan Scheduler
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.6 -- Added critical vulnerability alert emails to admins
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Schedule CVE sync and scan tasks
 */
class VMPFence_CVE_Scheduler {
    
    /**
     * Initialize scheduler (only if API available)
     */
    public static function init() {
        // Only schedule if API is available (premium feature)
        if (!VMPFence_Config::is_api_available()) {
            return;
        }
        
        // Schedule daily CVE database sync
        if (!wp_next_scheduled('vmpfence_daily_cve_sync')) {
            wp_schedule_event(time(), 'daily', 'vmpfence_daily_cve_sync');
        }
        
        // Schedule daily vulnerability scan
        if (!wp_next_scheduled('vmpfence_daily_cve_scan')) {
            wp_schedule_event(time() + 3600, 'daily', 'vmpfence_daily_cve_scan'); // 1 hour after sync
        }
        
        // Hook the sync function
        add_action('vmpfence_daily_cve_sync', array(__CLASS__, 'sync_cve_database'));
        
        // Hook the scan function
        add_action('vmpfence_daily_cve_scan', array(__CLASS__, 'scan_vulnerabilities'));
    }
    
    /**
     * Sync CVE database from API
     */
    public static function sync_cve_database() {
        require_once VMPFENCE_PLUGIN_DIR . 'includes/cve/class-cve-sync.php';
        
        $result = VMPFence_CVE_Sync::sync_from_api();
        
        if ($result['success']) {
            VMPFence_Secure_Logger::log('info', 'CVE: Daily sync completed', ['imported' => $result['imported']]);
        } else {
            VMPFence_Secure_Logger::log('error', 'CVE: Daily sync failed', ['errors' => implode(', ', $result['errors'])]);
        }
    }
    
    /**
     * Run vulnerability scan
     */
    public static function scan_vulnerabilities() {
        require_once VMPFENCE_PLUGIN_DIR . 'includes/cve/class-cve-scanner.php';
        
        $scanner = new VMPFence_CVE_Scanner();
        $result = $scanner->scan_site();
        
        if ($result['success']) {
            // Send admin email if critical vulnerabilities found
            if ($result['severity_counts']['critical'] > 0) {
                self::send_critical_alert($result);
            }
        } else {
            VMPFence_Secure_Logger::log('error', 'CVE: Daily scan failed', ['error' => $result['error']]);
        }
    }
    
    /**
     * Send critical vulnerability alert email
     *
     * @param array $scan_results Scan results
     */
    private static function send_critical_alert($scan_results) {
        $admin_email = get_option('admin_email');
        $critical_count = $scan_results['severity_counts']['critical'];
        $high_count = $scan_results['severity_counts']['high'];

        // Send via centralized Email Service (API → branded template)
        $context = array(
            'critical_count' => $critical_count,
            'high_count'     => $high_count,
            'total_count'    => $scan_results['total_vulnerabilities'],
            'dashboard_url'  => admin_url('admin.php?page=vmpfence-cve-scanner'),
        );

        // Include individual vulnerability details if available
        if (!empty($scan_results['vulnerabilities'])) {
            $context['vulnerabilities'] = array_map(function ($v) {
                return array(
                    'name'     => isset($v['name']) ? $v['name'] : (isset($v['component']) ? $v['component'] : ''),
                    'severity' => isset($v['severity']) ? $v['severity'] : '',
                    'version'  => isset($v['version']) ? $v['version'] : '',
                    'cve_id'   => isset($v['cve_id']) ? $v['cve_id'] : '',
                );
            }, array_slice($scan_results['vulnerabilities'], 0, 20));
        }

        VMPFence_Email_Service::send_alert('cve_vulnerability_alert', $context, array($admin_email));

        VMPFence_Secure_Logger::log('warning', 'CVE: Critical vulnerability alert sent', ['admin_email' => $admin_email]);
    }
    
    /**
     * Unschedule tasks on deactivation
     */
    public static function unschedule() {
        $timestamp = wp_next_scheduled('vmpfence_daily_cve_sync');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'vmpfence_daily_cve_sync');
        }
        
        $timestamp = wp_next_scheduled('vmpfence_daily_cve_scan');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'vmpfence_daily_cve_scan');
        }
    }
}
