<?php
namespace NeoMotionBeta\NeoGlobal; if (!defined("ABSPATH")) { die("neoWP direct access not allowed"); }





// Create a dedicated cache directory for the neoPlugin in the filesystem location designated by WordPress.


function cache_path($subdir = null, $only_get_path = false) {
    try {
        \NeoMotionBeta\NeoGlobal\performance_checkpoint("cache_path", is_start: true);
        if (str_contains($subdir ?? "", "/")) { throw new \Error("Cache subdir must not contain slashes!"); }
        
        static $cache_path_cache = [];
        if (isset($cache_path_cache[$subdir ?? "null"]) && !\NeoMotionBeta\NeoGlobal\fs_file_exists($cache_path_cache[$subdir ?? "null"])) { unset($cache_path_cache[$subdir ?? "null"]); }
        if (isset($cache_path_cache[$subdir ?? "null"])) { return $cache_path_cache[$subdir ?? "null"]; }
        
        if ($subdir === "neo-log") {
            $existing_subdir = (\NeoMotionBeta\NeoGlobal\fs_glob(cache_path() . "/$subdir--*", GLOB_ONLYDIR) ?: [])[0] ?? null;
            if ($existing_subdir) { return cache_path(basename($existing_subdir)); }
            return cache_path($subdir . "--" . substr(hash("sha256", SECURE_AUTH_KEY . "neosalt"), 0, 16));
        }

        $cache_path = WP_CONTENT_DIR . "/cache/" . \NeoMotionBeta\NeoGlobal\get_plugin_cache_folder_name(\NeoMotionBeta\NeoGlobal\plugin_slug(), \NeoMotionBeta\NeoGlobal\plugin_edition());
        if ($only_get_path) { return $cache_path . ($subdir ? ("/" . $subdir) : ""); }
        \NeoMotionBeta\NeoGlobal\suppress_log(true); try {
            
            \NeoMotionBeta\NeoGlobal\mkdir_better(dirname($cache_path));
            \NeoMotionBeta\NeoGlobal\synclock_dir(dirname($cache_path), function() use ($cache_path) { \NeoMotionBeta\NeoGlobal\mkdir_better($cache_path); });
            
            return \NeoMotionBeta\NeoGlobal\synclock_dir($cache_path, function() use (&$cache_path_cache, &$cache_path, &$subdir) {
                
                $cleanup_cache = false;
                $version_file = $cache_path . "/.version";
                if (!\NeoMotionBeta\NeoGlobal\fs_file_exists($version_file) || \NeoMotionBeta\NeoGlobal\plugin_version() !== \NeoMotionBeta\NeoGlobal\fs_file_get_contents($version_file)) {
                    $cleanup_cache = true;
                    \NeoMotionBeta\NeoGlobal\fs_file_put_contents($version_file, \NeoMotionBeta\NeoGlobal\plugin_version());
                }

                if (\NeoMotionBeta\NeoGlobal\is_live_update_version(\NeoMotionBeta\NeoGlobal\plugin_version())) { $cleanup_cache = false; }
                
                if ($cleanup_cache) {
                    \NeoMotionBeta\NeoGlobal\clear_plugin_cache(delete_all: false);
                }

                $cache_hash_path = $cache_path . "/cache-hash.json";
                $plugin_hash_path = \NeoMotionBeta\NeoGlobal\plugin_path() . "/" . "plugin-hash.txt";
                $is_cache_hash_valid = function () use ($cache_hash_path) { if (\NeoMotionBeta\NeoGlobal\plugin_edition() === "dev") { return true; } try { $cache_hash_contents = \NeoMotionBeta\NeoGlobal\json_decode_better(\NeoMotionBeta\NeoGlobal\fs_file_get_contents($cache_hash_path) ?: "[]"); return ($cache_hash_contents["cache_hash"] ?? "cache_hash") === ($cache_hash_contents["plugin_hash"] ?? "plugin_hash"); } catch (\Throwable $e) { \NeoMotionBeta\NeoGlobal\global_warn_with_module_name("_global-cache", "Broken cache hash: " . $e->getMessage()); return false; } };
                if (\NeoMotionBeta\NeoGlobal\fs_file_exists($plugin_hash_path) && (!\NeoMotionBeta\NeoGlobal\fs_file_exists($cache_hash_path) || \NeoMotionBeta\NeoGlobal\is_cache_file_outdated($cache_hash_path, (7) * 24 * 60 * 60) || !$is_cache_hash_valid())) {
                    $hash_dbg = false;
                    $cache_hash = "";
                    if ($hash_dbg) { $cache_hash_dbg = ""; }
                    $files = iterator_to_array(\NeoMotionBeta\NeoGlobal\iterate_all_files(\NeoMotionBeta\NeoGlobal\plugin_path()));
                    usort($files, function ($a, $b) { return strcmp($a, $b); });
                    foreach ($files as $file) {
                        $file_ending = pathinfo(__FILE__, PATHINFO_EXTENSION);
                        if (!str_ends_with($file, ".$file_ending")) { continue; }
                        if (str_ends_with($file, "/neo-pro--activate-license" . ".$file_ending")) { continue; }
                        $cache_hash .= md5(\NeoMotionBeta\NeoGlobal\fs_file_get_contents($file));
                        if ($hash_dbg) { $cache_hash_dbg .= "=== " . \NeoMotionBeta\NeoGlobal\make_plugin_file_path_relative($file) . " ===\n" . \NeoMotionBeta\NeoGlobal\fs_file_get_contents($file) . "\n\nIn between hash: $cache_hash\n\n\n\n"; }
                    }
                    $cache_hash = md5($cache_hash);
                    \NeoMotionBeta\NeoGlobal\fs_file_put_contents($cache_hash_path, \NeoMotionBeta\NeoGlobal\json_encode_better(["cache_hash" => $cache_hash, "plugin_hash" => \NeoMotionBeta\NeoGlobal\fs_file_get_contents($plugin_hash_path)]));
                    if ($hash_dbg) {
                        $plugin_hash_path_dbg = \NeoMotionBeta\NeoGlobal\plugin_path() . "/" . "plugin-hash-debug.txt";
                        \NeoMotionBeta\NeoGlobal\fs_file_put_contents(str_replace(".json", "-debug-cache-hash.txt",  $cache_hash_path), str_replace(["\r\n", "\n"], ["R\n", "N\n"], $cache_hash_dbg));
                        \NeoMotionBeta\NeoGlobal\fs_file_put_contents(str_replace(".json", "-debug-plugin-hash.txt", $cache_hash_path), str_replace(["\r\n", "\n"], ["R\n", "N\n"], \NeoMotionBeta\NeoGlobal\fs_file_exists($plugin_hash_path_dbg) ? \NeoMotionBeta\NeoGlobal\fs_file_get_contents($plugin_hash_path_dbg) : ""));
                    }
                }

                // Add empty index.php to the cache folder for security (no directory listing allowed)
                if (!\NeoMotionBeta\NeoGlobal\fs_file_exists($cache_path . "/index.php")) { \NeoMotionBeta\NeoGlobal\fs_file_put_contents($cache_path . "/index.php", "<?php\n// Silence is golden.\n"); }
                
                $cache_path_with_subdir = $cache_path . ($subdir ? ("/" . $subdir) : "");
                \NeoMotionBeta\NeoGlobal\mkdir_better($cache_path_with_subdir);
                
                $cache_path_cache[$subdir ?? "null"] = $cache_path_with_subdir;
                
                return $cache_path_with_subdir;
            });
        } finally {
            \NeoMotionBeta\NeoGlobal\suppress_log(false);
        }
    } finally { \NeoMotionBeta\NeoGlobal\performance_checkpoint("cache_path", is_end: true); }
}


function cache_url($subdir = null) {
    $cache_path = cache_path($subdir);
    if (!str_starts_with($cache_path, WP_CONTENT_DIR . "/")) { throw new \Error("Cache path must start with WP_CONTENT_DIR!"); } /* The WP_CONTENT_DIR constant is required here because the already resolved cache path must be compared against the exact filesystem base path, not a URL or filtered value from a WordPress helper. This prevents generating invalid public cache URLs on custom wp-content setups and keeps cached assets accessible for users. */
    return content_url() . substr($cache_path, strlen(WP_CONTENT_DIR)); /* The WP_CONTENT_DIR constant is required here because the already resolved cache path must be trimmed by the exact filesystem base path before appending the remaining suffix to content_url(). This preserves support for relocated wp-content directories and prevents broken cache asset URLs for users. */
}



\NeoMotionBeta\NeoGlobal\add_action_hook("neo_init", function () { cache_path(); });
