<?php

if (!defined('ABSPATH')) {
    exit;
}

// Schedule integrity check
function moesec_schedule_integrity_check() {
    $enable_integrity_check = get_option('moesec_enable_integrity_check', false);
    $integrity_check_frequency = get_option('moesec_integrity_check_frequency', 'daily');
    
    // Clear existing schedule
    wp_clear_scheduled_hook('moesec_daily_integrity_check');
    wp_clear_scheduled_hook('moesec_weekly_integrity_check');
    wp_clear_scheduled_hook('moesec_monthly_integrity_check');
    
    if ($enable_integrity_check) {
        switch ($integrity_check_frequency) {
            case 'daily':
                wp_schedule_event(time(), 'daily', 'moesec_daily_integrity_check');
                moesec_log('✓ Integrity checks ENABLED: Daily frequency - Cron job created');
                break;
            case 'weekly':
                wp_schedule_event(time(), 'weekly', 'moesec_weekly_integrity_check');
                moesec_log('✓ Integrity checks ENABLED: Weekly frequency - Cron job created');
                break;
            case 'monthly':
                wp_schedule_event(time(), 'monthly', 'moesec_monthly_integrity_check');
                moesec_log('✓ Integrity checks ENABLED: Monthly frequency - Cron job created');
                break;
            default:
                wp_schedule_event(time(), 'daily', 'moesec_daily_integrity_check');
                moesec_log('✓ Integrity checks ENABLED: Daily frequency (default) - Cron job created');
        }
    } else {
        moesec_log('✓ Integrity checks DISABLED - All cron jobs removed');
    }
}

// Run scheduled integrity check
add_action('moesec_daily_integrity_check', 'moesec_run_scheduled_integrity_check');
add_action('moesec_weekly_integrity_check', 'moesec_run_scheduled_integrity_check');
add_action('moesec_monthly_integrity_check', 'moesec_run_scheduled_integrity_check');

function moesec_run_scheduled_integrity_check() {
    $results = moesec_run_integrity_check();
    
    if (!empty($results['modified']) || !empty($results['added']) || !empty($results['missing'])) {
        // Send email notification if enabled
        if (get_option('moesec_email_notifications', false)) {
            $admin_email = get_option('moesec_notification_email', get_option('admin_email'));
            $subject = sprintf('[%s] MoeSec Integrity Check Alert', get_bloginfo('name'));
            
            $message = sprintf(
                "Integrity check detected changes:\n\n" .
                "Modified files: %d\n" .
                "Added files: %d\n" .
                "Missing files: %d\n\n" .
                "Please review these changes at: %s",
                count($results['modified']),
                count($results['added']),
                count($results['missing']),
                admin_url('admin.php?page=moesec&tab=integrity-check')
            );
            
            wp_mail($admin_email, $subject, $message);
        }
    }
    
    moesec_log(sprintf(
        'Integrity check completed: %d modified, %d added, %d missing',
        count($results['modified']),
        count($results['added']),
        count($results['missing'])
    ));
}

function moesec_integrity_check_tab() {
    // Handle form submissions
    if (isset($_POST['moesec_integrity_check']) && check_admin_referer('moesec_integrity_check', 'moesec_integrity_check_nonce')) {
        $integrity_check_results = moesec_run_integrity_check();
        update_option('moesec_last_integrity_check', $integrity_check_results);
        update_option('moesec_last_integrity_check_time', current_time('mysql'));
    }
    
    // Handle integrity check settings
    if (isset($_POST['moesec_save_integrity_settings']) && check_admin_referer('moesec_integrity_settings', 'moesec_integrity_settings_nonce')) {
        $enable_integrity_check = isset($_POST['enable_integrity_check']);
        update_option('moesec_enable_integrity_check', $enable_integrity_check);
        
        $integrity_check_frequency = isset($_POST['integrity_check_frequency']) ? sanitize_text_field($_POST['integrity_check_frequency']) : 'daily';
        update_option('moesec_integrity_check_frequency', $integrity_check_frequency);
        
        // Reschedule
        moesec_schedule_integrity_check();
        
        echo '<div class="updated"><p>' . esc_html__('Integrity check settings saved.', 'moesec') . '</p></div>';
    }
    
    // Handle whitelist actions
    if (isset($_GET['action']) && isset($_GET['file']) && isset($_GET['_wpnonce'])) {
        if ($_GET['action'] === 'whitelist_integrity' && wp_verify_nonce($_GET['_wpnonce'], 'moesec_whitelist_integrity')) {
            $file = sanitize_text_field(urldecode($_GET['file']));
            moesec_whitelist_integrity_file($file);
            echo '<div class="updated"><p>' . esc_html__('File whitelisted successfully.', 'moesec') . '</p></div>';
        } elseif ($_GET['action'] === 'remove_integrity_whitelist' && wp_verify_nonce($_GET['_wpnonce'], 'moesec_remove_integrity_whitelist')) {
            $file = sanitize_text_field(urldecode($_GET['file']));
            moesec_remove_integrity_whitelist($file);
            echo '<div class="updated"><p>' . esc_html__('File removed from whitelist.', 'moesec') . '</p></div>';
        }
    }
    
    $last_check_results = get_option('moesec_last_integrity_check', array());
    $last_check_time = get_option('moesec_last_integrity_check_time', null);
    $enable_integrity_check = get_option('moesec_enable_integrity_check', false);
    $whitelisted_files = get_option('moesec_integrity_whitelist', array());
    $integrity_check_frequency = get_option('moesec_integrity_check_frequency', 'daily');
    
    ?>
    <style>
    .moesec-integrity-results {
        margin: 20px 0;
    }
    .moesec-integrity-section {
        background: #fff;
        border-left: 4px solid #ccc;
        padding: 15px 20px;
        margin: 15px 0;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .moesec-integrity-section.modified {
        border-left-color: #ff9800;
        background: #fff8e1;
    }
    .moesec-integrity-section.added {
        border-left-color: #2196f3;
        background: #e3f2fd;
    }
    .moesec-integrity-section.missing {
        border-left-color: #f44336;
        background: #ffebee;
    }
    .moesec-integrity-section.ok {
        border-left-color: #4caf50;
        background: #e8f5e9;
    }
    .moesec-integrity-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    .moesec-integrity-icon {
        font-size: 24px;
        margin-right: 10px;
    }
    .moesec-integrity-title {
        font-size: 16px;
        font-weight: 600;
        margin: 0;
    }
    .moesec-integrity-count {
        margin-left: auto;
        background: rgba(0,0,0,0.1);
        padding: 5px 12px;
        border-radius: 15px;
        font-weight: bold;
    }
    .moesec-file-list {
        list-style: none;
        padding: 0;
        margin: 10px 0 0 0;
    }
    .moesec-file-item {
        padding: 8px 12px;
        margin: 5px 0;
        background: rgba(255,255,255,0.7);
        border-radius: 4px;
        display: flex;
        align-items: center;
        font-family: 'Courier New', monospace;
        font-size: 13px;
    }
    .moesec-file-path {
        flex: 1;
        word-break: break-all;
    }
    .moesec-file-actions {
        margin-left: 10px;
    }
    .moesec-stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin: 20px 0;
    }
    .moesec-stat-box {
        background: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        text-align: center;
    }
    .moesec-stat-number {
        font-size: 32px;
        font-weight: bold;
        margin: 10px 0;
    }
    .moesec-stat-label {
        color: #666;
        font-size: 14px;
    }
    .modified .moesec-stat-number { color: #ff9800; }
    .added .moesec-stat-number { color: #2196f3; }
    .missing .moesec-stat-number { color: #f44336; }
    .ok .moesec-stat-number { color: #4caf50; }
    </style>
    
    <h3><?php esc_html_e('MoeSec WordPress Core Integrity Check', 'moesec'); ?></h3>
    
    <div class="moesec-integrity-settings" style="background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 8px;">
        <h4><?php esc_html_e('Integrity Check Settings', 'moesec'); ?></h4>
        <form method="post" action="">
            <?php wp_nonce_field('moesec_integrity_settings', 'moesec_integrity_settings_nonce'); ?>
            <table class="form-table">
                <tr>
                    <th><label for="enable_integrity_check"><?php esc_html_e('Enable Daily Integrity Check', 'moesec'); ?></label></th>
                    <td>
                        <input type="checkbox" id="enable_integrity_check" name="enable_integrity_check" <?php checked($enable_integrity_check); ?>>
                        <p class="description"><?php esc_html_e('Automatically check WordPress core file integrity daily and send email notifications if changes are detected.', 'moesec'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="integrity_check_frequency"><?php esc_html_e('Check Frequency', 'moesec'); ?></label></th>
                    <td>
                        <select id="integrity_check_frequency" name="integrity_check_frequency">
                            <option value="daily" <?php selected($integrity_check_frequency, 'daily'); ?>><?php esc_html_e('Daily', 'moesec'); ?></option>
                            <option value="weekly" <?php selected($integrity_check_frequency, 'weekly'); ?>><?php esc_html_e('Weekly', 'moesec'); ?></option>
                            <option value="monthly" <?php selected($integrity_check_frequency, 'monthly'); ?>><?php esc_html_e('Monthly', 'moesec'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Select how often you want the integrity check to run.', 'moesec'); ?></p>
                    </td>
                </tr>
            </table>
            <p class="submit">
                <input type="submit" name="moesec_save_integrity_settings" class="button button-primary" value="<?php esc_attr_e('Save Settings', 'moesec'); ?>">
            </p>
        </form>
    </div>
    
    <?php if ($last_check_time): ?>
    <div style="background: #fff; padding: 15px; margin: 20px 0; border-left: 4px solid #0073aa;">
        <strong><?php esc_html_e('Last Check:', 'moesec'); ?></strong> <?php echo esc_html($last_check_time); ?>
    </div>
    <?php endif; ?>
    
    <form method="post" action="">
        <?php wp_nonce_field('moesec_integrity_check', 'moesec_integrity_check_nonce'); ?>
        <p>
            <input type="submit" name="moesec_integrity_check" class="button button-primary button-large" value="<?php esc_attr_e('🔍 Run Integrity Check Now', 'moesec'); ?>">
        </p>
        <p class="description">
            <?php esc_html_e('This will compare your WordPress core files against the official repository checksums to detect any modifications, additions, or missing files.', 'moesec'); ?>
        </p>
    </form>
    
    <?php if (!empty($last_check_results)): ?>
    <div class="moesec-integrity-results">
        <h3><?php esc_html_e('Integrity Check Results', 'moesec'); ?></h3>
        
        <!-- Summary Stats -->
        <div class="moesec-stats-grid">
            <div class="moesec-stat-box modified">
                <div class="moesec-stat-label"><?php esc_html_e('Modified Files', 'moesec'); ?></div>
                <div class="moesec-stat-number"><?php echo count($last_check_results['modified']); ?></div>
            </div>
            <div class="moesec-stat-box added">
                <div class="moesec-stat-label"><?php esc_html_e('Added Files', 'moesec'); ?></div>
                <div class="moesec-stat-number"><?php echo count($last_check_results['added']); ?></div>
            </div>
            <div class="moesec-stat-box missing">
                <div class="moesec-stat-label"><?php esc_html_e('Missing Files', 'moesec'); ?></div>
                <div class="moesec-stat-number"><?php echo count($last_check_results['missing']); ?></div>
            </div>
            <div class="moesec-stat-box ok">
                <div class="moesec-stat-label"><?php esc_html_e('Status', 'moesec'); ?></div>
                <div class="moesec-stat-number">
                    <?php 
                    if (empty($last_check_results['modified']) && empty($last_check_results['added']) && empty($last_check_results['missing'])) {
                        echo '✓';
                    } else {
                        echo '⚠';
                    }
                    ?>
                </div>
            </div>
        </div>
        
        <!-- Modified Files -->
        <?php if (!empty($last_check_results['modified'])): ?>
        <div class="moesec-integrity-section modified">
            <div class="moesec-integrity-header">
                <span class="moesec-integrity-icon">⚠️</span>
                <h4 class="moesec-integrity-title"><?php esc_html_e('Modified Files', 'moesec'); ?></h4>
                <span class="moesec-integrity-count"><?php echo count($last_check_results['modified']); ?></span>
            </div>
            <p><?php esc_html_e('These core files have been modified from their original versions:', 'moesec'); ?></p>
            <ul class="moesec-file-list">
                <?php foreach ($last_check_results['modified'] as $file): ?>
                <li class="moesec-file-item">
                    <span class="moesec-file-path"><?php echo esc_html($file); ?></span>
                    <span class="moesec-file-actions">
                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=moesec&tab=integrity-check&action=whitelist_integrity&file=' . urlencode($file) . '#integrity-check'), 'moesec_whitelist_integrity')); ?>" class="button button-small">
                            <?php esc_html_e('Whitelist', 'moesec'); ?>
                        </a>
                    </span>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <!-- Added Files -->
        <?php if (!empty($last_check_results['added'])): ?>
        <div class="moesec-integrity-section added">
            <div class="moesec-integrity-header">
                <span class="moesec-integrity-icon">ℹ️</span>
                <h4 class="moesec-integrity-title"><?php esc_html_e('Added Files', 'moesec'); ?></h4>
                <span class="moesec-integrity-count"><?php echo count($last_check_results['added']); ?></span>
            </div>
            <p><?php esc_html_e('These files exist but are not part of the official WordPress core:', 'moesec'); ?></p>
            <ul class="moesec-file-list">
                <?php foreach ($last_check_results['added'] as $file): ?>
                <li class="moesec-file-item">
                    <span class="moesec-file-path"><?php echo esc_html($file); ?></span>
                    <span class="moesec-file-actions">
                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=moesec&tab=integrity-check&action=whitelist_integrity&file=' . urlencode($file) . '#integrity-check'), 'moesec_whitelist_integrity')); ?>" class="button button-small">
                            <?php esc_html_e('Whitelist', 'moesec'); ?>
                        </a>
                    </span>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <!-- Missing Files -->
        <?php if (!empty($last_check_results['missing'])): ?>
        <div class="moesec-integrity-section missing">
            <div class="moesec-integrity-header">
                <span class="moesec-integrity-icon">❌</span>
                <h4 class="moesec-integrity-title"><?php esc_html_e('Missing Files', 'moesec'); ?></h4>
                <span class="moesec-integrity-count"><?php echo count($last_check_results['missing']); ?></span>
            </div>
            <p><?php esc_html_e('These core files are missing from your WordPress installation:', 'moesec'); ?></p>
            <ul class="moesec-file-list">
                <?php foreach ($last_check_results['missing'] as $file): ?>
                <li class="moesec-file-item">
                    <span class="moesec-file-path"><?php echo esc_html($file); ?></span>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        
        <!-- All Clear -->
        <?php if (empty($last_check_results['modified']) && empty($last_check_results['added']) && empty($last_check_results['missing'])): ?>
        <div class="moesec-integrity-section ok">
            <div class="moesec-integrity-header">
                <span class="moesec-integrity-icon">✅</span>
                <h4 class="moesec-integrity-title"><?php esc_html_e('All Clear!', 'moesec'); ?></h4>
            </div>
            <p><?php esc_html_e('All WordPress core files match their official checksums. Your installation is intact.', 'moesec'); ?></p>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- Whitelisted Files -->
    <?php if (!empty($whitelisted_files)): ?>
    <div class="moesec-integrity-section" style="border-left-color: #9e9e9e; background: #f5f5f5;">
        <div class="moesec-integrity-header">
            <span class="moesec-integrity-icon">📋</span>
            <h4 class="moesec-integrity-title"><?php esc_html_e('Whitelisted Files', 'moesec'); ?></h4>
            <span class="moesec-integrity-count"><?php echo count($whitelisted_files); ?></span>
        </div>
        <p><?php esc_html_e('These files are excluded from integrity checks:', 'moesec'); ?></p>
        <ul class="moesec-file-list">
            <?php foreach ($whitelisted_files as $file): ?>
            <li class="moesec-file-item">
                <span class="moesec-file-path"><?php echo esc_html($file); ?></span>
                <span class="moesec-file-actions">
                    <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=moesec&tab=integrity-check&action=remove_integrity_whitelist&file=' . urlencode($file) . '#integrity-check'), 'moesec_remove_integrity_whitelist')); ?>" class="button button-small">
                        <?php esc_html_e('Remove', 'moesec'); ?>
                    </a>
                </span>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <div class="moesec-info-box" style="background: #e7f3fd; border-left: 4px solid #0073aa; padding: 15px; margin: 20px 0;">
        <h4><?php esc_html_e('About MoeSec Integrity Checks:', 'moesec'); ?></h4>
        <ul>
            <li><?php esc_html_e('Compares your files against official WordPress checksums', 'moesec'); ?></li>
            <li><?php esc_html_e('Detects unauthorized modifications to core files', 'moesec'); ?></li>
            <li><?php esc_html_e('Whitelist legitimate customizations to reduce false positives', 'moesec'); ?></li>
            <li><?php esc_html_e('Schedule daily, weekly, or monthly checks with email notifications', 'moesec'); ?></li>
        </ul>
    </div>
    <?php
}

// Run integrity check
function moesec_run_integrity_check() {
    global $wp_version;
    
    $checksums_url = "https://api.wordpress.org/core/checksums/1.0/?version=" . $wp_version . "&locale=" . get_locale();
    
    $response = wp_remote_get($checksums_url, array('timeout' => 30));
    
    if (is_wp_error($response)) {
        return array(
            'modified' => array(),
            'added' => array(),
            'missing' => array(),
            'error' => $response->get_error_message()
        );
    }
    
    $checksums_data = json_decode(wp_remote_retrieve_body($response), true);
    
    if (!isset($checksums_data['checksums'])) {
        return array(
            'modified' => array(),
            'added' => array(),
            'missing' => array(),
            'error' => 'Invalid checksums data'
        );
    }
    
    $checksums = $checksums_data['checksums'];
    $whitelisted_files = get_option('moesec_integrity_whitelist', array());
    
    $modified = array();
    $added = array();
    $missing = array();
    
    $wp_content_dir = basename(WP_CONTENT_DIR);
    
    foreach ($checksums as $file => $expected_hash) {
        if (in_array($file, $whitelisted_files)) {
            continue;
        }
        
        if (strpos($file, 'wp-content/') === 0 && $wp_content_dir !== 'wp-content') {
            $file = str_replace('wp-content/', $wp_content_dir . '/', $file);
        }
        
        $file_path = ABSPATH . $file;
        
        if (!file_exists($file_path)) {
            $missing[] = $file;
            continue;
        }
        
        $actual_hash = md5_file($file_path);
        
        if ($actual_hash !== $expected_hash) {
            $modified[] = $file;
        }
    }
    
    $core_dirs = array(
        ABSPATH . 'wp-admin',
        ABSPATH . 'wp-includes'
    );
    
    foreach ($core_dirs as $dir) {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        
        foreach ($files as $file) {
            if ($file->isFile()) {
                $relative_path = str_replace(ABSPATH, '', $file->getPathname());
                
                if (in_array($relative_path, $whitelisted_files)) {
                    continue;
                }
                
                $check_path = $relative_path;
                if ($wp_content_dir !== 'wp-content' && strpos($check_path, $wp_content_dir . '/') === 0) {
                    $check_path = str_replace($wp_content_dir . '/', 'wp-content/', $check_path);
                }
                
                if (!isset($checksums[$check_path])) {
                    $added[] = $relative_path;
                }
            }
        }
    }
    
    return array(
        'modified' => $modified,
        'added' => $added,
        'missing' => $missing
    );
}

function moesec_whitelist_integrity_file($file) {
    $whitelist = get_option('moesec_integrity_whitelist', array());
    
    if (!in_array($file, $whitelist)) {
        $whitelist[] = $file;
        update_option('moesec_integrity_whitelist', $whitelist);
        moesec_log('File whitelisted from integrity check: ' . $file);
    }
}

function moesec_remove_integrity_whitelist($file) {
    $whitelist = get_option('moesec_integrity_whitelist', array());
    $key = array_search($file, $whitelist);
    
    if ($key !== false) {
        unset($whitelist[$key]);
        update_option('moesec_integrity_whitelist', array_values($whitelist));
        moesec_log('File removed from integrity whitelist: ' . $file);
    }
}
?>
