<?php
namespace Blogibot\Feed;

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

/**
 * Feed Manager
 * Handles CRUD operations for feed sources
 */
class FeedManager {
    
    /**
     * Add a new feed source
     */
    public static function add_feed_source($data) {
        global $wpdb;
        
        // Validate required fields
        if (empty($data['feed_name']) || empty($data['feed_url'])) {
            return [
                'success' => false,
                'message' => 'Feed name and URL are required.'
            ];
        }
        
        // Validate URL format
        if (!filter_var($data['feed_url'], FILTER_VALIDATE_URL)) {
            return [
                'success' => false,
                'message' => 'Invalid feed URL format.'
            ];
        }
        
        // Check if feed URL already exists
        $table_name = FeedDatabase::get_table_name();
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$table_name} WHERE feed_url = %s",
            $data['feed_url']
        ));
        
        if ($existing) {
            return [
                'success' => false,
                'message' => 'This feed URL already exists.'
            ];
        }
        
        // Prepare data for insertion
        $insert_data = [
            'feed_name' => sanitize_text_field($data['feed_name']),
            'feed_url' => esc_url_raw($data['feed_url']),
            'feed_type' => isset($data['feed_type']) ? sanitize_text_field($data['feed_type']) : 'rss',
            'category' => isset($data['category']) ? sanitize_text_field($data['category']) : null,
            'fetch_frequency' => isset($data['fetch_frequency']) ? sanitize_text_field($data['fetch_frequency']) : (isset($data['import_frequency']) ? sanitize_text_field($data['import_frequency']) : 'daily'),
            'max_posts' => isset($data['max_posts']) ? intval($data['max_posts']) : 10,
            'status' => 'active',
            'auto_fetch' => isset($data['auto_fetch']) && ($data['auto_fetch'] === 'on' || $data['auto_fetch'] == 1) ? 1 : 0,
            'auto_featured_image' => isset($data['auto_featured_image']) && ($data['auto_featured_image'] === 'on' || $data['auto_featured_image'] == 1) ? 1 : 0,
            'auto_publish' => isset($data['auto_publish']) ? intval($data['auto_publish']) : (isset($data['import_type']) && $data['import_type'] === 'publish' ? 1 : 0),
            'excerpt_length' => isset($data['excerpt_length']) ? intval($data['excerpt_length']) : 150,
        ];
        
        // Insert into database
        $result = $wpdb->insert($table_name, $insert_data);
        
        if ($result === false) {
            return [
                'success' => false,
                'message' => 'Database error: ' . $wpdb->last_error
            ];
        }
        
        $feed_id = $wpdb->insert_id;
        
        // Schedule cron job for auto-fetch if enabled
        if (isset($data['auto_fetch']) && ($data['auto_fetch'] === 'on' || $data['auto_fetch'] == 1)) {
            self::schedule_feed_cron($feed_id, $insert_data['fetch_frequency']);
        }
        
        // Trigger action to register cron hook dynamically
        do_action('blogibot_feed_created', $feed_id);
        
        return [
            'success' => true,
            'message' => 'Feed source added successfully!',
            'feed_id' => $feed_id
        ];
    }
    
    /**
     * Update an existing feed source
     */
    public static function update_feed_source($feed_id, $data) {
        global $wpdb;
        
        if (empty($feed_id)) {
            return [
                'success' => false,
                'message' => 'Feed ID is required.'
            ];
        }
        
        $table_name = FeedDatabase::get_table_name();
        
        // Check if feed exists
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$table_name} WHERE id = %d",
            $feed_id
        ));
        
        if (!$exists) {
            return [
                'success' => false,
                'message' => 'Feed source not found.'
            ];
        }
        
        // Prepare update data
        $update_data = [];
        
        if (isset($data['feed_name'])) {
            $update_data['feed_name'] = sanitize_text_field($data['feed_name']);
        }
        if (isset($data['feed_url'])) {
            $update_data['feed_url'] = esc_url_raw($data['feed_url']);
        }
        if (isset($data['category'])) {
            $update_data['category'] = sanitize_text_field($data['category']);
        }
        if (isset($data['fetch_frequency'])) {
            $update_data['fetch_frequency'] = sanitize_text_field($data['fetch_frequency']);
        }
        if (isset($data['max_posts'])) {
            $update_data['max_posts'] = intval($data['max_posts']);
        }
        if (isset($data['status'])) {
            $update_data['status'] = sanitize_text_field($data['status']);
        }
        if (isset($data['auto_featured_image'])) {
            $update_data['auto_featured_image'] = intval($data['auto_featured_image']);
        }
        if (isset($data['auto_publish'])) {
            $update_data['auto_publish'] = intval($data['auto_publish']);
        }
        if (isset($data['excerpt_length'])) {
            $update_data['excerpt_length'] = intval($data['excerpt_length']);
        }
        
        if (empty($update_data)) {
            return [
                'success' => false,
                'message' => 'No data to update.'
            ];
        }
        
        // Update database
        $result = $wpdb->update(
            $table_name,
            $update_data,
            ['id' => $feed_id]
        );
        
        if ($result === false) {
            return [
                'success' => false,
                'message' => 'Database error: ' . $wpdb->last_error
            ];
        }
        
        // Get current feed data to check auto_fetch status
        $feed = self::get_feed_source($feed_id);
        
        // Reschedule cron job if needed
        if ($feed && isset($feed['auto_fetch']) && intval($feed['auto_fetch']) === 1) {
            $frequency = isset($update_data['fetch_frequency']) ? $update_data['fetch_frequency'] : $feed['fetch_frequency'];
            self::schedule_feed_cron($feed_id, $frequency);
        } else {
            // Unschedule if auto-fetch is disabled
            self::unschedule_feed_cron($feed_id);
        }
        
        // Trigger action to register/update cron hook dynamically
        do_action('blogibot_feed_updated', $feed_id);
        
        return [
            'success' => true,
            'message' => 'Feed source updated successfully!'
        ];
    }
    
    /**
     * Delete a feed source
     */
    public static function delete_feed_source($feed_id) {
        global $wpdb;
        
        if (empty($feed_id)) {
            return [
                'success' => false,
                'message' => 'Feed ID is required.'
            ];
        }
        
        $table_name = FeedDatabase::get_table_name();
        
        // Unschedule cron job before deleting
        self::unschedule_feed_cron($feed_id);
        
        // Delete from database
        $result = $wpdb->delete($table_name, ['id' => $feed_id]);
        
        if ($result === false) {
            return [
                'success' => false,
                'message' => 'Database error: ' . $wpdb->last_error
            ];
        }
        
        if ($result === 0) {
            return [
                'success' => false,
                'message' => 'Feed source not found.'
            ];
        }
        
        // Also delete related fetched posts records
        $fetched_posts_table = FeedDatabase::get_fetched_posts_table_name();
        $wpdb->delete($fetched_posts_table, ['feed_source_id' => $feed_id]);
        
        return [
            'success' => true,
            'message' => 'Feed source deleted successfully!'
        ];
    }
    
    /**
     * Get all feed sources with optional filters
     */
    public static function get_feed_sources($filters = []) {
        global $wpdb;
        
        $table_name = FeedDatabase::get_table_name();
        
        $where = ['1=1'];
        $params = [];
        
        if (!empty($filters['status'])) {
            $where[] = 'status = %s';
            $params[] = $filters['status'];
        }
        
        if (!empty($filters['category'])) {
            $where[] = 'category = %s';
            $params[] = $filters['category'];
        }
        
        if (!empty($filters['fetch_frequency'])) {
            $where[] = 'fetch_frequency = %s';
            $params[] = $filters['fetch_frequency'];
        }
        
        if (!empty($filters['search'])) {
            $where[] = '(feed_name LIKE %s OR feed_url LIKE %s)';
            $search_term = '%' . $wpdb->esc_like($filters['search']) . '%';
            $params[] = $search_term;
            $params[] = $search_term;
        }
        
        $where_clause = implode(' AND ', $where);
        
        $sql = "SELECT * FROM {$table_name} WHERE {$where_clause} ORDER BY created_at DESC";
        
        if (!empty($params)) {
            $sql = $wpdb->prepare($sql, $params);
        }
        
        return $wpdb->get_results($sql);
    }
    
    /**
     * Get a single feed source by ID
     */
    public static function get_feed_source($feed_id) {
        global $wpdb;
        
        $table_name = FeedDatabase::get_table_name();
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table_name} WHERE id = %d",
            $feed_id
        ));
    }
    
    /**     * Schedule cron job for feed fetching
     */
    public static function schedule_feed_cron($feed_id, $frequency) {
        $hook = 'blogibot_fetch_feed_' . $feed_id;
        
        // Clear any existing schedule
        $timestamp = wp_next_scheduled($hook, [$feed_id]);
        if ($timestamp) {
            wp_unschedule_event($timestamp, $hook, [$feed_id]);
        }
        
        // Map frequency to WordPress schedules
        $schedule_map = [
            'hourly' => 'hourly',
            '6hours' => 'sixhours',
            'daily' => 'daily',
            'weekly' => 'weekly'
        ];
        
        $schedule = isset($schedule_map[$frequency]) ? $schedule_map[$frequency] : 'daily';
        
        // Schedule the event
        if (!wp_next_scheduled($hook, [$feed_id])) {
            wp_schedule_event(time(), $schedule, $hook, [$feed_id]);
        }
    }
    
    /**
     * Unschedule cron job for feed fetching
     */
    public static function unschedule_feed_cron($feed_id) {
        $hook = 'blogibot_fetch_feed_' . $feed_id;
        $timestamp = wp_next_scheduled($hook, [$feed_id]);
        
        if ($timestamp) {
            wp_unschedule_event($timestamp, $hook, [$feed_id]);
        }
    }
    
    /**     * Get feed statistics
     */
    public static function get_feed_stats() {
        global $wpdb;
        
        $table_name = FeedDatabase::get_table_name();
        
        return [
            'total' => $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}"),
            'active' => $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'active'"),
            'inactive' => $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'inactive'"),
            'error' => $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'error'"),
            'paused' => $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE status = 'paused'"),
            'total_posts' => $wpdb->get_var("SELECT SUM(posts_imported_total) FROM {$table_name}"),
        ];
    }
    
    /**
     * Update feed fetch status
     */
    public static function update_fetch_status($feed_id, $status, $message = null, $posts_imported = 0) {
        global $wpdb;
        
        $table_name = FeedDatabase::get_table_name();
        
        $update_data = [
            'last_fetch_time' => current_time('mysql'),
            'last_fetch_status' => $status,
            'last_fetch_message' => $message
        ];
        
        if ($posts_imported > 0) {
            // Get current totals
            $current = $wpdb->get_row($wpdb->prepare(
                "SELECT posts_imported_total, posts_imported_today FROM {$table_name} WHERE id = %d",
                $feed_id
            ));
            
            if ($current) {
                $update_data['posts_imported_total'] = intval($current->posts_imported_total) + $posts_imported;
                $update_data['posts_imported_today'] = intval($current->posts_imported_today) + $posts_imported;
            }
        }
        
        return $wpdb->update(
            $table_name,
            $update_data,
            ['id' => $feed_id]
        );
    }
    
    /**
     * Reset daily post counts (should be run via cron at midnight)
     */
    public static function reset_daily_counts() {
        global $wpdb;
        
        $table_name = FeedDatabase::get_table_name();
        
        return $wpdb->query("UPDATE {$table_name} SET posts_imported_today = 0");
    }
}
