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

/**
 * Automation Triggers
 *
 * Registers and handles WordPress hooks that serve as automation triggers.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/automation/triggers
 */

class Kitsune_AI_Platform_Automation_Triggers {

    /**
     * Workflow Model
     */
    private $workflow_model;

    /**
     * Initialize Triggers
     */
    public function __construct() {
        // Models loaded via Autoloader
        $this->workflow_model = new Kitsune_AI_Platform_Workflow_Model();


        $this->register_hooks();
    }

    /**
     * Register all trigger hooks
     */
    private function register_hooks() {
        // Content Management
        add_action('save_post', array($this, 'handle_post_updated'), 10, 3);
        add_action('transition_post_status', array($this, 'handle_post_status_transition'), 10, 3); // For publish
        add_action('wp_trash_post', array($this, 'handle_trash_post'));
        
        // Comments
        add_action('wp_insert_comment', array($this, 'handle_comment_post'), 10, 2);

        // Media
        add_action('add_attachment', array($this, 'handle_add_attachment'));
        add_action('delete_attachment', array($this, 'handle_delete_attachment'));

        // System
        add_action('init', array($this, 'handle_init'));
    }

    /**
     * Get list of registered triggers for UI
     * 
     * Each trigger includes:
     * - label: Human-readable name
     * - description: Purpose of the trigger
     * - config_fields: Optional configuration options
     * - context_vars: Variables available in workflow for this trigger (WordPress object fields)
     */
    public function get_registered_triggers() {
        return array(
            'post_updated' => array(
                'label' => __('Post Updated', 'kitsune-ai-platform'),
                'description' => __('Fires when an existing post is updated (not on initial creation)', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'post_type',
                        'label' => __('Post Type Filter', 'kitsune-ai-platform'),
                        'type' => 'multiselect',
                        'placeholder' => __('All post types', 'kitsune-ai-platform'),
                        'options' => $this->get_post_types_options()
                    )
                ),
                'context_vars' => array(
                    'post_id'       => __('Post ID', 'kitsune-ai-platform'),
                    'post_title'    => __('Post Title', 'kitsune-ai-platform'),
                    'post_content'  => __('Post Content', 'kitsune-ai-platform'),
                    'post_excerpt'  => __('Post Excerpt', 'kitsune-ai-platform'),
                    'post_author'   => __('Post Author ID', 'kitsune-ai-platform'),
                    'post_status'   => __('Post Status', 'kitsune-ai-platform'),
                    'post_type'     => __('Post Type', 'kitsune-ai-platform'),
                    'post_date'     => __('Post Date', 'kitsune-ai-platform'),
                    'post_url'      => __('Post URL', 'kitsune-ai-platform'),
                    'post_modified' => __('Last Modified Date', 'kitsune-ai-platform')
                )
            ),
            'publish_post' => array(
                'label' => __('Post Published', 'kitsune-ai-platform'),
                'description' => __('Triggers when a post is published', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'post_type',
                        'label' => __('Post Type Filter', 'kitsune-ai-platform'),
                        'type' => 'multiselect',
                        'placeholder' => __('All post types', 'kitsune-ai-platform'),
                        'options' => $this->get_post_types_options()
                    )
                ),
                'context_vars' => array(
                    'post_id' => __('Post ID', 'kitsune-ai-platform'),
                    'post_title' => __('Post Title', 'kitsune-ai-platform'),
                    'post_content' => __('Post Content', 'kitsune-ai-platform'),
                    'post_excerpt' => __('Post Excerpt', 'kitsune-ai-platform'),
                    'post_author' => __('Post Author ID', 'kitsune-ai-platform'),
                    'post_status' => __('Post Status', 'kitsune-ai-platform'),
                    'post_type' => __('Post Type', 'kitsune-ai-platform'),
                    'post_date' => __('Post Date', 'kitsune-ai-platform'),
                    'post_url' => __('Post URL', 'kitsune-ai-platform')
                )
            ),
            'trashed_post' => array(
                'label' => __('Post Moved to Trash', 'kitsune-ai-platform'),
                'description' => __('Triggers when a post is moved to trash', 'kitsune-ai-platform'),
                'config_fields' => array(
                    array(
                        'name' => 'post_type',
                        'label' => __('Post Type Filter', 'kitsune-ai-platform'),
                        'type' => 'multiselect',
                        'placeholder' => __('All post types', 'kitsune-ai-platform'),
                        'options' => $this->get_post_types_options()
                    )
                ),
                'context_vars' => array(
                    'post_id'    => __('Post ID', 'kitsune-ai-platform'),
                    'post_title' => __('Post Title', 'kitsune-ai-platform'),
                    'post_type'  => __('Post Type', 'kitsune-ai-platform')
                )
            ),
            'comment_post' => array(
                'label' => __('New Comment', 'kitsune-ai-platform'),
                'description' => __('Fires when a new comment is posted', 'kitsune-ai-platform'),
                'context_vars' => array(
                    'comment_id' => __('Comment ID', 'kitsune-ai-platform'),
                    'comment_content' => __('Comment Content', 'kitsune-ai-platform'),
                    'comment_author' => __('Comment Author Name', 'kitsune-ai-platform'),
                    'comment_author_email' => __('Comment Author Email', 'kitsune-ai-platform'),
                    'comment_post_id' => __('Parent Post ID', 'kitsune-ai-platform'),
                    'comment_date' => __('Comment Date', 'kitsune-ai-platform')
                )
            ),
            'add_attachment' => array(
                'label' => __('File Uploaded', 'kitsune-ai-platform'),
                'description' => __('Fires when a file is uploaded to the media library', 'kitsune-ai-platform'),
                'context_vars' => array(
                    'attachment_id' => __('Attachment ID', 'kitsune-ai-platform'),
                    'file_url' => __('File URL', 'kitsune-ai-platform'),
                    'file_type' => __('File MIME Type', 'kitsune-ai-platform'),
                    'file_name' => __('File Name', 'kitsune-ai-platform')
                )
            ),
            'delete_attachment' => array(
                'label' => __('Attachment Deleted', 'kitsune-ai-platform'),
                'description' => __('Fires when an attachment is deleted', 'kitsune-ai-platform'),
                'context_vars' => array(
                    'attachment_id' => __('Attachment ID', 'kitsune-ai-platform')
                )
            ),
            'init' => array(
                'label' => __('System Init', 'kitsune-ai-platform'),
                'description' => __('Fires when WordPress is fully loaded (use with caution)', 'kitsune-ai-platform'),
                'context_vars' => array()
            )
        );
    }

    /**
     * Get post types for dropdown options
     */
    private function get_post_types_options() {
        $post_types = get_post_types(array('public' => true), 'objects');
        $options = array();
        foreach ($post_types as $slug => $post_type) {
            $options[$slug] = $post_type->label;
        }
        return $options;
    }

    /**
     * Handler: post_updated (save_post, updates only)
     */
    public function handle_post_updated($post_id, $post, $update) {
        if (!$update) return; // Skip initial creation
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (wp_is_post_revision($post_id)) return;

        $context = array(
            'post_id'       => $post_id,
            'post'          => $post,
            'post_title'    => $post->post_title,
            'post_content'  => $post->post_content,
            'post_excerpt'  => $post->post_excerpt,
            'post_author'   => $post->post_author,
            'post_status'   => $post->post_status,
            'post_type'     => $post->post_type,
            'post_date'     => $post->post_date,
            'post_url'      => get_permalink($post_id),
            'post_modified' => $post->post_modified
        );

        $this->process_trigger('post_updated', $context);
    }

    /**
     * Handler: transition_post_status (for publish)
     */
    public function handle_post_status_transition($new_status, $old_status, $post) {
        if ($new_status === 'publish' && $old_status !== 'publish') {
            $context = array(
                'post_id' => $post->ID,
                'post' => $post,
                'post_title' => $post->post_title,
                'post_content' => $post->post_content,
                'post_excerpt' => $post->post_excerpt,
                'post_author' => $post->post_author,
                'post_status' => $post->post_status,
                'post_type' => $post->post_type,
                'post_date' => $post->post_date,
                'post_url' => get_permalink($post->ID)
            );
            $this->process_trigger('publish_post', $context);
        }
    }

    /**
     * Handler: trash_post
     */
    public function handle_trash_post($post_id) {
        $post = get_post($post_id);
        $this->process_trigger('trashed_post', array(
            'post_id'    => $post_id,
            'post_title' => $post ? $post->post_title : '',
            'post_type'  => $post ? $post->post_type : '',
        ));
    }

    /**
     * Handler: comment_post
     */
    public function handle_comment_post($comment_id, $comment_object) {
        $context = array(
            'comment_id' => $comment_id,
            'comment_object' => $comment_object,
            'comment_content' => $comment_object->comment_content,
            'comment_author' => $comment_object->comment_author,
            'comment_author_email' => $comment_object->comment_author_email,
            'comment_post_id' => $comment_object->comment_post_ID,
            'comment_date' => $comment_object->comment_date
        );
        $this->process_trigger('comment_post', $context);
    }

    /**
     * Handler: add_attachment
     */
    public function handle_add_attachment($attachment_id) {
        $url = wp_get_attachment_url($attachment_id);
        $type = get_post_mime_type($attachment_id);
        $file_path = get_attached_file($attachment_id);
        $file_name = basename($file_path);

        $this->process_trigger('add_attachment', array(
            'attachment_id' => $attachment_id, 
            'file_url' => $url,
            'file_type' => $type,
            'file_name' => $file_name
        ));
    }

    /**
     * Handler: delete_attachment
     */
    public function handle_delete_attachment($attachment_id) {
        $this->process_trigger('delete_attachment', array('attachment_id' => $attachment_id));
    }

    /**
     * Handler: init
     */
    public function handle_init() {
        // Run once per request - dangerous if not careful. 
        // For Automation, usually we check if there are any specific one-time tasks or scheduled checks.
        // Keeping it simple for now, maybe just log or specific use case.
        // $this->process_trigger('init', array());
    }

    /**
     * Process Trigger
     * Find workflows matching this trigger and execute them.
     */
    private function process_trigger($trigger_type, $context) {
        // Fetch active workflows with this trigger type
        $workflows = $this->get_workflows_by_trigger($trigger_type);
        
        foreach ($workflows as $workflow) {
            $config = json_decode($workflow->post_content, true);
            if (!$config || !isset($config['trigger'])) continue;

            if ($config['trigger']['type'] === $trigger_type) {
                // Check filters (e.g. post_type)
                if (!$this->check_conditions($config['trigger'], $context)) continue;

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

    /**
     * Get Workflows by Trigger Type
     */
    private function get_workflows_by_trigger($trigger_type) {
        $args = array(
            'post_type'      => 'kitsune_ai_workflow',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_key'       => '_ai_workflow_trigger',
            'meta_value'     => $trigger_type
        );
        return get_posts($args);
    }

    /**
     * Check Trigger Conditions
     */
    private function check_conditions($trigger_config, $context) {
        $config = isset($trigger_config['config']) ? $trigger_config['config'] : array();

        // Post type filter: supports single value or multiselect array.
        // An empty / unset selection means "all post types" — allow through.
        if (!empty($config['post_type'])) {
            $allowed_types = is_array($config['post_type'])
                ? array_filter(array_map('sanitize_key', $config['post_type']))
                : array(sanitize_key($config['post_type']));

            if (!empty($allowed_types)) {
                // Resolve the actual post type from context.
                if (isset($context['post_type']) && $context['post_type'] !== '') {
                    $actual_type = $context['post_type'];
                } elseif (isset($context['post']) && is_object($context['post'])) {
                    $actual_type = $context['post']->post_type;
                } else {
                    $actual_type = '';
                }

                if ($actual_type === '' || !in_array($actual_type, $allowed_types, true)) {
                    return false;
                }
            }
        }

        return true;
    }
}
