<?php
// Auto-split module from bot.php. Keep this file beside the project root.

// ========================== Lightweight JSON cache ==========================
// Heavy dashboards/lists are cached in /cache as JSON so frequent reads do not hit SQL every time.
function bot_cache_dir(){ return dirname(__DIR__, 2) . '/cache'; }
function bot_cache_safe_key($key){
    $key = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', (string)$key);
    return trim($key, '_');
}
function bot_cache_path($group, $key){
    $group = bot_cache_safe_key($group ?: 'general');
    $safe = bot_cache_safe_key($key);
    if($safe === '') $safe = sha1((string)$key);
    return bot_cache_dir() . '/' . $group . '_' . $safe . '_' . substr(sha1((string)$group.'|'.(string)$key),0,12) . '.json';
}
function bot_cache_get($group, $key, $ttl = 60){
    $file = bot_cache_path($group, $key);
    if(!is_file($file)) return null;
    $raw = @file_get_contents($file);
    $data = json_decode((string)$raw, true);
    if(!is_array($data) || !isset($data['created_at'])) return null;
    if($ttl > 0 && time() - (int)$data['created_at'] > (int)$ttl){ @unlink($file); return null; }
    return $data['payload'] ?? null;
}
function bot_cache_set($group, $key, $payload){
    $dir = bot_cache_dir(); if(!is_dir($dir)) @mkdir($dir, 0775, true);
    $file = bot_cache_path($group, $key);
    $tmp = $file.'.tmp';
    @file_put_contents($tmp, json_encode(['created_at'=>time(), 'payload'=>$payload], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    @rename($tmp, $file);
    return true;
}
function bot_cache_clear_group($group){
    $dir = bot_cache_dir(); if(!is_dir($dir)) return 0;
    $prefix = bot_cache_safe_key($group ?: 'general') . '_';
    $n = 0;
    foreach(glob($dir.'/'.$prefix.'*.json') ?: [] as $f){ if(@unlink($f)) $n++; }
    return $n;
}
function bot_cache_clear_heavy(){
    return bot_cache_clear_group('orders') + bot_cache_clear_group('admin_best') + bot_cache_clear_group('users');
}
function bot_cache_invalidate_for_path($path){
    $path = str_replace('\\','/', (string)$path);
    if(strpos($path, 'ads/') === 0){
        bot_cache_clear_group('orders');
        bot_cache_clear_group('admin_best');
        if(function_exists('bot_scale_cache_clear_group')){ bot_scale_cache_clear_group('storage_lists'); bot_scale_cache_clear_group('stats'); }
    }
    if(strpos($path, 'melat/') === 0 || $path === 'melat.json'){
        bot_cache_clear_group('users');
        bot_cache_clear_group('admin_best');
        if(function_exists('bot_scale_cache_clear_group')){ bot_scale_cache_clear_group('users'); bot_scale_cache_clear_group('stats'); }
    }
    if(strpos($path, 'lib/kodam/') === 0 || strpos($path, 'lib/Button/') === 0){
        bot_cache_clear_group('admin_best');
        if(function_exists('bot_scale_cache_clear_group')) bot_scale_cache_clear_group('stats');
    }
}
