<?php
namespace Blogibot\Feed;

if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Feed Fetcher
 * Handles fetching and importing posts from RSS/Atom feeds
 */
class FeedFetcher {
    
    /**
     * Fetch posts from a feed source
     */
    public static function fetch_feed($feed_id) {
        $feed_source = FeedManager::get_feed_source($feed_id);
        
        if (!$feed_source) {
            return [
                'success' => false,
                'message' => 'Feed source not found.'
            ];
        }
        
        // Check if feed is active
        if ($feed_source->status !== 'active') {
            return [
                'success' => false,
                'message' => 'Feed is not active.'
            ];
        }
        
        // Fetch the feed
        include_once(ABSPATH . WPINC . '/feed.php');
        
        $rss = fetch_feed($feed_source->feed_url);
        
        if (is_wp_error($rss)) {
            // Update fetch status with error
            FeedManager::update_fetch_status($feed_id, 'error', $rss->get_error_message());
            
            return [
                'success' => false,
                'message' => 'Failed to fetch feed: ' . $rss->get_error_message()
            ];
        }
        
        // Get items
        $maxitems = intval($feed_source->max_posts);
        $items = $rss->get_items(0, $maxitems);
        
        if (empty($items)) {
            FeedManager::update_fetch_status($feed_id, 'success', 'No new posts found.');
            
            return [
                'success' => true,
                'message' => 'No new posts found.',
                'posts_imported' => 0
            ];
        }
        
        // Process each item
        $imported_count = 0;
        $errors = [];
        
        foreach ($items as $item) {
            $result = self::import_feed_item($feed_id, $feed_source, $item);
            
            if ($result['success']) {
                $imported_count++;
            } else {
                $errors[] = $result['message'];
            }
        }
        
        // Update fetch status
        $status = empty($errors) ? 'success' : 'partial';
        $message = "{$imported_count} posts imported" . (empty($errors) ? '' : ', some errors occurred.');
        
        FeedManager::update_fetch_status($feed_id, $status, $message, $imported_count);
        
        return [
            'success' => true,
            'message' => $message,
            'posts_imported' => $imported_count,
            'errors' => $errors
        ];
    }
    
    /**
     * Import a single feed item
     */
    private static function import_feed_item($feed_id, $feed_source, $item) {
        global $wpdb;
        
        $guid = $item->get_id() ?: $item->get_permalink();
        $title = $item->get_title() ?: 'Untitled';
        $url = $item->get_permalink() ?: '';
        $date = $item->get_date('Y-m-d H:i:s') ?: current_time('mysql');
        
        // Check if already imported
        $fetched_posts_table = FeedDatabase::get_fetched_posts_table_name();
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$fetched_posts_table} WHERE feed_item_guid = %s",
            $guid
        ));
        
        if ($existing) {
            return [
                'success' => false,
                'message' => 'Post already imported: ' . $title
            ];
        }
        
        // Prepare post content
        $content = $item->get_content() ?: $item->get_description() ?: '';
        $content = wp_kses_post($content);
        
        // Prepare excerpt
        $excerpt = wp_trim_words(strip_tags($content), intval($feed_source->excerpt_length));
        
        // Prepare post data
        $post_data = [
            'post_title' => sanitize_text_field($title),
            'post_content' => $content,
            'post_excerpt' => $excerpt,
            'post_status' => intval($feed_source->auto_publish) ? 'publish' : 'draft',
            'post_author' => get_current_user_id(),
            'post_date' => $date,
            'post_type' => 'post',
        ];
        
        // Set category if specified (category is now stored as WordPress term_id)
        if (!empty($feed_source->category)) {
            $category_id = intval($feed_source->category);
            // Verify the category exists
            $category = get_term($category_id, 'category');
            if ($category && !is_wp_error($category)) {
                $post_data['post_category'] = [$category_id];
            }
        }

        
        // Insert post
        $post_id = wp_insert_post($post_data, true);
        
        if (is_wp_error($post_id)) {
            // Log to fetched posts table as failed
            $wpdb->insert($fetched_posts_table, [
                'feed_source_id' => $feed_id,
                'feed_item_guid' => $guid,
                'feed_item_title' => $title,
                'feed_item_url' => $url,
                'feed_item_date' => $date,
                'import_status' => 'failed',
                'error_message' => $post_id->get_error_message(),
            ]);
            
            return [
                'success' => false,
                'message' => 'Failed to import: ' . $post_id->get_error_message()
            ];
        }
        
        // Add source URL as post meta
        add_post_meta($post_id, '_blogibot_source_url', $url);
        add_post_meta($post_id, '_blogibot_feed_id', $feed_id);
        
        // Handle featured image if enabled
        if (intval($feed_source->auto_featured_image)) {
            self::set_featured_image($post_id, $item);
        }
        
        // Log to fetched posts table
        $wpdb->insert($fetched_posts_table, [
            'feed_source_id' => $feed_id,
            'post_id' => $post_id,
            'feed_item_guid' => $guid,
            'feed_item_title' => $title,
            'feed_item_url' => $url,
            'feed_item_date' => $date,
            'import_status' => 'imported',
            'import_date' => current_time('mysql'),
        ]);
        
        return [
            'success' => true,
            'message' => 'Post imported: ' . $title,
            'post_id' => $post_id
        ];
    }
    
    /**
     * Set featured image from feed item
     */
    private static function set_featured_image($post_id, $item) {
        $image_url = null;
        
        // Method 1: Try to get image from enclosure
        $enclosure = $item->get_enclosure();
        if ($enclosure) {
            if ($enclosure->get_thumbnail()) {
                $image_url = $enclosure->get_thumbnail();
            } elseif ($enclosure->get_link() && strpos($enclosure->get_type(), 'image') !== false) {
                $image_url = $enclosure->get_link();
            }
        }
        
        // Method 2: Try media:content or media:thumbnail (common in feeds)
        if (!$image_url) {
            $media_content = $item->get_item_tags('http://search.yahoo.com/mrss/', 'content');
            if ($media_content && isset($media_content[0]['attribs']['']['url'])) {
                $image_url = $media_content[0]['attribs']['']['url'];
            }
            
            if (!$image_url) {
                $media_thumbnail = $item->get_item_tags('http://search.yahoo.com/mrss/', 'thumbnail');
                if ($media_thumbnail && isset($media_thumbnail[0]['attribs']['']['url'])) {
                    $image_url = $media_thumbnail[0]['attribs']['']['url'];
                }
            }
        }
        
        // Method 3: Try to extract first image from content
        if (!$image_url) {
            $content = $item->get_content() ?: $item->get_description();
            // Try multiple image patterns
            if (preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches)) {
                $image_url = $matches[1];
            } elseif (preg_match('/!\[([^\]]*)\]\(([^)]+)\)/', $content, $matches)) {
                // Markdown image format
                $image_url = $matches[2];
            }
        }
        
        // Method 4: Try og:image from link
        if (!$image_url && $item->get_permalink()) {
            $image_url = self::extract_og_image($item->get_permalink());
        }
        
        if ($image_url) {
            // Clean and validate URL
            $image_url = esc_url_raw($image_url);
            
            if (filter_var($image_url, FILTER_VALIDATE_URL)) {
                $attachment_id = self::upload_image_from_url($image_url, $post_id);
                if ($attachment_id && !is_wp_error($attachment_id)) {
                    set_post_thumbnail($post_id, $attachment_id);
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * Extract og:image from URL
     */
    private static function extract_og_image($url) {
        try {
            $response = wp_remote_get($url, ['timeout' => 10, 'redirection' => 5]);
            
            if (is_wp_error($response)) {
                return null;
            }
            
            $body = wp_remote_retrieve_body($response);
            
            // Try to find og:image meta tag
            if (preg_match('/<meta[^>]+property=[\'"]og:image[\'"][^>]+content=[\'"]([^\'"]+)[\'"][^>]*>/i', $body, $matches)) {
                return $matches[1];
            }
            
            if (preg_match('/<meta[^>]+content=[\'"]([^\'"]+)[\'"][^>]+property=[\'"]og:image[\'"][^>]*>/i', $body, $matches)) {
                return $matches[1];
            }
        } catch (Exception $e) {
            // Silently fail
        }
        
        return null;
    }
    
    /**
     * Upload image from URL and attach to post
     */
    private static function upload_image_from_url($image_url, $post_id) {
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        
        // Download image to temp file with timeout
        $temp_file = download_url($image_url, 30);
        
        if (is_wp_error($temp_file)) {
            error_log('Blogibot: Failed to download image: ' . $temp_file->get_error_message());
            return false;
        }
        
        // Validate it's actually an image
        $file_type = wp_check_filetype(basename($image_url));
        if (!$file_type['type'] || strpos($file_type['type'], 'image/') !== 0) {
            // Try to detect mime type from file
            $mime = mime_content_type($temp_file);
            if (!$mime || strpos($mime, 'image/') !== 0) {
                @unlink($temp_file);
                return false;
            }
            $file_type['type'] = $mime;
        }
        
        // Generate proper filename
        $filename = sanitize_file_name(basename(parse_url($image_url, PHP_URL_PATH)));
        if (!$filename || strpos($filename, '.') === false) {
            $ext = $file_type['ext'] ?: 'jpg';
            $filename = 'feed-image-' . time() . '.' . $ext;
        }
        
        // Prepare file array
        $file_array = [
            'name' => $filename,
            'tmp_name' => $temp_file,
            'type' => $file_type['type']
        ];
        
        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, $post_id, null, [
            'test_form' => false,
            'test_type' => false
        ]);
        
        // Delete temp file
        if (file_exists($temp_file)) {
            @unlink($temp_file);
        }
        
        if (is_wp_error($attachment_id)) {
            error_log('Blogibot: Failed to upload image: ' . $attachment_id->get_error_message());
            return false;
        }
        
        return $attachment_id;
    }
}
