<?php

namespace EstatebudConnect\Core;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Traits\Singleton;

class Cache
{
    use Singleton;

    const TTL_1M = 1;
    const TTL_5M = 5;
    const TTL_10M = 10;
    const TTL_30M = 30;
    const TTL_1H = 1 * 60 * 60;
    const TTL_2H = 2 * 60 * 60;
    const TTL_1D = 1 * 24 * 60 * 60;
    const TTL_1MO = 30 * 24 * 60 * 60;

    private $prefix = 'estatebud_cache_';

    private function get_cache_key($name)
    {
        return $this->prefix . $name;
    }

    public function get($name)
    {
        $cache_key = $this->get_cache_key($name);
        return get_transient($cache_key);
    }

    public function set($name, $value, $duration)
    {
        $cache_key = $this->get_cache_key($name);

        Log::write("Cache: Storing data with key {$cache_key} for {$duration} seconds");

        return set_transient($cache_key, $value, $duration);
    }

    public function delete($name)
    {
        $cache_key = $this->get_cache_key($name);
        return delete_transient($cache_key);
    }

    public function flush()
    {
        global $wpdb;
        $deleted = 0;

        $items = $wpdb->get_col(
            $wpdb->prepare(
                "SELECT option_name FROM {$wpdb->options}
                WHERE option_name LIKE %s",
                '_transient_' . $this->prefix . '%',
            ),
        );

        foreach ($items as $item) {
            $cache_key = str_replace('_transient_', '', $item);
            if (delete_transient($cache_key)) {
                $deleted++;
            }
        }

        return $deleted;
    }
}
