<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Core Plugin Class
 *
 * Orchestrates all plugin functionality and initializes components
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes
 */

class Kitsune_AI_Platform_Core {

    /**
     * The unique identifier of this plugin
     */
    protected $plugin_name;

    /**
     * The current version of the plugin
     */
    protected $version;

    /**
     * Admin class instance
     */
    protected $admin;

    /**
     * Public class instance
     */
    protected $public;

    /**
     * Initialize the plugin
     */
    public function __construct() {
        $this->plugin_name = 'kitsune-ai-platform';
        $this->version = KITSUNE_AI_PLATFORM_VERSION;

        $this->load_dependencies();
        $this->set_locale();
        $this->define_admin_hooks();
        $this->define_public_hooks();

        $this->define_cron_hooks();
        $this->check_upgrade();
    }

    /**
     * Load required dependencies
     */
    private function load_dependencies() {









        new Kitsune_AI_Platform_Automation_Manager($this->plugin_name, $this->version);

        // Initialize CPTs
        new Kitsune_AI_Platform_CPT();
    }

    /**
     * Check for database upgrades
     */
    private function check_upgrade() {
        $db_version = get_option('kitsune_ai_platform_db_version');
        if (version_compare($db_version, KITSUNE_AI_PLATFORM_VERSION, '<')) {
            require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/class-kitsune-ai-platform-activator.php';
            Kitsune_AI_Platform_Activator::activate();
        }
    }

    /**
     * Set plugin text domain for internationalization
     */
    private function set_locale() {
        add_action('init', array($this, 'load_plugin_textdomain'));
    }

    /**
     * Load plugin text domain
     *
     * Respects the plugin-level language setting, allowing the admin to override
     * the WordPress site locale for this plugin specifically.
     */
    public function load_plugin_textdomain() {
        $plugin_locale = $this->get_plugin_locale();

        if ( ! empty( $plugin_locale ) ) {
            // Unload the text domain in case WP has already loaded English (e.g. via JIT)
            unload_textdomain( 'kitsune-ai-platform' );

            $mofile_core = WP_LANG_DIR . '/plugins/kitsune-ai-platform-' . $plugin_locale . '.mo';
            $mofile_local = WP_PLUGIN_DIR . '/' . dirname( KITSUNE_AI_PLATFORM_PLUGIN_BASENAME ) . '/languages/kitsune-ai-platform-' . $plugin_locale . '.mo';

            // Explicitly load parsing the MO file if it exists
            if ( file_exists( $mofile_core ) ) {
                load_textdomain( 'kitsune-ai-platform', $mofile_core );
                return; // successfully loaded custom language from WP_LANG_DIR
            } elseif ( file_exists( $mofile_local ) ) {
                load_textdomain( 'kitsune-ai-platform', $mofile_local );
                return; // successfully loaded custom language from plugin dir
            }
        }

        // Let WordPress core auto-load plugin translations on WordPress.org.
        return;
    }

    /**
     * Resolve the per-plugin locale from saved settings.
     *
     * Returns an empty string when English (default) is selected so that
     * the WordPress site locale is used unchanged.
     *
     * @return string Locale code (e.g. 'fr_FR') or empty string for English.
     */
    private function get_plugin_locale() {
        $settings = get_option( 'kitsune_ai_platform_settings', array() );
        $lang     = isset( $settings['language'] ) ? (string) $settings['language'] : 'en';

        return ( $lang === 'en' ) ? '' : $lang;
    }

    /**
     * Register admin-related hooks
     */
    private function define_admin_hooks() {
        $this->admin = new Kitsune_AI_Platform_Admin($this->plugin_name, $this->version);

        // Add admin menu
        add_action('admin_menu', array($this->admin, 'add_plugin_admin_menu'));

        // Enqueue admin assets
        add_action('admin_enqueue_scripts', array($this->admin, 'enqueue_admin_scripts'));

        // Add settings link to plugins page
        add_filter('plugin_action_links_' . KITSUNE_AI_PLATFORM_PLUGIN_BASENAME, array($this->admin, 'add_action_links'));

    }

    /**
     * Register public-facing hooks
     */
    private function define_public_hooks() {
        $this->public = new Kitsune_AI_Platform_Public($this->plugin_name, $this->version);

        // Enqueue public assets
        add_action('wp_enqueue_scripts', array($this->public, 'enqueue_public_scripts'));

        // Handle direct chatbot URL (/?ai-chatbot=ID)
        add_action('template_redirect', array($this->public, 'handle_direct_chatbot_url'));

        // Register shortcodes
        add_shortcode('kitsune_ai_platform_chatbot', array($this->public, 'render_chatbot_shortcode'));
        add_shortcode('kitsune-ai-platform-chatbot', array($this->public, 'render_chatbot_shortcode'));
        add_shortcode('kitsune_ai_platform_form', array($this->public, 'render_form_shortcode'));
        add_shortcode('kitsune_ai_platform_search', array($this->public, 'render_search_shortcode'));

        // Add chatbot widget to footer (if enabled)
        add_action('wp_footer', array($this->public, 'render_chatbot_widget'));

        // AJAX: Chatbot message handler (guest + logged-in)
        add_action('wp_ajax_kitsune_ai_platform_chatbot_message', array($this->public, 'ajax_chatbot_message'));
        add_action('wp_ajax_nopriv_kitsune_ai_platform_chatbot_message', array($this->public, 'ajax_chatbot_message'));

        // AJAX: End chatbot session (guest + logged-in)
        add_action('wp_ajax_kitsune_ai_platform_end_session', array($this->public, 'ajax_end_session'));
        add_action('wp_ajax_nopriv_kitsune_ai_platform_end_session', array($this->public, 'ajax_end_session'));

        // AJAX: Get session messages (guest + logged-in)
        add_action('wp_ajax_kitsune_ai_platform_get_session_messages', array($this->public, 'ajax_get_session_messages'));
        add_action('wp_ajax_nopriv_kitsune_ai_platform_get_session_messages', array($this->public, 'ajax_get_session_messages'));

        // AJAX: Form submission handler (guest + logged-in)
        add_action('wp_ajax_kitsune_ai_platform_submit_form', array($this->public, 'ajax_submit_form'));
        add_action('wp_ajax_nopriv_kitsune_ai_platform_submit_form', array($this->public, 'ajax_submit_form'));

        // AJAX: Get chatbot config on demand (guest + logged-in)
        add_action('wp_ajax_kitsune_ai_platform_get_chatbot_config', array($this->public, 'ajax_get_chatbot_config'));
        add_action('wp_ajax_nopriv_kitsune_ai_platform_get_chatbot_config', array($this->public, 'ajax_get_chatbot_config'));
    }



    /**
     * Register cron hooks
     */
    private function define_cron_hooks() {
        // Register custom cron intervals before any schedules are used
        add_filter('cron_schedules', array($this, 'add_custom_cron_schedules'));

        add_action('kitsune_ai_platform_daily_stats', array($this, 'process_daily_stats'));
        add_action('kitsune_ai_platform_weekly_summary', array($this, 'send_weekly_summary'));
        add_action('kitsune_ai_platform_cleanup_logs', array($this, 'cleanup_old_logs'));

        // Scheduled automation task execution
        add_action('kitsune_ai_platform_run_scheduled_task', array($this, 'run_scheduled_task'));
    }

    /**
     * Register custom WP-Cron recurrence intervals.
     * WP ships hourly / twicedaily / daily / weekly; we add monthly & yearly.
     *
     * @param array $schedules Existing schedules.
     * @return array
     */
    public function add_custom_cron_schedules($schedules) {
        if (!isset($schedules['monthly'])) {
            $schedules['monthly'] = array(
                'interval' => 30 * DAY_IN_SECONDS,
                /* translators: %s: Monthly interval description */
                'display'  => __('Once Monthly', 'kitsune-ai-platform'),
            );
        }
        if (!isset($schedules['yearly'])) {
            $schedules['yearly'] = array(
                'interval' => 365 * DAY_IN_SECONDS,
                /* translators: %s: Yearly interval description */
                'display'  => __('Once Yearly', 'kitsune-ai-platform'),
            );
        }
        return $schedules;
    }

    /**
     * Process daily statistics
     */
    public function process_daily_stats() {
        global $wpdb;
        $stats_table = $wpdb->prefix . 'kitsune_ai_platform_stats';
        $today = current_time('Y-m-d');

        // Aggregate chatbot stats
        $chatbot_stats = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT chatbot_id, COUNT(*) as count, AVG(satisfaction_rating) as avg_rating
                 FROM {$wpdb->prefix}kitsune_ai_platform_conversations
                 WHERE DATE(created_at) = %s
                 GROUP BY chatbot_id",
                $today
            )
        );

        foreach ($chatbot_stats as $stat) {
            $wpdb->insert(
                $stats_table,
                array(
                    'stat_type' => 'chatbot',
                    'stat_key' => 'daily_conversations_' . $stat->chatbot_id,
                    'stat_value' => json_encode(array(
                        'count' => $stat->count,
                        'avg_rating' => $stat->avg_rating
                    )),
                    'date' => $today,
                )
            );
        }

        // Aggregate API usage stats
        $api_stats = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT SUM(tokens_input + tokens_output) as total_tokens, SUM(cost) as total_cost
                 FROM {$wpdb->prefix}kitsune_ai_platform_api_logs
                 WHERE DATE(created_at) = %s",
                $today
            )
        );

        if ($api_stats) {
            $wpdb->insert(
                $stats_table,
                array(
                    'stat_type' => 'api',
                    'stat_key' => 'daily_usage',
                    'stat_value' => json_encode($api_stats),
                    'date' => $today,
                )
            );
        }
    }

    /**
     * Send weekly summary email
     */
    public function send_weekly_summary() {
        $settings = get_option('kitsune_ai_platform_settings', array());

        if (empty($settings['notifications']['weekly_summary'])) {
            return;
        }

        $admin_email = $settings['admin_email'] ?? get_option('admin_email');

        // Get weekly stats
        global $wpdb;
        $week_ago = gmdate('Y-m-d', strtotime('-7 days'));

        $stats = array(
            'conversations' => $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}kitsune_ai_platform_conversations
                     WHERE created_at >= %s",
                    $week_ago
                )
            ),
            'content_generated' => $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}kitsune_ai_platform_content
                     WHERE created_at >= %s",
                    $week_ago
                )
            ),
            'form_submissions' => $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}kitsune_ai_platform_form_submissions
                     WHERE created_at >= %s",
                    $week_ago
                )
            ),
            'total_cost' => $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COALESCE(SUM(cost), 0) FROM {$wpdb->prefix}kitsune_ai_platform_api_logs
                     WHERE created_at >= %s",
                    $week_ago
                )
            ),
        );

        // Send email
        /* translators: %s: Weekly summary subject prefix */
        $subject = __('AI Platform - Weekly Summary', 'kitsune-ai-platform');
        $message = $this->format_weekly_summary_email($stats);

        wp_mail($admin_email, $subject, $message, array('Content-Type: text/html; charset=UTF-8'));
    }

    /**
     * Format weekly summary email content
     */
    private function format_weekly_summary_email($stats) {
        ob_start();
        ?>
        <html>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <h2><?php esc_html_e('AI Platform - Weekly Summary', 'kitsune-ai-platform'); ?></h2>
            <p><?php esc_html_e("Here's your weekly activity summary:", 'kitsune-ai-platform'); ?></p>
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 10px; border: 1px solid #ddd;"><strong><?php esc_html_e('Chatbot Conversations:', 'kitsune-ai-platform'); ?></strong></td>
                    <td style="padding: 10px; border: 1px solid #ddd;"><?php echo esc_html(number_format((int) $stats['conversations'])); ?></td>
                </tr>
                <tr>
                    <td style="padding: 10px; border: 1px solid #ddd;"><strong><?php esc_html_e('Content Generated:', 'kitsune-ai-platform'); ?></strong></td>
                    <td style="padding: 10px; border: 1px solid #ddd;"><?php echo esc_html(number_format((int) $stats['content_generated'])); ?></td>
                </tr>
                <tr>
                    <td style="padding: 10px; border: 1px solid #ddd;"><strong><?php esc_html_e('Form Submissions:', 'kitsune-ai-platform'); ?></strong></td>
                    <td style="padding: 10px; border: 1px solid #ddd;"><?php echo esc_html(number_format((int) $stats['form_submissions'])); ?></td>
                </tr>
                <tr>
                    <td style="padding: 10px; border: 1px solid #ddd;"><strong><?php esc_html_e('Total Cost:', 'kitsune-ai-platform'); ?></strong></td>
                    <td style="padding: 10px; border: 1px solid #ddd;">$<?php echo esc_html(number_format((float) $stats['total_cost'], 2)); ?></td>
                </tr>
            </table>
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=ai-platform')); ?>"><?php esc_html_e('View Dashboard', 'kitsune-ai-platform'); ?></a></p>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }

    /**
     * Cleanup old logs based on retention settings
     */
    public function cleanup_old_logs() {
        global $wpdb;
        $settings = get_option('kitsune_ai_platform_settings', array());
        $retention_days = $settings['data_retention'] ?? 90;
        $cutoff_date = gmdate('Y-m-d', strtotime("-{$retention_days} days"));

        // Delete old API logs
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}kitsune_ai_platform_api_logs WHERE created_at < %s",
                $cutoff_date
            )
        );

        // Delete old workflow logs
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}kitsune_ai_platform_workflow_logs WHERE created_at < %s",
                $cutoff_date
            )
        );

        // Delete old stats (keep for 1 year)
        $stats_cutoff = gmdate('Y-m-d', strtotime('-365 days'));
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}kitsune_ai_platform_stats WHERE date < %s",
                $stats_cutoff
            )
        );
    }

    /**
     * Run a scheduled automation task
     * 
     * @param int $task_id The scheduled task ID
     */
    public function run_scheduled_task($task_id) {
        $model = new Kitsune_AI_Platform_Scheduled_Task_Model();
        $task  = $model->get_by_id($task_id);

        if (!$task || $task->status !== 'active') {
            return;
        }

        // Check if end date has passed
        if (!empty($task->end_date)) {
            $end_time = strtotime($task->end_date . ' 23:59:59');
            if (time() > $end_time) {
                // Deactivate the task and remove the cron event
                $model->update($task_id, array('active' => false));
                $model->unschedule_cron_event($task_id);
                return;
            }
        }

        // Get the workflow
        $workflow_model = new Kitsune_AI_Platform_Workflow_Model();
        $workflow       = $workflow_model->get_by_id($task->workflow_id);

        if (!$workflow) {
            error_log('AI Platform: Scheduled task ' . $task_id . ' - workflow not found');
            return;
        }

        // Decode workflow config
        $config = json_decode($workflow->config, true);
        if (!$config || !isset($config['trigger'])) {
            error_log('AI Platform: Scheduled task ' . $task_id . ' - invalid workflow config');
            return;
        }

        // Record last run time
        $model->update_last_run($task_id);

        // Create a scheduled context
        $context = array(
            'scheduled_task_id'   => $task_id,
            'scheduled_task_name' => $task->name,
            'trigger_type'        => 'scheduled',
            'execution_time'      => current_time('mysql'),
        );

        // Execute the workflow
        do_action('kitsune_ai_platform_execute_workflow', $workflow->id, $config, $context);
    }

    /**
     * Run the plugin
     */
    public function run() {
        // Plugin is now initialized and hooks are registered
    }
}
