<?php
/**
 * Plugin Name: Blogibot - Smart AI for SEO-Ready Blog Creation & Feed Management
 * Plugin URI: https://wontonee.com/blogibot
 * Author: Saju Gopal / Wontonee DigitalCraft LLP
 * Author URI: https://wontonee.com
 * Description: AI-powered WordPress blog writer & RSS feed aggregator. Generate SEO-optimized articles, auto-import content from feeds, schedule posts, and boost organic traffic with smart content automation.
 * Version: 2.0.4
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

defined('ABSPATH') || exit;

// Plugin version constant
if (!defined('BLOGIBOT_VERSION')) {
    define('BLOGIBOT_VERSION', '2.0.4');
}

// Blogibot API Environment Constants
if (!defined('BLOGIBOT_API_ENV')) {
    define('BLOGIBOT_API_ENV', 'production'); // Change to 'local' for development
}
if (!defined('BLOGIBOT_API_SANDBOX')) {
    define('BLOGIBOT_API_SANDBOX', 'https://licenseapp.test/api/');
}
if (!defined('BLOGIBOT_API_PRODUCTION')) {
    define('BLOGIBOT_API_PRODUCTION', 'https://myapps.wontonee.com/api');
}

// Enable Feed Tab
if (!defined('BLOGIBOT_ENABLE_FEED')) {
    define('BLOGIBOT_ENABLE_FEED', true);
}

// Enable debug mode for better error tracking
if (!defined('WP_DEBUG')) {
    define('WP_DEBUG', true);
}
if (!defined('WP_DEBUG_LOG')) {
    define('WP_DEBUG_LOG', true);
}

// Load Composer Autoload
require_once __DIR__ . '/vendor/autoload.php';

// Load Feed classes
require_once __DIR__ . '/src/Feed/FeedDatabase.php';
require_once __DIR__ . '/src/Feed/FeedManager.php';
require_once __DIR__ . '/src/Feed/FeedAjax.php';
require_once __DIR__ . '/src/Feed/FeedFetcher.php';

// Load main plugin class
require_once __DIR__ . '/src/Blogibot.php';

// Activation hook - create database tables
register_activation_hook(__FILE__, function() {
    \Blogibot\Feed\FeedDatabase::create_tables();
});

// Initialize AJAX handlers
add_action('init', function() {
    \Blogibot\Feed\FeedAjax::init();
});

// Register custom cron schedules
add_filter('cron_schedules', function($schedules) {
    $schedules['sixhours'] = [
        'interval' => 21600, // 6 hours in seconds
        'display' => __('Every 6 Hours', 'blogibot')
    ];
    return $schedules;
});

/**
 * Register cron hook for a single feed
 * This function can be called dynamically when feeds are created/updated
 */
function blogibot_register_feed_cron_hook($feed_id) {
    $hook = 'blogibot_fetch_feed_' . $feed_id;
    
    // Only register if not already registered
    if (!has_action($hook)) {
        add_action($hook, function() use ($feed_id) {
            error_log("Blogibot: Running cron fetch for feed ID: " . $feed_id);
            
            try {
                $result = \Blogibot\Feed\FeedFetcher::fetch_feed($feed_id);
                
                if ($result['success']) {
                    error_log("Blogibot: Successfully fetched " . count($result['posts']) . " posts for feed ID: " . $feed_id);
                } else {
                    error_log("Blogibot: Failed to fetch feed ID: " . $feed_id . " - " . $result['message']);
                }
            } catch (Exception $e) {
                error_log("Blogibot: Exception fetching feed ID: " . $feed_id . " - " . $e->getMessage());
            }
        });
    }
}

// Register cron handlers for all existing feed sources very early (plugins_loaded)
// This ensures hooks are available when WP-Cron runs
add_action('plugins_loaded', function() {
    global $wpdb;
    $table_name = \Blogibot\Feed\FeedDatabase::get_table_name();
    $feeds = $wpdb->get_results("SELECT id FROM {$table_name} WHERE status = 'active'", ARRAY_A);
    
    if ($feeds) {
        foreach ($feeds as $feed) {
            blogibot_register_feed_cron_hook($feed['id']);
        }
    }
}, 5); // Priority 5 to run early

// Register hook for dynamically registering cron hooks when feeds are created
add_action('blogibot_feed_created', 'blogibot_register_feed_cron_hook');
add_action('blogibot_feed_updated', 'blogibot_register_feed_cron_hook');

// Enqueue scripts for admin
add_action('admin_enqueue_scripts', function($hook) {
    // Only load on Blogibot feed pages
    if (strpos($hook, 'blogibot') === false) {
        return;
    }
    
    // Check if we're on the add/edit feed source page
    $current_tab = isset($_GET['tab']) ? $_GET['tab'] : '';
    $current_subtab = isset($_GET['subtab']) ? $_GET['subtab'] : '';
    
    if ($current_tab === 'feed' && ($current_subtab === 'add_feed_source' || $current_subtab === 'edit_feed_source')) {
        // Enqueue the external JavaScript file
        wp_enqueue_script(
            'blogibot-add-feed-source',
            plugins_url('assets/js/feed/add-feed-source.js', __FILE__),
            array('jquery'),
            BLOGIBOT_VERSION,
            true
        );
        
        // Localize script with data
        $script_data = array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('blogibot_feed_nonce'),
            'manage_feeds_url' => admin_url('admin.php?page=blogibot&tab=feed&subtab=manage_feeds')
        );
        
        // Add feed data for edit mode
        if ($current_subtab === 'edit_feed_source' && isset($_GET['feed_id'])) {
            $feed_id = intval($_GET['feed_id']);
            $feed_data = \Blogibot\Feed\FeedManager::get_feed($feed_id);
            if ($feed_data) {
                $script_data['edit_mode'] = true;
                $script_data['feed_data'] = $feed_data;
            }
        }
        
        wp_localize_script('blogibot-add-feed-source', 'blogibotFeed', $script_data);
        
        // For edit mode, also add feed data separately
        if (isset($script_data['feed_data'])) {
            wp_localize_script('blogibot-add-feed-source', 'blogibotFeedData', array(
                'edit_mode' => true,
                'feed_data' => $script_data['feed_data']
            ));
        }
    }
});
