<?php
/*
Plugin Name: IGNY8 AI SEO
Description: A comprehensive WordPress plugin for content optimization, automation, and SEO management.
Version: 0.1
Author: Alorig
*/

/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : igny8.php
 * @location     : /igny8.php
 * @type         : Plugin Bootstrap
 * @scope        : Global
 * @allowed      : Plugin initialization, core includes, hook registration
 * @reusability  : Single Use
 * @notes        : Main plugin entry point, loads core systems and modules
 */

/**
 * ==============================
 * 🔷 IGNY8 PLUGIN ROLE INDEX MAP
 * ==============================
 *
 * Layer 1: Global Index (this file)
 * Layer 2: Modular Folder Scope
 * Layer 3: Subfolder/File Index
 * Layer 4: File-Level RULE HEADER
 *
 * === Folder Role Map ===
 *
 * /modules/      → Core admin pages (Planner, Writer, etc.)
 * /core/         → Layout, init, DB, CRON
 * /ai/           → AI content/image logic, parsers, prompt APIs
 * /shortcodes/   → All shortcode handler files (split by module)
 * /components/   → UI/UX templates (forms, modals, tables)
 * /config/       → Central config arrays (filters, tables, prompts)
 * /assets/js/    → Module JS files
 * /debug/        → Dev-only tools: logs, CRON tests, function runners
 * /docs/         → Markdown docs only
 *
 * Rules:
 * - Every .php file must have a RULE HEADER block
 * - Only `/core/`, `/ai/`, and `/components/` can be reused globally
 * - Modules may not use each other directly
 * - No mixed-scope logic allowed
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// ---------------------------------------------------------------------
// PLUGIN INITIALIZATION
// ---------------------------------------------------------------------
add_action('plugins_loaded', 'igny8_bootstrap_plugin');

function igny8_bootstrap_plugin() {
    $plugin_path = plugin_dir_path(__FILE__);

// 1. Core database and schema
require_once $plugin_path . 'install.php';
require_once $plugin_path . 'core/db/db.php';

// 2. Database schema is now handled by install.php and db.php
    
    // 2. AI model rates configuration
    require_once $plugin_path . 'ai/model-rates-config.php';
    
    // 2. AI prompts library
    require_once $plugin_path . 'ai/prompts-library.php';

    // 2. Automation workflows (must load early for AJAX)
    require_once $plugin_path . 'flows/sync-hooks.php';     // Hook definitions first
    require_once $plugin_path . 'flows/sync-functions.php'; // Functions
    require_once $plugin_path . 'flows/sync-ajax.php';      // AJAX handlers
    // Marker-based image injection removed - now using div container system
    
    // 2.5. Cron system (load after workflows)
    // Legacy cron manager removed - using new master dispatcher system
    require_once $plugin_path . 'core/cron/igny8-cron-handlers.php';   // Cron handlers

    // CRON key generation moved to conditional loading
    // Only generate when actually needed (not on every page load)
    
    // Include wp-load handler for CRON requests (after plugin is loaded)
    if (isset($_GET['import_id']) && $_GET['import_id'] === 'igny8_cron') {
        require_once $plugin_path . 'igny8-wp-load-handler.php';
    }

// 3. Core admin functionality
    if (is_admin()) {
        require_once $plugin_path . 'core/admin/module-manager-class.php'; // Module manager class and functions
        require_once $plugin_path . 'core/admin/menu.php';
        
        // Debug utilities (only in admin)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // Debug utilities can be added here if needed
        }
        require_once $plugin_path . 'core/admin/init.php'; // handles admin_init + settings
        require_once $plugin_path . 'core/admin/ajax.php'; // registers all AJAX actions
        require_once $plugin_path . 'core/admin/meta-boxes.php'; // SEO meta boxes
    }

    // 4. API layer
    require_once $plugin_path . 'ai/openai-api.php';
    require_once $plugin_path . 'ai/modules-ai.php';
    require_once $plugin_path . 'ai/writer/images/image-generation.php';

    // 4.5. Frontend shortcodes (load for both admin and frontend)
    require_once $plugin_path . 'shortcodes/ai-shortcodes.php';
    require_once $plugin_path . 'shortcodes/writer-shortcodes.php';

    // 4. Module components (UI templates)
    $components = [
        'modules/components/kpi-tpl.php',
        'modules/components/filters-tpl.php',
        'modules/components/actions-tpl.php',
        'modules/components/table-tpl.php',
        'modules/components/pagination-tpl.php',
        'modules/components/forms-tpl.php'
    ];
    foreach ($components as $file) {
        require_once $plugin_path . $file;
    }

    // 5. Global configuration
    $GLOBALS['igny8_kpi_config'] = require_once $plugin_path . 'modules/config/kpi-config.php';
    
    // 6. Register taxonomies
    add_action('init', 'igny8_register_taxonomies', 5);
}

/**
 * Get or generate CRON key - ensures key is always available
 */
function igny8_get_or_generate_cron_key() {
    // Use static cache to prevent multiple database calls
    static $cached_key = null;
    
    if ($cached_key !== null) {
        return $cached_key;
    }
    
    $key = get_option('igny8_secure_cron_key');
    
    if (empty($key)) {
        $key = wp_generate_password(32, false, false);
        update_option('igny8_secure_cron_key', $key);
    }
    
    // Cache the key for this request
    $cached_key = $key;
    
    return $key;
}

/**
 * Check if current page needs CRON functionality
 */
function igny8_needs_cron_functionality() {
    $current_page = $_GET['page'] ?? '';
    $current_submodule = $_GET['sm'] ?? '';
    
    // Pages that need CRON functionality
    $cron_pages = [
        'igny8-schedules',           // Schedules page
        'igny8-planner' => 'home',   // Planner home only
        'igny8-writer' => 'home'    // Writer home only
    ];
    
    // Check if current page needs CRON
    if (isset($cron_pages[$current_page])) {
        if (is_string($cron_pages[$current_page])) {
            // Page has submodule requirement
            return $current_submodule === $cron_pages[$current_page];
        }
        return true; // Page needs CRON without submodule requirement
    }
    
    return false;
}

// ---------------------------------------------------------------------
// ACTIVATION / DEACTIVATION
// ---------------------------------------------------------------------
register_activation_hook(__FILE__, 'igny8_activate');
register_deactivation_hook(__FILE__, 'igny8_deactivate');

function igny8_activate() {
    require_once plugin_dir_path(__FILE__) . 'install.php';
    if (function_exists('igny8_install')) {
    igny8_install();
    }
    flush_rewrite_rules();
}

function igny8_deactivate() {
    flush_rewrite_rules();
}

// ---------------------------------------------------------------------
// ADMIN ASSETS ENQUEUING
// ---------------------------------------------------------------------
add_action('admin_enqueue_scripts', 'igny8_admin_scripts');

function igny8_admin_scripts($hook) {
    // Only load on Igny8 admin pages
    if (strpos($hook, 'igny8') === false) return;

    $plugin_url = plugin_dir_url(__FILE__);
    
    // Enqueue core CSS with updated version
    wp_enqueue_style('igny8-admin-style', $plugin_url . 'assets/css/core.css', [], '0.1');
    
    // Enqueue Chart.js
    wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js@4.5.0/dist/chart.umd.min.js', [], '4.5.0', true);
    wp_add_inline_script('chart-js', 'window.Chart = Chart;', 'after');

    // Enqueue core JavaScript with dependencies and updated version
    wp_enqueue_script('igny8-admin-js', $plugin_url . 'assets/js/core.js', ['jquery', 'chart-js'], '0.1', true);
    
    // Enqueue image queue processor
    wp_enqueue_script('igny8-image-queue', $plugin_url . 'assets/js/image-queue-processor.js', ['igny8-admin-js'], '0.1', true);
    
    // AJAX localization
    wp_localize_script('igny8-admin-js', 'igny8_ajax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('igny8_ajax_nonce'),
        'module' => igny8_get_current_module(),
        'debug_enabled' => false
    ]);
}

// ---------------------------------------------------------------------
// HELPER: Get current module from admin URL
// ---------------------------------------------------------------------
function igny8_get_current_module() {
    if (isset($_GET['page']) && strpos($_GET['page'], 'igny8-') === 0) {
        return str_replace('igny8-', '', sanitize_text_field($_GET['page']));
    }
    return 'planner';
}
