<?php
if (!defined('ABSPATH'))
    exit;

class Dori_Chatbot_Cache_Manager
{
    private static $instance = null;

    private static $order_tracking_permission = null;
    private static $woocommerce_session = null;
    private static $current_product_id = null;

    private function __construct()
    {
    }

    public static function init()
    {
        add_action('update_option_dori_chatbot_allow_order_tracking', array(__CLASS__, 'clear_order_tracking_permission_cache'));

        add_action('transition_post_status', array(__CLASS__, 'clear_product_count_on_post_change'), 10, 3);

        add_action('save_post', array(__CLASS__, 'clear_product_id_cache'));
    }

    public static function clear_product_count_on_post_change($new_status, $old_status, $post)
    {
        if ($post->post_type === 'product') {
            self::clear_product_count_cache();
        }
    }

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public static function get_sharing_id()
    {
        return get_option('dori-chatbot-sharing-id', '');
    }

    public static function get_api_credentials()
    {
        return array(
            'client_id' => get_option('dori-chatbot-client-id', ''),
            'client_secret' => get_option('dori-chatbot-client-secret', ''),
        );
    }

    public static function get_order_tracking_permission()
    {
        return true;
    }

    public static function clear_order_tracking_permission_cache()
    {
        self::$order_tracking_permission = null;
    }

    public static function get_woocommerce_session()
    {
        if (!self::is_session_context_available()) {
            return null;
        }

        if (null === self::$woocommerce_session && class_exists('WooCommerce')) {
            $wc_available = function_exists('WC');
            $wc_session_available = $wc_available && WC()->session !== null;
            $is_rest_request = defined('REST_REQUEST') && REST_REQUEST;

            $wc_session = WC()->session;
            if ($wc_session) {
                $session_data = $wc_session->get_session_data();
                self::$woocommerce_session = array(
                    'session_id' => $wc_session->get_customer_id(),
                    'session_data' => $session_data,
                );
            }
        }
        return self::$woocommerce_session;
    }

    public static function is_session_context_available()
    {
        $is_rest_request = defined('REST_REQUEST') && REST_REQUEST;
        $is_admin = is_admin();
        return !$is_rest_request && !$is_admin;
    }

    public static function clear_woocommerce_session_cache()
    {
        self::$woocommerce_session = null;
    }

    public static function get_product_count()
    {
        $cache_key = 'dori_chatbot_product_count';
        $cached_count = get_transient($cache_key);

        if (false === $cached_count) {
            $cached_count = wp_count_posts('product')->publish;
            set_transient($cache_key, $cached_count, 15 * MINUTE_IN_SECONDS);
        }

        return $cached_count;
    }

    public static function clear_product_count_cache()
    {
        delete_transient('dori_chatbot_product_count');
    }

    public static function get_woocommerce_api_keys()
    {
        $consumer_key = get_option('dori-chatbot-wc-consumer-key');
        $consumer_secret = get_option('dori-chatbot-wc-consumer-secret');

        if (!empty($consumer_key) && !empty($consumer_secret)) {
            $existing_keys = array(
                'consumer_key' => $consumer_key,
                'consumer_secret' => $consumer_secret,
                'description' => 'Original WooCommerce API Keys from wp_options'
            );
        } else {
            return false;
        }

        if (!self::validate_keys_in_database($consumer_key, $consumer_secret)) {
            return false;
        }

        return $existing_keys;
    }

    private static function validate_keys_in_database($consumer_key, $consumer_secret)
    {
        global $wpdb;

        if (!preg_match('/^ck_/', $consumer_key)) {
            return false;
        }

        if (!preg_match('/^cs_/', $consumer_secret)) {
            return false;
        }

        $key_length_valid = strlen($consumer_key) >= 43 && strlen($consumer_secret) >= 43;
        if (!$key_length_valid) {
            return false;
        }

        $truncated_key = substr($consumer_key, -7);
        $table_name = $wpdb->prefix . 'woocommerce_api_keys';

        $result = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table_name} WHERE truncated_key = %s",
            $truncated_key
        ));

        if ($result === null || $result == 0) {
            return false;
        }

        return true;
    }

    public static function get_current_product_id()
    {
        if (null !== self::$current_product_id) {
            return self::$current_product_id;
        }

        if (function_exists('is_product') && is_product()) {
            self::$current_product_id = get_the_ID();
            return self::$current_product_id;
        }

        if (is_single() || is_page()) {
            self::$current_product_id = get_the_ID();
            return self::$current_product_id;
        }

        self::$current_product_id = false;
        return false;
    }

    public static function clear_product_id_cache()
    {
        self::$current_product_id = null;
    }

    public static function clear_all_caches()
    {
        self::clear_order_tracking_permission_cache();
        self::clear_woocommerce_session_cache();
        self::clear_product_count_cache();
        self::clear_product_id_cache();

    }
}
