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

class Dori_Chatbot_WooCommerce_API_Keys
{
    public static function init()
    {
    }

    public static function get_and_test_keys($bypass_cache = false, $skip_api_test = true)
    {
        if (!class_exists('WooCommerce')) {
            return false;
        }

        if ($bypass_cache) {
            $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)) {
                return false;
            }

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

            $keys = array(
                'consumer_key' => $consumer_key,
                'consumer_secret' => $consumer_secret,
                'description' => 'Fresh WooCommerce API Keys from database'
            );

            return $keys;
        }

        return Dori_Chatbot_Cache_Manager::get_woocommerce_api_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 generate_keys()
    {
        global $wpdb;

        delete_option('dori-chatbot-wc-consumer-key');
        delete_option('dori-chatbot-wc-consumer-secret');

        $consumer_key = 'ck_' . wp_generate_password(40, false);
        $consumer_secret = 'cs_' . wp_generate_password(40, false);

        $table_name = $wpdb->prefix . 'woocommerce_api_keys';

        $result = $wpdb->insert(
            $table_name,
            array(
                'user_id' => get_current_user_id(),
                'description' => 'Mori Chatbot Auto Generated Keys - ' . gmdate('Y-m-d H:i:s'),
                'permissions' => 'read_write',
                'consumer_key' => wc_api_hash($consumer_key),
                'consumer_secret' => $consumer_secret,
                'nonces' => '',
                'truncated_key' => substr($consumer_key, -7),
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s', '%s')
        );

        if ($result === false) {
            throw new Exception('ذخیره کلیدهای API ووکامرس در پایگاه داده ناموفق بود');
        }

        update_option('dori-chatbot-wc-consumer-key', $consumer_key);
        update_option('dori-chatbot-wc-consumer-secret', $consumer_secret);

        return array(
            'consumer_key' => $consumer_key,
            'consumer_secret' => $consumer_secret
        );
    }
}
