<?php
/* Plugin Name: RSO Smart Guard (Agent 3.0 FIM) */
if(!defined("ABSPATH")) exit;
define("RSO_KEY", "SUPER_SECRET_RSO_2026");

// 1. ODCZYT LOGÓW
add_action("wp_ajax_nopriv_get_rso_logs", function(){
    $key = isset($_POST["key"]) ? $_POST["key"] : "";
    if($key !== RSO_KEY) wp_die("Access Denied");
    echo json_encode(get_option("rso_security_logs_v2", array()));
    wp_die();
});

// 2. BLOKADA UPLOADU
add_filter("wp_handle_upload_prefilter", function($file){
    $ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
    if(in_array($ext, array("php","phtml","php3","phar","js"))){
        $logs = get_option("rso_security_logs_v2", array());
        $logs[] = array("date"=>date("Y-m-d H:i:s"), "type"=>"BLOCK_UPLOAD", "details"=>"Zablokowano upload: ".$file["name"]." (IP: ".$_SERVER["REMOTE_ADDR"].")");
        update_option("rso_security_logs_v2", array_slice($logs, -100));
        $file["error"] = "RSO Security 3.0: Unsafe uploads restricted.";
    }
    return $file;
});

// 3. SKANER PLIKÓW (FILE INTEGRITY MONITOR)
add_action("wp_ajax_nopriv_run_rso_scan", function(){
    $key = isset($_POST["key"]) ? $_POST["key"] : "";
    if($key !== RSO_KEY) wp_die("Access Denied");
    
    $dirs = array(ABSPATH . "wp-admin", ABSPATH . "wp-includes", WP_CONTENT_DIR);
    $current_state = array();
    
    // Zbieramy listę wszystkich wrażliwych plików
    foreach($dirs as $dir) {
        if(!is_dir($dir)) continue;
        $iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
        foreach($iter as $file) {
            if($file->isFile() && in_array(strtolower($file->getExtension()), array("php", "js", "htaccess"))) {
                $path = str_replace(ABSPATH, "", $file->getPathname());
                $current_state[$path] = $file->getMTime() . "_" . $file->getSize();
            }
        }
    }
    // Dodajemy pliki z głównego katalogu (np. wp-config.php)
    foreach(glob(ABSPATH . "*.php") as $file) {
        $path = str_replace(ABSPATH, "", $file);
        $current_state[$path] = filemtime($file) . "_" . filesize($file);
    }

    $baseline = get_option("rso_fim_baseline", array());
    $logs = get_option("rso_security_logs_v2", array());
    $changes = 0;

    if(!empty($baseline)) {
        // Porównanie ze starym stanem
        foreach($current_state as $path => $hash) {
            if(!isset($baseline[$path])) {
                $logs[] = array("date"=>date("Y-m-d H:i:s"), "type"=>"FILE_CREATED", "details"=>"Nowy plik: " . $path);
                $changes++;
            } elseif($baseline[$path] !== $hash) {
                $logs[] = array("date"=>date("Y-m-d H:i:s"), "type"=>"FILE_MODIFIED", "details"=>"Zmieniono plik: " . $path);
                $changes++;
            }
        }
        foreach($baseline as $path => $hash) {
            if(!isset($current_state[$path])) {
                $logs[] = array("date"=>date("Y-m-d H:i:s"), "type"=>"FILE_DELETED", "details"=>"Usunięto plik: " . $path);
                $changes++;
            }
        }
    } else {
        $logs[] = array("date"=>date("Y-m-d H:i:s"), "type"=>"INFO", "details"=>"Skan początkowy. Zabezpieczono ".count($current_state)." plików.");
    }

    if($changes > 0 || empty($baseline)) {
        update_option("rso_security_logs_v2", array_slice($logs, -100));
    }
    update_option("rso_fim_baseline", $current_state);
    
    echo json_encode(array("success"=>true, "changes"=>$changes, "total"=>count($current_state)));
    wp_die();
});