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

class Dori_Chatbot_Admin_UI_API
{
    private static function is_rate_limit_message($error_message)
    {
        $message = strtolower((string) $error_message);

        return strpos($message, 'rate limit') !== false
            || strpos($message, 'too many requests') !== false
            || strpos($message, 'retry later') !== false
            || strpos($message, '429') !== false
            || strpos((string) $error_message, 'درخواست') !== false;
    }

    private static function extract_retry_after_seconds($error_message, $default_retry_after = 60)
    {
        $normalized = strtr((string) $error_message, array(
            '۰' => '0',
            '۱' => '1',
            '۲' => '2',
            '۳' => '3',
            '۴' => '4',
            '۵' => '5',
            '۶' => '6',
            '۷' => '7',
            '۸' => '8',
            '۹' => '9',
        ));

        $retry_after = (int) $default_retry_after;

        if (preg_match('/retry[_\\s-]?after[=:]?\\s*(\\d+)/iu', $normalized, $matches)) {
            $retry_after = (int) $matches[1];
        } elseif (preg_match('/(\\d+)\\s*(?:minute|minutes|دقیقه)/iu', $normalized, $matches)) {
            $retry_after = (int) $matches[1] * 60;
        } elseif (preg_match('/(\\d+)\\s*(?:second|seconds|sec|secs|ثانیه)/iu', $normalized, $matches)) {
            $retry_after = (int) $matches[1];
        }

        if ($retry_after < 1) {
            $retry_after = 1;
        }

        if ($retry_after > 600) {
            $retry_after = 600;
        }

        return $retry_after;
    }

    private static function build_rate_limit_error($source, $error_message, $subject = '')
    {
        $retry_after = self::extract_retry_after_seconds($error_message, 60);
        $message = 'درخواست‌های زیادی ارسال شده. لطفاً ' . $retry_after . ' ثانیه دیگر تلاش کنید.';

        Dori_Chatbot_Logger::debug(
                'Auth rate limit: source=' . sanitize_text_field($source)
                . ', retry_after=' . $retry_after
                . (!empty($subject) ? ', subject=' . sanitize_text_field($subject) : '')
                . ', raw_error=' . sanitize_text_field((string) $error_message)
        );

        return new WP_Error('RATE_LIMIT', $message, array(
            'status' => 429,
            'retry_after' => $retry_after,
        ));
    }

    public static function init()
    {
        add_action('rest_api_init', array(__CLASS__, 'register_routes'));
    }

    public static function register_routes()
    {
        $admin_namespace = 'dori/v1';

        register_rest_route($admin_namespace, '/connect-store', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_connect_store'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/auth/register', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_register'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/auth/verify-sms', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_verify_sms'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/auth/resend-sms', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_resend_sms'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/auth/activate-trial', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_activate_trial'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/auth/get-integration-id', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_integration_id'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/auth/extract-status', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_extract_status'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/status', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_status'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/settings', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_settings'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/reset-connection', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_reset_connection'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/start-crawl', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_start_crawl'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/crawl-status', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_crawl_status'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/create-bot', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_create_bot'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/bot-status', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_bot_status'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/onboarding-status', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_onboarding_status'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/complete-onboarding', array(
            'methods' => 'POST',
            'callback' => array(__CLASS__, 'handle_complete_onboarding'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));

        register_rest_route($admin_namespace, '/usage-stats', array(
            'methods' => 'GET',
            'callback' => array(__CLASS__, 'handle_get_usage_stats'),
            'permission_callback' => array(__CLASS__, 'check_admin_permission'),
        ));
    }

    public static function check_admin_permission()
    {
        return current_user_can('manage_options');
    }

    public static function handle_connect_store($request)
    {
        $params = $request->get_json_params();
        $integrate_string = isset($params['integrationId']) ? sanitize_text_field($params['integrationId']) : '';

        try {
            if (!class_exists('WooCommerce')) {
                throw new Exception('WooCommerce is required for this plugin.');
            }

            $result = Dori_Chatbot_Settings_Service::connect_store($integrate_string);
            return rest_ensure_response(array(
                'success' => true,
                'data' => $result,
            ));
        } catch (Exception $e) {
            return new WP_Error('connection_failed', $e->getMessage(), array('status' => 400));
        }
    }

    public static function handle_register($request)
    {
        $params = $request->get_json_params();
        $email = isset($params['email']) ? sanitize_email($params['email']) : '';
        $password = isset($params['password']) ? $params['password'] : '';
        $phone = isset($params['phoneNumber']) ? sanitize_text_field($params['phoneNumber']) : '';
        $website_url = isset($params['websiteUrl']) ? esc_url_raw($params['websiteUrl']) : get_site_url();
        $platform = isset($params['platformSelection']) ? sanitize_text_field($params['platformSelection']) : 'wordpress';
        $how_find_us = isset($params['howFindUs']) ? sanitize_text_field($params['howFindUs']) : '';

        if (!is_email($email)) {
            return new WP_Error('INVALID_EMAIL', 'فرمت ایمیل نامعتبر است.', array('status' => 400));
        }
        if (strlen($password) < 8 || !preg_match('/[A-Za-z]/', $password) || !preg_match('/[0-9]/', $password)) {
            return new WP_Error('WEAK_PASSWORD', 'رمز عبور باید حداقل ۸ کاراکتر و شامل حروف و اعداد باشد.', array('status' => 400));
        }
        if (!preg_match('/^09[0-9]{9}$/', $phone)) {
            return new WP_Error('INVALID_PHONE_NUMBER', 'شماره تلفن باید با ۰۹ شروع شود و ۱۱ رقم باشد.', array('status' => 400));
        }

        try {
            $result = Dori_Chatbot_Mori_Style_Client::register($email, $password, $phone, $website_url, $platform, $how_find_us);

            $user_id = isset($result['userId']) ? $result['userId'] : '';

            if (empty($user_id)) {
                return new WP_Error('registration_failed', 'خطا در ثبت نام.', array('status' => 400));
            }

            update_option('dori-chatbot-temp-user-id', $user_id);

            return rest_ensure_response(array(
                'success' => true,
                'userId' => $user_id,
            ));
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            $error_code = 'registration_failed';

            if (strpos($error_message, 'Email already exists') !== false || strpos($error_message, 'EMAIL_ALREADY_IN_USE') !== false) {
                $error_code = 'EMAIL_ALREADY_IN_USE';
                $error_message = 'این ایمیل قبلاً ثبت شده است.';
            } elseif (strpos($error_message, 'Phone already exists') !== false || strpos($error_message, 'PHONE_ALREADY_IN_USE') !== false) {
                $error_code = 'PHONE_ALREADY_IN_USE';
                $error_message = 'این شماره تلفن قبلاً ثبت شده است.';
            } elseif (self::is_rate_limit_message($error_message)) {
                return self::build_rate_limit_error('register', $error_message, $phone);
            }

            return new WP_Error($error_code, $error_message, array('status' => 400));
        }
    }

    public static function handle_verify_sms($request)
    {
        $params = $request->get_json_params();
        $user_id = isset($params['userId']) ? sanitize_text_field($params['userId']) : get_option('dori-chatbot-temp-user-id');
        $code = isset($params['code']) ? sanitize_text_field($params['code']) : '';

        if (empty($user_id)) {
            return new WP_Error('USER_NOT_FOUND', 'شناسه کاربر یافت نشد.', array('status' => 404));
        }

        try {
            $result = Dori_Chatbot_Mori_Style_Client::verify_sms($user_id, $code);

            return rest_ensure_response(array('success' => true));
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            $error_code = 'verification_failed';

            if (strpos($error_message, 'Invalid verification code') !== false || strpos($error_message, 'INVALID_VERIFICATION_CODE') !== false) {
                $error_code = 'INVALID_VERIFICATION_CODE';
                $error_message = 'کد تأیید نامعتبر است.';
            } elseif (strpos($error_message, 'Code expired') !== false || strpos($error_message, 'VERIFICATION_CODE_EXPIRED') !== false) {
                $error_code = 'VERIFICATION_CODE_EXPIRED';
                $error_message = 'کد تأیید منقضی شده است.';
            } elseif (strpos($error_message, 'User not found') !== false || strpos($error_message, 'USER_NOT_FOUND') !== false) {
                $error_code = 'USER_NOT_FOUND';
                $error_message = 'شناسه کاربر یافت نشد.';
            } elseif (self::is_rate_limit_message($error_message)) {
                return self::build_rate_limit_error('verify_sms', $error_message, $user_id);
            }

            return new WP_Error($error_code, $error_message, array('status' => 400));
        }
    }

    public static function handle_resend_sms($request)
    {
        $params = $request->get_json_params();
        $user_id = isset($params['userId']) ? sanitize_text_field($params['userId']) : get_option('dori-chatbot-temp-user-id');

        if (empty($user_id)) {
            return new WP_Error('USER_NOT_FOUND', 'شناسه کاربر یافت نشد.', array('status' => 404));
        }

        try {
            $result = Dori_Chatbot_Mori_Style_Client::resend_sms($user_id);

            return rest_ensure_response(array('success' => true));
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            $error_code = 'resend_failed';

            if (strpos($error_message, 'User not found') !== false || strpos($error_message, 'USER_NOT_FOUND') !== false) {
                $error_code = 'USER_NOT_FOUND';
                $error_message = 'شناسه کاربر یافت نشد.';
            } elseif (self::is_rate_limit_message($error_message)) {
                return self::build_rate_limit_error('resend_sms', $error_message, $user_id);
            }

            return new WP_Error($error_code, $error_message, array('status' => 400));
        }
    }

    public static function handle_activate_trial($request)
    {
        $params = $request->get_json_params();
        $user_id = isset($params['userId']) ? sanitize_text_field($params['userId']) : get_option('dori-chatbot-temp-user-id');

        if (empty($user_id)) {
            return new WP_Error('USER_NOT_FOUND', 'شناسه کاربر یافت نشد.', array('status' => 404));
        }

        try {
            $result = Dori_Chatbot_Mori_Style_Client::activate_trial($user_id);

            $platform = isset($result['data']['platformSelection']) ? $result['data']['platformSelection'] : 'wordpress';

            if ($platform !== 'manual' && $platform !== 'wordpress') {
                try {
                    Dori_Chatbot_Gollum_Client::trigger_crawl($user_id);
                } catch (Exception $e) {
                    Dori_Chatbot_Logger::log('Crawler Trigger Error: ' . $e->getMessage());
                }
            }

            return rest_ensure_response(array(
                'success' => true,
                'data' => $result,
            ));
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            $error_code = 'trial_activation_failed';

            if (strpos($error_message, 'User not found') !== false || strpos($error_message, 'USER_NOT_FOUND') !== false) {
                $error_code = 'USER_NOT_FOUND';
                $error_message = 'شناسه کاربر یافت نشد.';
            }

            return new WP_Error($error_code, $error_message, array('status' => 400));
        }
    }

    public static function handle_get_integration_id($request)
    {
        $user_id = $request->get_param('userId');
        if (empty($user_id)) {
            $user_id = get_option('dori-chatbot-temp-user-id');
        }

        if (empty($user_id)) {
            return new WP_Error('USER_NOT_FOUND', 'شناسه کاربر یافت نشد.', array('status' => 404));
        }

        try {
            $result = Dori_Chatbot_Mori_Style_Client::get_integration_id($user_id);

            $integrate_id = '';
            if (isset($result['data']['integrate_id'])) {
                $integrate_id = $result['data']['integrate_id'];
            } elseif (isset($result['integrate_id'])) {
                $integrate_id = $result['integrate_id'];
            }

            return rest_ensure_response(array(
                'success' => true,
                'data' => array(
                    'integrate_id' => $integrate_id
                ),
            ));
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            $error_code = 'get_integration_id_failed';

            if (strpos($error_message, 'User not found') !== false || strpos($error_message, 'USER_NOT_FOUND') !== false) {
                $error_code = 'USER_NOT_FOUND';
                $error_message = 'شناسه کاربر یافت نشد.';
            }

            return new WP_Error($error_code, $error_message, array('status' => 400));
        }
    }

    public static function handle_extract_status($request)
    {
        $params = $request->get_json_params();
        $user_id = isset($params['userId']) ? sanitize_text_field($params['userId']) : get_option('dori-chatbot-temp-user-id');
        $save_empty_bot = isset($params['saveEmptyBot']) ? (bool) $params['saveEmptyBot'] : true;

        if (empty($user_id)) {
            return new WP_Error('USER_NOT_FOUND', 'شناسه کاربر یافت نشد.', array('status' => 404));
        }

        try {
            $result = Dori_Chatbot_Mori_Style_Client::extract_status($user_id, $save_empty_bot);

            $extracted_data = array(
                'shop' => array(
                    'currency' => 'IRT',
                    'language' => 'Persian',
                    'isRTL' => true,
                    'country' => 'iran',
                    'onboarding_completed' => false,
                ),
                'crawler_info' => array(
                    'website_url' => isset($result['websiteUrl']) ? $result['websiteUrl'] : get_site_url(),
                    'platform' => 'wordpress',
                ),
                'faqs' => array(),
                'platform' => 'wordpress',
            );

            set_transient('dori-chatbot-extract-response-data', $extracted_data, HOUR_IN_SECONDS);

            try {
                Dori_Chatbot_Bot_Creator::create_bot($user_id, true);
            } catch (Exception $e) {
                Dori_Chatbot_Logger::debug('Bot creation error: ' . $e->getMessage());
                if (strpos($e->getMessage(), 'User already exists') !== false) {
                    Dori_Chatbot_Logger::debug("Bot creation: User already exists for {$user_id}");
                } else {
                    throw new Exception('MIGRATION_FAILED: ' . $e->getMessage());
                }
            }
            
            return rest_ensure_response(array(
                'success' => true,
            ));
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            $error_code = 'extraction_failed';
            Dori_Chatbot_Logger::debug('Extraction failed: ' . $e->getMessage());

            if (strpos($error_message, 'MIGRATION_FAILED') !== false) {
                $error_code = 'MIGRATION_FAILED';
                $error_message = 'ایجاد ربات با خطا مواجه شد.';
            } elseif (strpos($error_message, 'User not found') !== false || strpos($error_message, 'USER_NOT_FOUND') !== false) {
                $error_code = 'USER_NOT_FOUND';
                $error_message = 'شناسه کاربر یافت نشد.';
            }

            return new WP_Error($error_code, $error_message, array('status' => 400));
        }
    }

    public static function handle_get_status()
    {
        $is_connected = false;
        $woocommerce_version = null;

        try {
            if (class_exists('WooCommerce')) {
                $woocommerce_version = WC()->version;

                if (class_exists('Dori_Chatbot_WooCommerce_Integration')) {
                    $is_connected = Dori_Chatbot_WooCommerce_Integration::is_store_fully_connected();
                }
            }
        } catch (Exception $e) {
            Dori_Chatbot_Logger::log('Error checking WooCommerce status in handle_get_status: ' . $e->getMessage());
        }

        return rest_ensure_response(array(
            'success' => true,
            'isConnected' => $is_connected,
            'siteUrl' => get_site_url(),
            'woocommerceVersion' => $woocommerce_version,
        ));
    }

    public static function handle_get_settings()
    {
        return rest_ensure_response(array(
            'success' => true,
            'settings' => array(
                'integrationId' => get_option('dori-chatbot-integrate', ''),
                'sharingId' => get_option('dori-chatbot-sharing-id', ''),
                'clientId' => get_option('dori-chatbot-client-id', ''),
            ),
        ));
    }

    public static function handle_reset_connection()
    {
        delete_option('dori-chatbot-client-id');
        delete_option('dori-chatbot-client-secret');
        delete_option('dori-chatbot-integrate');
        delete_option('dori-chatbot-sharing-id');
        delete_option('dori-chatbot-onboarding-completed');

        if (class_exists('Dori_Chatbot_Cache_Manager')) {
            Dori_Chatbot_Cache_Manager::clear_all_caches();
        }

        return rest_ensure_response(array('success' => true));
    }

    public static function handle_start_crawl()
    {
        try {
            $user_id = Dori_Chatbot_API_Client::get_user_id();
            Dori_Chatbot_Crawler_Service::start_crawl($user_id);
            return rest_ensure_response(array('success' => true));
        } catch (Exception $e) {
            return new WP_Error('crawl_failed', $e->getMessage(), array('status' => 400));
        }
    }

    public static function handle_get_crawl_status()
    {
        try {
            $user_id = Dori_Chatbot_API_Client::get_user_id();
            $status = Dori_Chatbot_Crawler_Service::get_crawl_status($user_id);
            return rest_ensure_response(array('success' => true, 'data' => $status));
        } catch (Exception $e) {
            return new WP_Error('status_failed', $e->getMessage(), array('status' => 400));
        }
    }

    public static function handle_create_bot()
    {
        try {
            $user_id = Dori_Chatbot_API_Client::get_user_id();
            set_transient('dori-chatbot-bot-creation-retries', 0, HOUR_IN_SECONDS);
            set_transient('dori-chatbot-bot-creation-status', 'not-sent-yet', HOUR_IN_SECONDS);
            Dori_Chatbot_Bot_Creator::create_bot($user_id);
            return rest_ensure_response(array('success' => true));
        } catch (Exception $e) {
            return new WP_Error('bot_creation_failed', $e->getMessage(), array('status' => 400));
        }
    }

    public static function handle_get_bot_status()
    {
        try {
            $user_id = Dori_Chatbot_API_Client::get_user_id();
            $status = Dori_Chatbot_Bot_Creator::get_seller_health_check($user_id);
            return rest_ensure_response(array('success' => true, 'data' => $status));
        } catch (Exception $e) {
            return new WP_Error('status_failed', $e->getMessage(), array('status' => 400));
        }
    }

    public static function handle_get_onboarding_status()
    {
        return rest_ensure_response(array(
            'success' => true,
            'data' => array(
                'completed' => get_option('dori-chatbot-onboarding-completed', false)
            )
        ));
    }

    public static function handle_complete_onboarding($request)
    {
        $params = $request->get_json_params();
        $phone = isset($params['phoneNumber']) ? sanitize_text_field($params['phoneNumber']) : '';
        
        if (!empty($phone)) {
            update_option('dori-chatbot-user-phone', $phone);
        }
        
        update_option('dori-chatbot-onboarding-completed', true);
        
        return rest_ensure_response(array('success' => true));
    }

    public static function handle_get_usage_stats()
    {
        try {
            $user_id = Dori_Chatbot_API_Client::get_user_id();
            $stats = Dori_Chatbot_Standard_API_Client::get_aggregate_statistics($user_id);
            
            return rest_ensure_response(array(
                'success' => true,
                'data' => array(
                    'data' => $stats
                )
            ));
        } catch (Exception $e) {
            return new WP_Error('usage_stats_failed', $e->getMessage(), array('status' => 400));
        }
    }
}
