<?php

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

class AIEO_Google_Reviews_Cache {

    const VER_GROUP    = 'aieo_grv_ver';
    const RENDER_GROUP = 'aieo_grv';
    const ALL_LOC_KEY  = '__all__';

    private static $request_memo = array();

    
    public static function get_version($location_key) {
        $key = self::normalise_key($location_key);
        $v   = wp_cache_get($key, self::VER_GROUP);
        if (!is_int($v) || $v <= 0) {
            
            $persisted = (int) get_option('aieo_grv_ver_' . $key, 0);
            $v = $persisted > 0 ? $persisted : 1;
            wp_cache_set($key, $v, self::VER_GROUP, 0);
        }
        return $v;
    }

    
    public static function bump_version($location_key) {
        foreach (array(self::normalise_key($location_key), self::ALL_LOC_KEY) as $k) {
            $next = self::get_version($k) + 1;
            wp_cache_set($k, $next, self::VER_GROUP, 0);
            update_option('aieo_grv_ver_' . $k, $next, false);
        }
    }

    
    public static function render_get($location_key, $attrs_hash) {
        $loc = self::normalise_key($location_key);
        $ver = self::get_version($loc);
        $key = $loc . ':' . $ver . ':' . $attrs_hash;

        if (array_key_exists($key, self::$request_memo)) {
            return self::$request_memo[$key];
        }
        $val = wp_cache_get($key, self::RENDER_GROUP);
        if ($val !== false) {
            self::$request_memo[$key] = $val;
        }
        return $val;
    }

    public static function render_set($location_key, $attrs_hash, $value) {
        $loc = self::normalise_key($location_key);
        $ver = self::get_version($loc);
        $key = $loc . ':' . $ver . ':' . $attrs_hash;

        wp_cache_set($key, $value, self::RENDER_GROUP, 0);
        self::$request_memo[$key] = $value;
    }

    private static function normalise_key($k) {
        if ($k === null || $k === '' || $k === 'all') {
            return self::ALL_LOC_KEY;
        }
        if (is_int($k) || ctype_digit((string) $k)) {
            return 'loc_' . (int) $k;
        }
        return 'slug_' . sanitize_key((string) $k);
    }
}
