<?php

class EveAI_Post_Handler {
    private $api;

    public function __construct($api) {
        $this->api = $api;
    }

    public function handle_post_save($post_id, $post, $update) {
        // Verify if this is not an auto save routine.
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

        // Check if this is a revision
        if (wp_is_post_revision($post_id)) return;

        // Check if post type is one we want to sync
        if (!in_array($post->post_type, ['post', 'page'])) return;

        // Check if post status is published
        if ($post->post_status != 'publish') return;

        // Verify nonce
        if (!isset($_POST['eveai_sync_meta_box_nonce']) || !wp_verify_nonce($_POST['eveai_sync_meta_box_nonce'], 'eveai_sync_meta_box')) {
            return;
        }

        // Check permissions
        if ('page' == $_POST['post_type']) {
            if (!current_user_can('edit_page', $post_id)) return;
        } else {
            if (!current_user_can('edit_post', $post_id)) return;
        }

        // Check if we should sync this post
        if (!$this->should_sync_post($post_id)) return;

        // Check if this is a REST API request
        if (defined('REST_REQUEST') && REST_REQUEST) {
            error_log("EveAI: REST API request detected for post $post_id");
        }

        error_log('Handling post' . $post_id . 'save event with update: ' . $update);

        // Check if we've already synced this post in this request
        if (get_post_meta($post_id, '_eveai_syncing', true)) {
            return;
        }

        // Set a flag to indicate we're syncing
        update_post_meta($post_id, '_eveai_syncing', true);

        $this->sync_post($post_id, $update);

        // Remove the flag after syncing
        delete_post_meta($post_id, '_eveai_syncing');
    }

    public function sync_post($post_id, $is_update) {
        $evie_id = get_post_meta($post_id, '_eveai_document_id', true);

        try {
            if ($evie_id && $is_update) {
                $old_data = $this->get_old_post_data($post_id);
                $new_data = $this->prepare_post_data($post_id);

                if ($this->has_metadata_changed($old_data, $new_data)) {
                    $result = $this->refresh_document_with_info($evie_id, $new_data);
                } else {
                    $result = $this->refresh_document($evie_id);
                }
            } else {
                $data = $this->prepare_post_data($post_id);
                $result = $this->api->add_url($data);
            }

            if (isset($result['document_id']) && isset($result['document_version_id'])) {
                update_post_meta($post_id, '_eveai_document_id', $result['document_id']);
                update_post_meta($post_id, '_eveai_document_version_id', $result['document_version_id']);

                // Add debugging
                error_log("EveAI: Set document_id {$result['document_id']} and document_version_id {$result['document_version_id']} for post {$post_id}");
            }
            return true;
        } catch (Exception $e) {
            error_log('EveAI Sync Error: ' . $e->getMessage());
            // Optionally, you can add an admin notice here
            add_action('admin_notices', function() use ($e) {
                echo '<div class="notice notice-error is-dismissible">';
                echo '<p>EveAI Sync Error: ' . esc_html($e->getMessage()) . '</p>';
                echo '</div>';
            });
            return false;
        }

        return false;
    }

    private function get_old_post_data($post_id) {
        $post = get_post($post_id);
        return array(
            'name' => $post->post_title,
            'user_metadata' => json_encode([
                'post_id' => $post_id,
                'type' => $post->post_type,
                'author' => get_the_author_meta('display_name', $post->post_author),
                'categories' => $post->post_type === 'post' ? wp_get_post_categories($post_id, array('fields' => 'names')) : [],
                'tags' => $post->post_type === 'post' ? wp_get_post_tags($post_id, array('fields' => 'names')) : [],
            ])
        );
    }

    private function has_metadata_changed($old_data, $new_data) {
        return $old_data['name'] !== $new_data['name'] ||
               (isset($old_data['user_metadata']) && isset($new_data['user_metadata']) &&
                $old_data['user_metadata'] !== $new_data['user_metadata']);
    }

    private function refresh_document_with_info($evie_id, $data) {
        try {
            return $this->api->refresh_document_with_info($evie_id, $data);
        } catch (Exception $e) {
            error_log('EveAI refresh with info error: ' . $e->getMessage());
            return false;
        }
    }

    private function refresh_document($evie_id) {
        try {
            return $this->api->refresh_document($evie_id);
        } catch (Exception $e) {
            error_log('EveAI refresh error: ' . $e->getMessage());
            add_action('admin_notices', function() use ($e) {
                echo '<div class="notice notice-error is-dismissible">';
                echo '<p>EveAI Sync Error: ' . esc_html($e->getMessage()) . '</p>';
                echo '</div>';
            });
            return false;
        }
    }

    public function handle_post_delete($post_id) {
        // First check if we have an EveAI document ID for this post
        $evie_id = get_post_meta($post_id, '_eveai_document_id', true);

        if ($evie_id) {
            try {
                error_log("EveAI: Attempting to invalidate document {$evie_id} for post {$post_id}");
                $result = $this->api->invalidate_document($evie_id);
                error_log("EveAI: Successfully invalidated document {$evie_id}");

                // Clean up post meta
                delete_post_meta($post_id, '_eveai_document_id');
                delete_post_meta($post_id, '_eveai_document_version_id');

                return true;
            } catch (Exception $e) {
                error_log("EveAI: Error invalidating document {$evie_id}: " . $e->getMessage());
                return false;
            }
        } else {
            error_log("EveAI: No document ID found for post {$post_id}, skipping invalidation");
            return false;
        }
    }

    public function process_sync_queue() {
        $queue = get_option('eveai_sync_queue', array());
        foreach ($queue as $key => $item) {
            $this->sync_post($item['post_id'], $item['is_update']);
            unset($queue[$key]);
        }
        update_option('eveai_sync_queue', $queue);
    }

    private function should_sync_post($post_id) {
        if (get_post_meta($post_id, '_eveai_exclude_sync', true)) {
            return false;
        }

        $post_type = get_post_type($post_id);

        if ($post_type === 'page') {
            // Pages are always synced unless individually excluded
            return true;
        }

        if ($post_type === 'post') {
            $excluded_categories_string = get_option('eveai_excluded_categories', '');
            $excluded_categories = array_map('trim', explode(',', $excluded_categories_string));

            $post_categories = wp_get_post_categories($post_id, array('fields' => 'names'));
            $post_tags = wp_get_post_tags($post_id, array('fields' => 'names'));

            // Check if any of the post's categories or tags are not in the excluded list
            $all_terms = array_merge($post_categories, $post_tags);
            foreach ($all_terms as $term) {
                if (!in_array($term, $excluded_categories)) {
                    return true;
                }
            }
        }

        return false;
    }

    private function prepare_post_data($post_id) {
        $post = get_post($post_id);
        // Get the permalink but replace localhost with the FQDN, keeping the port
        $url = get_permalink($post_id);
        $data = array(
            'url' => $url,
            'name' => $post->post_title,
            'language' => get_option('eveai_default_language', 'en'),
            'valid_from' => get_gmt_from_date($post->post_date, 'Y-m-d\TH:i:s\Z'),
            'user_metadata' => json_encode([
                'post_id' => $post_id,
                'type' => $post->post_type,
                'author' => get_the_author_meta('display_name', $post->post_author),
                'categories' => $post->post_type === 'post' ? wp_get_post_categories($post_id, array('fields' => 'names')) : [],
                'tags' => $post->post_type === 'post' ? wp_get_post_tags($post_id, array('fields' => 'names')) : [],
            ]),
        );

        return $data;
    }
}