<?php
/**
 * API Communication
 *
 * @package ReplyIt_Chat_Widget
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

class ReplyIt_API {

    /**
     * Single instance
     */
    private static $instance = null;

    /**
     * Get instance
     */
    public static function instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        // Future: Add any API-related hooks here
    }

    /**
     * Make API request
     */
    private static function make_request($endpoint, $method = 'GET', $data = null, $widget_id = null, $api_secret = null) {
        $config = ReplyIt_Core::get_config();

        $widget_id = $widget_id ?? $config['widget_id'];
        $api_secret = $api_secret ?? $config['api_secret'];
        $api_url = $config['api_url'];

        $url = trailingslashit($api_url) . 'api/' . ltrim($endpoint, '/');

        $args = [
            'method' => $method,
            'headers' => [
                'Content-Type' => 'application/json',
                'X-Widget-Secret' => $api_secret,
            ],
            'timeout' => 15,
        ];

        if ($data && in_array($method, ['POST', 'PUT', 'PATCH'])) {
            $args['body'] = wp_json_encode($data);
        }

        $response = wp_remote_request($url, $args);

        if (is_wp_error($response)) {
            return [
                'success' => false,
                'message' => $response->get_error_message()
            ];
        }

        $body = wp_remote_retrieve_body($response);
        $decoded = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return [
                'success' => false,
                'message' => 'Invalid JSON response'
            ];
        }

        return $decoded;
    }

    /**
     * Add domain to allowed list
     */
    public static function add_domain($widget_id, $api_secret, $domain) {
        return self::make_request(
            "widgets/{$widget_id}/add-domain",
            'POST',
            ['domain' => $domain],
            $widget_id,
            $api_secret
        );
    }

    /**
     * Send context to API
     */
    public static function send_context($session_id, $context) {
        $config = ReplyIt_Core::get_config();

        return self::make_request(
            "widgets/{$config['widget_id']}/context",
            'POST',
            [
                'session_id' => $session_id,
                'context' => $context
            ]
        );
    }

    /**
     * Get order status (for AI agent tools)
     */
    public static function get_order_status($order_id) {
        $config = ReplyIt_Core::get_config();

        return self::make_request(
            "widgets/{$config['widget_id']}/tools/order-status",
            'POST',
            ['order_id' => $order_id]
        );
    }

    /**
     * Update WooCommerce settings on backend
     */
    public static function update_woocommerce_settings($settings = null) {
        $config = ReplyIt_Core::get_config();

        if (empty($config['widget_id']) || empty($config['api_secret'])) {
            return [
                'success' => false,
                'message' => 'Widget not configured'
            ];
        }

        // If no settings provided, get from WordPress options
        if ($settings === null) {
            $settings = [
                'enabled' => (bool) get_option('replyit_woocommerce_enabled', false),
                'order_tracking_enabled' => (bool) get_option('replyit_order_tracking_enabled', true),
                'product_search_enabled' => (bool) get_option('replyit_product_search_enabled', true),
                'cart_abandon_time' => (int) get_option('replyit_cart_abandon_time', 3),
                'product_page_delay' => (int) get_option('replyit_product_page_delay', 20),
                'checkout_help_enabled' => (bool) get_option('replyit_checkout_help_enabled', true),
            ];
        }

        $response = self::make_request(
            "widgets/{$config['widget_id']}/settings/woocommerce",
            'POST',
            $settings
        );

        if (isset($response['success']) && $response['success']) {
            error_log('ReplyIt: WooCommerce settings synced successfully');
        } else {
            error_log('ReplyIt: Failed to sync WooCommerce settings - ' . ($response['message'] ?? 'Unknown error'));
        }

        return $response;
    }

    /**
     * Get default WooCommerce settings
     */
    public static function get_default_woocommerce_settings() {
        return [
            'enabled' => true,
            'order_tracking_enabled' => true,
            'cart_abandon_time' => 3,
            'product_page_delay' => 20,
            'checkout_help_enabled' => true,
        ];
    }

    /**
     * Update Blog settings on backend
     */
    public static function update_blog_settings($settings = null) {
        $config = ReplyIt_Core::get_config();

        if (empty($config['widget_id']) || empty($config['api_secret'])) {
            return [
                'success' => false,
                'message' => 'Widget not configured'
            ];
        }

        // If no settings provided, get from WordPress options
        if ($settings === null) {
            $settings = [
                'blog_search_enabled' => (bool) get_option('replyit_blog_search_enabled', true),
                'blog_content_enabled' => (bool) get_option('replyit_blog_content_enabled', true),
            ];
        }

        $response = self::make_request(
            "widgets/{$config['widget_id']}/settings/blog",
            'POST',
            $settings
        );

        if (isset($response['success']) && $response['success']) {
            error_log('ReplyIt: Blog settings synced successfully');
        } else {
            error_log('ReplyIt: Failed to sync blog settings - ' . ($response['message'] ?? 'Unknown error'));
        }

        return $response;
    }
}
