<?php
/**
 * Blog Integration
 *
 * @package ReplyIt_Chat_Widget
 */

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

class ReplyIt_Blog {

    /**
     * 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() {
        // Blog-specific hooks can be added here
    }

    /**
     * Get current post data (if on single blog post page)
     *
     * @return array|null
     */
    public static function get_current_post() {
        if (!is_single() || get_post_type() !== 'post') {
            return null;
        }

        global $post;

        if (!$post) {
            return null;
        }

        return self::format_post_data($post, true); // Include full content
    }

    /**
     * Get archive context (category, tag, author pages)
     *
     * @return array|null
     */
    public static function get_archive_context() {
        if (is_category()) {
            $category = get_queried_object();
            return [
                'type' => 'category',
                'id' => $category->term_id,
                'name' => $category->name,
                'slug' => $category->slug,
                'description' => $category->description,
                'post_count' => $category->count,
            ];
        }

        if (is_tag()) {
            $tag = get_queried_object();
            return [
                'type' => 'tag',
                'id' => $tag->term_id,
                'name' => $tag->name,
                'slug' => $tag->slug,
                'description' => $tag->description,
                'post_count' => $tag->count,
            ];
        }

        if (is_author()) {
            $author = get_queried_object();
            return [
                'type' => 'author',
                'id' => $author->ID,
                'name' => $author->display_name,
                'description' => get_the_author_meta('description', $author->ID),
            ];
        }

        return null;
    }

    /**
     * Search blog posts by various criteria
     *
     * @param array $args Search arguments
     * @return array Search results
     */
    public static function search_posts($args = []) {
        $query = $args['query'] ?? '';
        $category = $args['category'] ?? '';
        $tag = $args['tag'] ?? '';
        $author = $args['author'] ?? '';
        $post_id = $args['post_id'] ?? '';
        $limit = min(intval($args['limit'] ?? 10), 20); // Max 20 posts

        $posts = [];

        // Search by post ID first (exact match)
        if (!empty($post_id)) {
            $post = get_post(intval($post_id));
            if ($post && $post->post_status === 'publish' && $post->post_type === 'post') {
                return [
                    'posts' => [self::format_post_data($post, true)],
                    'total_found' => 1,
                    'search_type' => 'post_id'
                ];
            }
            return [
                'posts' => [],
                'total_found' => 0,
                'search_type' => 'post_id',
                'message' => __('Post not found with this ID.', 'replyit-chat-widget')
            ];
        }

        // Build query args
        $query_args = [
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => $limit,
            'orderby' => 'relevance',
            'order' => 'DESC',
        ];

        // Text search
        if (!empty($query)) {
            $query_args['s'] = sanitize_text_field($query);
        }

        // Category filter
        if (!empty($category)) {
            // Try to find category by name or slug
            $term = get_term_by('name', $category, 'category');
            if (!$term) {
                $term = get_term_by('slug', sanitize_title($category), 'category');
            }
            if ($term) {
                $query_args['cat'] = $term->term_id;
            }
        }

        // Tag filter
        if (!empty($tag)) {
            $query_args['tag'] = sanitize_title($tag);
        }

        // Author filter
        if (!empty($author)) {
            // Try to find by display name first
            $user = get_user_by('login', $author);
            if (!$user) {
                $user = get_user_by('slug', sanitize_title($author));
            }
            if (!$user) {
                // Search by display name
                $users = get_users([
                    'search' => '*' . $author . '*',
                    'search_columns' => ['display_name'],
                    'number' => 1,
                ]);
                $user = !empty($users) ? $users[0] : null;
            }
            if ($user) {
                $query_args['author'] = $user->ID;
            }
        }

        // Execute query
        $wp_query = new WP_Query($query_args);

        foreach ($wp_query->posts as $post) {
            $posts[] = self::format_post_data($post, false); // Summary only
        }

        return [
            'posts' => $posts,
            'total_found' => count($posts),
            'search_type' => !empty($query) ? 'keyword' : (!empty($category) ? 'category' : (!empty($tag) ? 'tag' : 'all')),
            'query' => $query,
            'category' => $category,
            'tag' => $tag,
        ];
    }

    /**
     * Get post content by ID
     *
     * @param int $post_id
     * @return array|null
     */
    public static function get_post_content($post_id) {
        $post = get_post(intval($post_id));

        if (!$post || $post->post_status !== 'publish' || $post->post_type !== 'post') {
            return null;
        }

        return self::format_post_data($post, true);
    }

    /**
     * Format post data for API response
     *
     * @param WP_Post $post
     * @param bool $include_full_content Include full content or just excerpt
     * @return array
     */
    private static function format_post_data($post, $include_full_content = false) {
        // Get categories
        $categories = [];
        $terms = get_the_terms($post->ID, 'category');
        if ($terms && !is_wp_error($terms)) {
            foreach ($terms as $term) {
                $categories[] = [
                    'id' => $term->term_id,
                    'name' => $term->name,
                    'slug' => $term->slug,
                ];
            }
        }

        // Get tags
        $tags = [];
        $tag_terms = get_the_terms($post->ID, 'post_tag');
        if ($tag_terms && !is_wp_error($tag_terms)) {
            foreach ($tag_terms as $term) {
                $tags[] = [
                    'id' => $term->term_id,
                    'name' => $term->name,
                    'slug' => $term->slug,
                ];
            }
        }

        // Get author
        $author = get_user_by('id', $post->post_author);
        $author_data = [
            'id' => $post->post_author,
            'name' => $author ? $author->display_name : '',
        ];

        // Get featured image
        $image_id = get_post_thumbnail_id($post->ID);
        $image_url = $image_id ? wp_get_attachment_image_url($image_id, 'medium') : null;

        // Get excerpt or generate from content
        $excerpt = $post->post_excerpt;
        if (empty($excerpt)) {
            $excerpt = wp_trim_words(strip_tags($post->post_content), 55, '...');
        }

        // Calculate reading time (approx 200 words per minute)
        $word_count = str_word_count(strip_tags($post->post_content));
        $reading_time = max(1, ceil($word_count / 200));

        $data = [
            'id' => $post->ID,
            'title' => $post->post_title,
            'slug' => $post->post_name,
            'excerpt' => $excerpt,
            'permalink' => get_permalink($post->ID),
            'date_published' => get_the_date('Y-m-d H:i:s', $post),
            'date_modified' => get_the_modified_date('Y-m-d H:i:s', $post),
            'author' => $author_data,
            'categories' => $categories,
            'tags' => $tags,
            'featured_image' => $image_url,
            'word_count' => $word_count,
            'reading_time_minutes' => $reading_time,
            'comment_count' => (int) $post->comment_count,
        ];

        // Include full content if requested
        if ($include_full_content) {
            // Get the raw content and apply filters for shortcodes, blocks, etc.
            $content = apply_filters('the_content', $post->post_content);
            // Strip HTML but keep paragraphs for readability
            $content = wp_strip_all_tags($content);
            // Clean up whitespace
            $content = preg_replace('/\s+/', ' ', $content);
            $content = trim($content);

            $data['content'] = $content;
        }

        return $data;
    }

    /**
     * Get related posts
     *
     * @param int $post_id
     * @param int $limit
     * @return array
     */
    public static function get_related_posts($post_id, $limit = 5) {
        $post = get_post($post_id);
        if (!$post) {
            return [];
        }

        // Get categories and tags for the post
        $categories = wp_get_post_categories($post_id, ['fields' => 'ids']);
        $tags = wp_get_post_tags($post_id, ['fields' => 'ids']);

        $query_args = [
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => $limit,
            'post__not_in' => [$post_id],
            'orderby' => 'relevance',
        ];

        // Build tax query
        $tax_query = ['relation' => 'OR'];

        if (!empty($categories)) {
            $tax_query[] = [
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => $categories,
            ];
        }

        if (!empty($tags)) {
            $tax_query[] = [
                'taxonomy' => 'post_tag',
                'field' => 'term_id',
                'terms' => $tags,
            ];
        }

        if (count($tax_query) > 1) {
            $query_args['tax_query'] = $tax_query;
        }

        $wp_query = new WP_Query($query_args);
        $related = [];

        foreach ($wp_query->posts as $related_post) {
            $related[] = self::format_post_data($related_post, false);
        }

        return $related;
    }
}
