<?php

namespace LoftyIDX\includes\common;
use LoftyIDX\includes\LoftyIDX;
defined('ABSPATH') || exit;

class LoftyIDXApiCache
{
    /**
     * @var string[]
     */
    private static $cacheApi = [
        'seo/original-param',
        'listing/mls-info',
        'admin/common/page/router',
        'search/center/conditions',
        'search/centerPoint',
        'listing-crm/here-api/systemSettings',
        'admin/listing-search/searchCondition/init-info',
    ];

    public static function clearAllCache()
    {
       try{
        foreach (self::$cacheApi as $path) {
            self::deleteApiCacheData($path);
        }

        // if the api key is set, clear the cache
        $settings = get_option('lofty_idx_settings');
        if (empty($settings) || !isset($settings['lofty_idx_api_key'])) {
            return ;
        }
        $forwarder = LoftyIDX::get_instance()->services['proxy'];
        $forwarder->post_data('/token/active-plugin/clearCache',[
            "apiKey" =>  $settings['lofty_idx_api_key']
        ]);
       }catch(\Exception $e){
        error_log($e->getMessage());
       }
    }

    public static function setApiCacheData($path, $data, $method = 'GET', $params = [], $expiration = 3600)
    {
        if(LOFTY_IS_DEV){
            return false;
        }
        if (in_array($path, self::$cacheApi)) {
            $cache_key = self::getCacheKey($path, $method, $params);
            set_transient($cache_key, $data, $expiration);
        }
    }

    public static function getApiCacheData($path, $method = 'GET', $params = [])
    {   
        if(LOFTY_IS_DEV){
            return false;
        }
        if (in_array($path, self::$cacheApi)) {
            $cache_key = self::getCacheKey($path, $method, $params);
            return get_transient($cache_key);
        }
        return false;
    }

    public static function deleteApiCacheData($path, $method = null, $params = null)
    {
        if ($method === null && $params === null) {
            // 删除该路径下所有缓存
            self::deleteApiCacheByPath($path);
        } else {
            $cache_key = self::getCacheKey($path, $method ?? 'GET', $params ?? []);
            delete_transient($cache_key);
        }
    }

    /**
     * 删除指定路径的所有缓存（不管请求方法和参数）
     */
    private static function deleteApiCacheByPath($path)
    {
        global $wpdb;
        $path_prefix = self::getPathPrefix($path);
        
        // WordPress transients 存储在 options 表中
        // transient 的 option_name 格式为 _transient_xxx 或 _transient_timeout_xxx
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
                '_transient_' . $path_prefix . '%',
                '_transient_timeout_' . $path_prefix . '%'
            )
        );
    }

    private static function getPathPrefix($path)
    {
        return 'lofty_api_' . md5($path) . '_';
    }

    private static function getCacheKey($path, $method = 'GET', $params = [])
    {
        $key_data = [
            'method' => strtoupper($method),
            'params' => $params
        ];
        return self::getPathPrefix($path) . md5(json_encode($key_data));
    }
}
