<?php
namespace AI_BotKit\Integration;

use WP_Error;

class API_Handler {
    private $API_URL;

    public function __construct() {
        global $ai_botkit_url;
        $this->API_URL = $ai_botkit_url . '/api/saas/';
        
        // Initialize post sync hooks
        $this->init_post_sync_hooks();
    }

    /**
     * Get the access token from options.
     *
     * @return string|false The access token or false if not found.
     */
    private function get_access_token() {
        return get_option('ai_botkit_saas_connect_token');
    }

    /**
     * Send get request to the API
     */
    public function send_get_request(string $endpoint, array $options = []): array {
        $access_token = $this->get_access_token();
        if (empty($access_token)) {
            return ['error' => 'Access token is not set.'];
        }

        $url = $this->API_URL . $endpoint;
        $params['headers'] = [
            'Content-Type' => 'application/json',
        ];
        $params['timeout'] = 100;
        $options['access_token'] = $access_token;
        $url = add_query_arg($options, $url);
        $response = wp_remote_get($url, $params);

        if (is_wp_error($response)) {
            return ['error' => $response->get_error_message()];
        }

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

        return is_array($data) ? $data : ['error' => 'Invalid API response.', 'response_body' => $body];
    }

    /**
     * Send post request to the API
     */
    public function send_post_request(string $endpoint, array $options = []): array {
        $access_token = $this->get_access_token();
        if (empty($access_token)) {
            return ['error' => 'Access token is not set.'];
        }

        $url = $this->API_URL . $endpoint;
        $params['headers'] = [
            'Content-Type' => 'application/json',
        ];
        $options['access_token'] = $access_token;
        $params['body'] = json_encode($options);
        
        $response = wp_remote_post($url, $params);

        if (is_wp_error($response)) {
            return ['error' => $response->get_error_message()];
        }

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

        return is_array($data) ? $data : ['error' => 'Invalid API response.', 'response_body' => $body];
    }

    /**
     * Initialize post sync hooks
     */
    private function init_post_sync_hooks(): void {
        // Hook into post update events
        add_action('save_post', [$this, 'handle_post_sync'], 10, 3);
        add_action('delete_post', [$this, 'handle_post_delete_sync'], 10, 2);
    }

    /**
     * Handle post sync when posts are updated
     */
    public function handle_post_sync(int $post_id, \WP_Post $post, bool $update): void {
        // Skip autosaves and revisions
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return;
        }

        // Check if post sync is enabled for this post type
        $sync_settings = get_option('ai_botkit_post_sync_settings', []);
        if (empty($sync_settings['enabled_post_types']) || !in_array($post->post_type, $sync_settings['enabled_post_types'])) {
            return;
        }

        // Only sync published posts
        if ($post->post_status !== 'publish') {
            return;
        }

        // Sync the post content
        $this->sync_post_content($post_id, $post);
    }

    /**
     * Handle post delete sync
     */
    public function handle_post_delete_sync(int $post_id, \WP_Post $post): void {
        // Check if post sync is enabled for this post type
        $sync_settings = get_option('ai_botkit_post_sync_settings', []);
        if (empty($sync_settings['enabled_post_types']) || !in_array($post->post_type, $sync_settings['enabled_post_types'])) {
            return;
        }

        // Notify SaaS about post deletion
        $this->sync_post_content($post_id, $post, 'delete');
    }

    /**
     * Sync post content to SaaS platform
     */
    private function sync_post_content(int $post_id, \WP_Post $post, string $action = 'sync'): void {
        global $ai_botkit_url;
        
        $access_token = $this->get_access_token();
        if (empty($access_token)) {
            return;
        }

        // Prepare post data
        $post_data = [
            'postId' => $post_id,
            'postTitle' => $post->post_title,
            'postContent' => $post->post_content,
            'postExcerpt' => $post->post_excerpt,
            'action' => $action,
            'authToken' => $access_token
        ];

        // Enrich post content via filter (allows third-party plugins to append metadata)
        $enriched_content = apply_filters( 'ai_botkit_enrich_post_content', $post->post_content, $post_id, $post->post_type );
        $post_data['postContent'] = $enriched_content;

        // For backward compatibility: if a plugin previously sent structured metadata,
        // remove those legacy keys so the SaaS receives clean enriched text only.
        unset( $post_data['postType'], $post_data['productPrice'], $post_data['productCategories'], $post_data['productTags'] );

        // Send to SaaS sync endpoint
        $url = $ai_botkit_url . '/api/wordpress/sync-content/';
        
        $response = wp_remote_post($url, [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($post_data),
            'timeout' => 30
        ]);

        error_log(print_r($response, true));

        // Log errors if any
        if (is_wp_error($response)) {
            error_log('AI BotKit Post Sync Error: ' . $response->get_error_message());
        } else {
            $response_code = wp_remote_retrieve_response_code($response);
            if ($response_code !== 200) {
                error_log('AI BotKit Post Sync Error: HTTP ' . $response_code);
            }
        }
    }

    /**
     * Get enabled post types for sync
     */
    public static function get_enabled_post_types(): array {
        $sync_settings = get_option('ai_botkit_post_sync_settings', []);
        return $sync_settings['enabled_post_types'] ?? [];
    }

    /**
     * Save post sync settings
     */
    public static function save_sync_settings(array $settings): bool {
        return update_option('ai_botkit_post_sync_settings', $settings);
    }

    /**
     * Get all available post types
     */
    public static function get_available_post_types(): array {
        $post_types = get_post_types(['public' => true], 'objects');
        $formatted_types = [];

        foreach ($post_types as $post_type) {
            $formatted_types[] = [
                'name' => $post_type->name,
                'label' => $post_type->label,
                'description' => $post_type->description ?? ''
            ];
        }

        return $formatted_types;
    }
}