<?php
defined('ABSPATH') || exit;

// IV1 WP Tools – Filemonitor AJAX & Funktionen

define('IV1WPT_FILE_MONITOR_OPTION', 'iv1wpt_file_monitor_snapshot');

/**
 * AJAX: Baseline erstellen
 */
add_action('wp_ajax_iv1wpt_filemonitor_create_baseline', 'iv1wpt_filemonitor_create_baseline_ajax');
function iv1wpt_filemonitor_create_baseline_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $snapshot = iv1wpt_filemonitor_create_snapshot();

    update_option(IV1WPT_FILE_MONITOR_OPTION, [
        'created_at' => time(),
        'files'      => $snapshot,
    ], false);

    wp_send_json_success([
        'message'    => __('Baseline created successfully.', 'iv1-wp-tools'),
        'created_at' => wp_date('d.m.Y H:i'),
        'count'      => count($snapshot),
    ]);
}

/**
 * AJAX: Änderungen prüfen
 */
add_action('wp_ajax_iv1wpt_filemonitor_scan_changes', 'iv1wpt_filemonitor_scan_changes_ajax');
function iv1wpt_filemonitor_scan_changes_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    $stored = get_option(IV1WPT_FILE_MONITOR_OPTION, []);

    if (empty($stored['files']) || !is_array($stored['files'])) {
        wp_send_json_error(__('No baseline found. Please create a baseline first.', 'iv1-wp-tools'));
    }

    $old_snapshot = $stored['files'];
    $new_snapshot = iv1wpt_filemonitor_create_snapshot();

    $result = iv1wpt_filemonitor_compare_snapshots($old_snapshot, $new_snapshot);

    wp_send_json_success([
        'message' => __('Scan completed.', 'iv1-wp-tools'),
        'summary' => [
            'added'   => count($result['added']),
            'changed' => count($result['changed']),
            'deleted' => count($result['deleted']),
        ],
        'result' => $result,
    ]);
}

/**
 * Snapshot aller überwachten Dateien erstellen
 */
function iv1wpt_filemonitor_create_snapshot(): array {
    $base = wp_normalize_path(ABSPATH);

    $paths = [
        ABSPATH . 'wp-admin',
        ABSPATH . 'wp-includes',
        WP_CONTENT_DIR . '/plugins',
        WP_CONTENT_DIR . '/themes',
    ];

    $snapshot = [];

    foreach ($paths as $path) {
        $path = wp_normalize_path($path);

        if (!is_dir($path)) {
            continue;
        }

        try {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );

            foreach ($iterator as $file) {
                if (!$file->isFile()) {
                    continue;
                }

                $full_path = wp_normalize_path($file->getPathname());

                if (iv1wpt_filemonitor_should_skip($full_path)) {
                    continue;
                }

                $relative = ltrim(str_replace($base, '', $full_path), '/');

                $hash = @hash_file('sha256', $full_path);

                if (!$hash) {
                    continue;
                }

                $snapshot[$relative] = [
                    'hash'  => $hash,
                    'size'  => (int) $file->getSize(),
                    'mtime' => (int) $file->getMTime(),
                ];
            }
        } catch (Exception $e) {
            continue;
        }
    }

    ksort($snapshot);

    return $snapshot;
}

/**
 * Dateien/Ordner überspringen
 */
function iv1wpt_filemonitor_should_skip(string $path): bool {
    $path = wp_normalize_path($path);

    $skip_parts = [
        '/node_modules/',
        '/vendor/',
        '/.git/',
        '/cache/',
        '/tmp/',
        '/logs/',
        '/backup/',
        '/backups/',
        '/iv1_backups/',
    ];

    foreach ($skip_parts as $part) {
        if (strpos($path, $part) !== false) {
            return true;
        }
    }

    return false;
}

/**
 * Snapshots vergleichen
 */
function iv1wpt_filemonitor_compare_snapshots(array $old, array $new): array {
    $added   = [];
    $changed = [];
    $deleted = [];

    foreach ($new as $path => $data) {
        if (!isset($old[$path])) {
            $added[$path] = $data;
            continue;
        }

        if (($old[$path]['hash'] ?? '') !== ($data['hash'] ?? '')) {
            $changed[$path] = [
                'old' => $old[$path],
                'new' => $data,
            ];
        }
    }

    foreach ($old as $path => $data) {
        if (!isset($new[$path])) {
            $deleted[$path] = $data;
        }
    }

    return [
        'added'   => $added,
        'changed' => $changed,
        'deleted' => $deleted,
    ];
}

/**
 * Infos zur vorhandenen Baseline holen
 */
function iv1wpt_filemonitor_get_baseline_info(): array {
    $stored = get_option(IV1WPT_FILE_MONITOR_OPTION, []);

    if (empty($stored['files']) || !is_array($stored['files'])) {
        return [
            'exists'     => false,
            'created_at' => '',
            'count'      => 0,
        ];
    }

    return [
        'exists'     => true,
        'created_at' => !empty($stored['created_at']) ? wp_date('d.m.Y H:i', (int) $stored['created_at']) : '',
        'count'      => count($stored['files']),
    ];
}

add_action('wp_ajax_iv1wpt_filemonitor_check_core', 'iv1wpt_filemonitor_check_core_ajax');
function iv1wpt_filemonitor_check_core_ajax(): void {
    check_ajax_referer('iv1wpt_ajax');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('No permission.', 'iv1-wp-tools'));
    }

    require_once ABSPATH . 'wp-admin/includes/update.php';

    if (!function_exists('get_core_checksums')) {
        wp_send_json_error(__('WordPress checksum function is not available.', 'iv1-wp-tools'));
    }

    $version = get_bloginfo('version');
    $locale  = get_locale();

    $checksums = get_core_checksums($version, $locale);

    if (!is_array($checksums)) {
        wp_send_json_error(__('Could not retrieve WordPress core checksums.', 'iv1-wp-tools'));
    }

    $changed = [];
    $missing = [];

	foreach ($checksums as $file => $expected_md5) {

		// Nur echten WordPress-Core prüfen.
		// wp-content enthält Themes, Plugins und Sprachdateien, die oft bewusst geändert/gelöscht werden.
		if (strpos($file, 'wp-content/') === 0) {
			continue;
		}

		$path = ABSPATH . $file;

		if (!file_exists($path)) {
			$missing[$file] = __('Missing', 'iv1-wp-tools');
			continue;
		}

		$actual_md5 = md5_file($path);

		if ($actual_md5 !== $expected_md5) {
			$changed[$file] = __('Changed', 'iv1-wp-tools');
		}
	}

    $items = array_merge($changed, $missing);

    if (empty($items)) {
        wp_send_json_success([
            'message' => __('WordPress core files are unchanged.', 'iv1-wp-tools'),
            'status'  => 'clean',
            'items'   => [],
        ]);
    }

    wp_send_json_success([
        'message' => __('WordPress core file changes detected.', 'iv1-wp-tools'),
        'status'  => 'warning',
        'items'   => $items,
    ]);
}