<?php
namespace Blogibot\Feed;

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

/**
 * Feed AJAX Handler
 * Handles all AJAX requests for feed operations
 */
class FeedAjax {
    
    /**
     * Register AJAX actions
     */
    public static function init() {
        // Feed management actions
        add_action('wp_ajax_blogibot_validate_feed', [__CLASS__, 'validate_feed']);
        add_action('wp_ajax_blogibot_add_feed_source', [__CLASS__, 'add_feed_source']);
        add_action('wp_ajax_blogibot_update_feed_source', [__CLASS__, 'update_feed_source']);
        add_action('wp_ajax_blogibot_delete_feed_source', [__CLASS__, 'delete_feed_source']);
        add_action('wp_ajax_blogibot_get_feed_sources', [__CLASS__, 'get_feed_sources']);
        add_action('wp_ajax_blogibot_fetch_feed', [__CLASS__, 'fetch_feed']);
        add_action('wp_ajax_blogibot_toggle_feed_status', [__CLASS__, 'toggle_feed_status']);
        add_action('wp_ajax_blogibot_bulk_feed_action', [__CLASS__, 'bulk_feed_action']);
    }
    
    /**
     * Validate a feed URL
     */
    public static function validate_feed() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $feed_url = isset($_POST['feed_url']) ? esc_url_raw($_POST['feed_url']) : '';
        
        if (empty($feed_url)) {
            wp_send_json_error(['message' => 'Feed URL is required.']);
        }
        
        // Validate URL format
        if (!filter_var($feed_url, FILTER_VALIDATE_URL)) {
            wp_send_json_error(['message' => 'Invalid URL format.']);
        }
        
        // Fetch and parse the feed
        include_once(ABSPATH . WPINC . '/feed.php');
        
        $rss = fetch_feed($feed_url);
        
        if (is_wp_error($rss)) {
            wp_send_json_error([
                'message' => 'Failed to fetch feed: ' . $rss->get_error_message()
            ]);
        }
        
        // Get feed information
        $maxitems = $rss->get_item_quantity(10);
        $items = $rss->get_items(0, $maxitems);
        
        // Safely get feed date
        $feed_date = 'Unknown';
        try {
            if (method_exists($rss, 'get_date')) {
                $timestamp = $rss->get_date('U');
                if ($timestamp) {
                    $feed_date = human_time_diff($timestamp) . ' ago';
                }
            }
        } catch (Exception $e) {
            // Silently catch any SimplePie exceptions
        }
        
        $feed_data = [
            'valid' => true,
            'title' => $rss->get_title() ?: 'Untitled Feed',
            'description' => $rss->get_description() ?: '',
            'link' => $rss->get_permalink() ?: '',
            'posts_count' => count($items),
            'last_updated' => $feed_date,
            'feed_type' => self::detect_feed_type($rss),
            'preview_posts' => []
        ];
        
        // Get preview of first 3 posts
        foreach (array_slice($items, 0, 3) as $item) {
            // Safely get item date
            $item_date = '';
            try {
                if (method_exists($item, 'get_date')) {
                    $item_date = $item->get_date('j F Y') ?: '';
                }
            } catch (Exception $e) {
                // Silently catch any SimplePie exceptions
            }
            
            $feed_data['preview_posts'][] = [
                'title' => $item->get_title() ?: 'Untitled',
                'link' => $item->get_permalink() ?: '',
                'date' => $item_date,
                'excerpt' => wp_trim_words(strip_tags($item->get_description()), 30)
            ];
        }
        
        wp_send_json_success($feed_data);
    }
    
    /**
     * Detect feed type (RSS or Atom)
     */
    private static function detect_feed_type($rss) {
        $feed_type = $rss->get_type();
        if (stripos($feed_type, 'atom') !== false) {
            return 'atom';
        }
        return 'rss';
    }
    
    /**
     * Add a new feed source
     */
    public static function add_feed_source() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $result = FeedManager::add_feed_source($_POST);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * Update an existing feed source
     */
    public static function update_feed_source() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $feed_id = isset($_POST['feed_id']) ? intval($_POST['feed_id']) : 0;
        $result = FeedManager::update_feed_source($feed_id, $_POST);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * Delete a feed source
     */
    public static function delete_feed_source() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $feed_id = isset($_POST['feed_id']) ? intval($_POST['feed_id']) : 0;
        $result = FeedManager::delete_feed_source($feed_id);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * Get all feed sources with filters
     */
    public static function get_feed_sources() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $filters = [
            'status' => isset($_POST['status']) ? sanitize_text_field($_POST['status']) : '',
            'category' => isset($_POST['category']) ? sanitize_text_field($_POST['category']) : '',
            'fetch_frequency' => isset($_POST['fetch_frequency']) ? sanitize_text_field($_POST['fetch_frequency']) : '',
            'search' => isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '',
        ];
        
        $feeds = FeedManager::get_feed_sources($filters);
        $stats = FeedManager::get_feed_stats();
        
        // Add category names to each feed
        if ($feeds) {
            foreach ($feeds as &$feed) {
                if (!empty($feed->category)) {
                    $category = get_term(intval($feed->category), 'category');
                    if ($category && !is_wp_error($category)) {
                        $feed->category_name = $category->name;
                    } else {
                        $feed->category_name = '';
                    }
                } else {
                    $feed->category_name = '';
                }
            }
        }
        
        wp_send_json_success([
            'feeds' => $feeds,
            'stats' => $stats
        ]);
    }

    
    /**
     * Fetch posts from a feed
     */
    public static function fetch_feed() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $feed_id = isset($_POST['feed_id']) ? intval($_POST['feed_id']) : 0;
        
        if (empty($feed_id)) {
            wp_send_json_error(['message' => 'Feed ID is required.']);
        }
        
        // Get feed source
        $feed_source = FeedManager::get_feed_source($feed_id);
        
        if (!$feed_source) {
            wp_send_json_error(['message' => 'Feed source not found.']);
        }
        
        // Use FeedFetcher to fetch posts
        $result = FeedFetcher::fetch_feed($feed_id);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * Toggle feed status (active/paused)
     */
    public static function toggle_feed_status() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $feed_id = isset($_POST['feed_id']) ? intval($_POST['feed_id']) : 0;
        $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : '';
        
        if (empty($feed_id) || empty($status)) {
            wp_send_json_error(['message' => 'Feed ID and status are required.']);
        }
        
        $result = FeedManager::update_feed_source($feed_id, ['status' => $status]);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * Bulk action for multiple feeds
     */
    public static function bulk_feed_action() {
        check_ajax_referer('blogibot_feed_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Permission denied.']);
        }
        
        $feed_ids = isset($_POST['feed_ids']) ? array_map('intval', $_POST['feed_ids']) : [];
        $action = isset($_POST['action_type']) ? sanitize_text_field($_POST['action_type']) : '';
        
        if (empty($feed_ids) || empty($action)) {
            wp_send_json_error(['message' => 'Feed IDs and action are required.']);
        }
        
        $success_count = 0;
        $errors = [];
        
        foreach ($feed_ids as $feed_id) {
            switch ($action) {
                case 'activate':
                    $result = FeedManager::update_feed_source($feed_id, ['status' => 'active']);
                    break;
                case 'pause':
                    $result = FeedManager::update_feed_source($feed_id, ['status' => 'paused']);
                    break;
                case 'delete':
                    $result = FeedManager::delete_feed_source($feed_id);
                    break;
                case 'fetch':
                    $result = FeedFetcher::fetch_feed($feed_id);
                    break;
                default:
                    $result = ['success' => false, 'message' => 'Invalid action'];
            }
            
            if ($result['success']) {
                $success_count++;
            } else {
                $errors[] = "Feed ID {$feed_id}: " . $result['message'];
            }
        }
        
        wp_send_json_success([
            'message' => "{$success_count} of " . count($feed_ids) . " feeds processed successfully.",
            'success_count' => $success_count,
            'errors' => $errors
        ]);
    }
}
