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

class Dori_Chatbot_Settings_Service
{
    public static function init()
    {
    }

    public static function send_keys_to_server($keys)
    {
        $api_url = Dori_Chatbot_API_Constants::get_server_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_WOOCOMMERCE_INTEGRATE;

        $data = array(
            'consumer_key' => $keys['consumer_key'],
            'consumer_secret' => $keys['consumer_secret'],
            'site_url' => get_site_url(),
            'site_name' => get_bloginfo('name'),
            'woocommerce_version' => class_exists('WooCommerce') ? WC()->version : 'Not installed',
            'wp_version' => get_bloginfo('version'),
            'allow_order_tracking' => 1,
            'generated_at' => current_time('mysql')
        );

        $max_retries = 5;
        $retry_delay_ms = 400;
        $attempt = 0;
        $response = null;

        while (true) {
            $response = Dori_Chatbot_API_Client::call_api($api_url, $data, Dori_Chatbot_API_Client::get_timeout_long(), true);

            $should_retry = false;
            $status = 'transport_error';

            if (is_wp_error($response)) {
                $should_retry = true;
            } else {
                $response_code = wp_remote_retrieve_response_code($response);
                $status = 'http_' . $response_code;
                $should_retry = $response_code === 404 || ($response_code >= 500 && $response_code < 600);
            }

            if (!$should_retry || $attempt >= $max_retries) {
                break;
            }

            $attempt++;
            Dori_Chatbot_Logger::debug("Retrying connect_store integrate attempt {$attempt} ({$status})");
            usleep(($retry_delay_ms * $attempt) * 1000);
        }

        if (is_wp_error($response)) {
            throw new Exception('ارسال داده به سرور ناموفق بود: ' . esc_html($response->get_error_message()));
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if ($response_code !== 200) {
            throw new Exception('سرور با کد خطا پاسخ داد ' . esc_html($response_code) . ': ' . esc_html($response_body));
        }

        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);

        if (!isset($response_data['success']) || !$response_data['success']) {
            $error_msg = isset($response_data['message']) ? $response_data['message'] : 'Unknown error';
            throw new Exception('خطای سرور: ' . esc_html($error_msg));
        }

        if (isset($response_data['sharing_id'])) {
            update_option('dori-chatbot-sharing-id', $response_data['sharing_id']);
        } else {
            $existing_sharing_id = Dori_Chatbot_Cache_Manager::get_sharing_id();
            if (!empty($existing_sharing_id)) {
            } else {
                throw new Exception('سرور شناسه اشتراک‌گذاری را برنگرداند. لطفاً دوباره تلاش کنید یا با پشتیبانی تماس بگیرید.');
            }
        }
    }

    public static function connect_store($integrate_string)
    {
        if (empty($integrate_string)) {
            throw new Exception('Integration ID is required');
        }

        $parts = explode(',', $integrate_string);
        if (count($parts) !== 2) {
            throw new Exception('Invalid integration ID format. Expected format: client_id,client_secret');
        }

        $client_id = trim($parts[0]);
        $client_secret = trim($parts[1]);

        if (empty($client_id) || empty($client_secret)) {
            throw new Exception('Both client_id and client_secret are required');
        }

        update_option('dori-chatbot-client-id', $client_id);
        update_option('dori-chatbot-client-secret', $client_secret);
        update_option('dori-chatbot-integrate', $integrate_string);

        Dori_Chatbot_Cache_Manager::clear_all_caches();

        $existing_keys = Dori_Chatbot_WooCommerce_API_Keys::get_and_test_keys();
        $keys_to_send = null;
        $is_new_keys = false;

        if (!$existing_keys) {
            $keys_to_send = Dori_Chatbot_WooCommerce_API_Keys::generate_keys();
            $is_new_keys = true;
        } else {
            $keys_to_send = array(
                'consumer_key' => $existing_keys['consumer_key'],
                'consumer_secret' => $existing_keys['consumer_secret']
            );
        }

        self::send_keys_to_server($keys_to_send);

        $user_id = self::auto_start_crawling();
        if ($user_id) {
            Dori_Chatbot_Bot_Creator::extract_bot_data($user_id);
        }

        $final_sharing_id = get_option('dori-chatbot-sharing-id', '');

        $connection_verified = false;
        try {
            if (class_exists('Dori_Chatbot_WooCommerce_Integration')) {
                $connection_verified = Dori_Chatbot_WooCommerce_Integration::verify_store_connection_fresh();
            }
        } catch (Exception $e) {
            Dori_Chatbot_Logger::log('Error verifying connection in connect_store: ' . $e->getMessage());
        }

        return array(
            'is_new_keys' => $is_new_keys,
            'sharing_id' => $final_sharing_id,
            'connection_verified' => $connection_verified
        );
    }

    public static function auto_start_crawling()
    {
        try {
            $user_id = Dori_Chatbot_API_Client::get_user_id();
            Dori_Chatbot_Crawler_Service::start_crawl($user_id);

            return $user_id;

        } catch (Exception $e) {
            return null;
        }
    }
}
