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

/**
 * Admin Integrations Handler
 *
 * Handles integrations, templates, and webhooks AJAX requests.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/admin
 */
class Kitsune_AI_Platform_Admin_Integrations extends Kitsune_AI_Platform_Admin_Ajax_Base {

    /**
     * Register AJAX hooks.
     */
    public function register_hooks() {
        add_action('wp_ajax_kitsune_ai_platform_get_integrations', array($this, 'ajax_get_integrations'));
        add_action('wp_ajax_kitsune_ai_platform_connect_integration', array($this, 'ajax_connect_integration'));
        add_action('wp_ajax_kitsune_ai_platform_disconnect_integration', array($this, 'ajax_disconnect_integration'));
        add_action('wp_ajax_kitsune_ai_platform_get_templates', array($this, 'ajax_get_templates'));
        add_action('wp_ajax_kitsune_ai_platform_install_template', array($this, 'ajax_install_template'));
        add_action('wp_ajax_kitsune_ai_platform_get_webhooks', array($this, 'ajax_get_webhooks'));
        add_action('wp_ajax_kitsune_ai_platform_create_webhook', array($this, 'ajax_create_webhook'));
        add_action('wp_ajax_kitsune_ai_platform_delete_webhook', array($this, 'ajax_delete_webhook'));
        add_action('wp_ajax_kitsune_ai_platform_test_webhook', array($this, 'ajax_test_webhook'));
    }

    /**
     * AJAX: Get Integrations
     */
    public function ajax_get_integrations() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        // Return integrations list (can be static or stored in options)
        $integrations = get_option('kitsune_ai_platform_integrations', array());
        
        // Default list if empty, or merge with available structure
        $default_integrations = array(
             array('id' => 'hubspot', 'name' => __('HubSpot', 'kitsune-ai-platform'), 'icon' => 'hubspot', 'description' => __('Connect to HubSpot CRM', 'kitsune-ai-platform'), 'connected' => false),
             array('id' => 'slack', 'name' => __('Slack', 'kitsune-ai-platform'), 'icon' => 'slack', 'description' => __('Send notifications to Slack', 'kitsune-ai-platform'), 'connected' => false),
             array('id' => 'zapier', 'name' => __('Zapier', 'kitsune-ai-platform'), 'icon' => 'zapier', 'description' => __('Connect to over 5000+ apps', 'kitsune-ai-platform'), 'connected' => false),
             array('id' => 'google_sheets', 'name' => __('Google Sheets', 'kitsune-ai-platform'), 'icon' => 'google', 'description' => __('Export data to Google Sheets', 'kitsune-ai-platform'), 'connected' => false),
        );
        
        // Merge state
        foreach ($default_integrations as &$integration) {
            if (isset($integrations[$integration['id']])) {
                $integration['connected'] = $integrations[$integration['id']]['connected'];
            }
        }

        wp_send_json_success($default_integrations);
    }

    /**
     * AJAX: Connect Integration
     */
    public function ajax_connect_integration() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        $id = isset($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
        if (!$id) {
             wp_send_json_error(array('message' => __('Integration ID required', 'kitsune-ai-platform')));
             return;
        }

        $integrations = get_option('kitsune_ai_platform_integrations', array());
        $integrations[$id] = array('connected' => true, 'connected_at' => current_time('mysql'));
        update_option('kitsune_ai_platform_integrations', $integrations);

        $integration = $integrations[$id];
        do_action('kitsune_ai_platform_integration_connected', $id, $integration);
        Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
            Kitsune_AI_Platform_Webhook_Events::INTEGRATION_CONNECTED,
            array(
                'integration_id' => $id,
                'integration' => $integration,
                'actor_id' => get_current_user_id(),
            )
        );

        wp_send_json_success(array('message' => __('Integration connected', 'kitsune-ai-platform')));
    }

    /**
     * AJAX: Disconnect Integration
     */
    public function ajax_disconnect_integration() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        $id = isset($_POST['id']) ? sanitize_text_field($_POST['id']) : '';
         if (!$id) {
             wp_send_json_error(array('message' => __('Integration ID required', 'kitsune-ai-platform')));
             return;
        }

        $integrations = get_option('kitsune_ai_platform_integrations', array());
        $integration = $integrations[$id] ?? null;
        if ($integration !== null) {
            unset($integrations[$id]);
            update_option('kitsune_ai_platform_integrations', $integrations);

            do_action('kitsune_ai_platform_integration_disconnected', $id, $integration);
            Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                Kitsune_AI_Platform_Webhook_Events::INTEGRATION_DISCONNECTED,
                array(
                    'integration_id' => $id,
                    'integration' => $integration,
                    'actor_id' => get_current_user_id(),
                )
            );
        }

        wp_send_json_success(array('message' => __('Integration disconnected', 'kitsune-ai-platform')));
    }

    /**
     * AJAX: Get Templates
     */
    public function ajax_get_templates() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        $type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';
        
        // Mock templates data matching frontend mocks
        $templates = array(
            'chatbot' => array(
                array('id' => 'support-agent', 'name' => __('Support Agent', 'kitsune-ai-platform'), 'description' => __('Handles customer support queries', 'kitsune-ai-platform'), 'image' => ''),
                array('id' => 'sales-rep', 'name' => __('Sales Representative', 'kitsune-ai-platform'), 'description' => __('Helps with product sales', 'kitsune-ai-platform'), 'image' => ''),
            ),
            'workflow' => array(
                array('id' => 'lead-qual', 'name' => __('Lead Qualification', 'kitsune-ai-platform'), 'description' => __('Qualifies incoming leads', 'kitsune-ai-platform'), 'image' => ''),
                array('id' => 'content-sched', 'name' => __('Content Scheduler', 'kitsune-ai-platform'), 'description' => __('Schedules blog posts', 'kitsune-ai-platform'), 'image' => ''),
            ),
            'forms' => array(
                array(
                    'id' => 'contact-form',
                    'name' => __('Contact Form', 'kitsune-ai-platform'),
                    'description' => __('Simple contact form with name, email, and message fields.', 'kitsune-ai-platform'),
                    'config' => array(
                        'fields' => array(
                            array('id' => 'field_name', 'type' => 'text', 'label' => __('Full Name', 'kitsune-ai-platform'), 'placeholder' => __('Enter your name', 'kitsune-ai-platform'), 'required' => true),
                            array('id' => 'field_email', 'type' => 'email', 'label' => __('Email Address', 'kitsune-ai-platform'), 'placeholder' => __('your@email.com', 'kitsune-ai-platform'), 'required' => true),
                            array('id' => 'field_message', 'type' => 'textarea', 'label' => __('Message', 'kitsune-ai-platform'), 'placeholder' => __('How can we help you?', 'kitsune-ai-platform'), 'required' => true),
                        ),
                        'settings' => array()
                    )
                ),
                array(
                    'id' => 'feedback-form',
                    'name' => __('Feedback Survey', 'kitsune-ai-platform'),
                    'description' => __('Collect user feedback with rating and comments.', 'kitsune-ai-platform'),
                    'config' => array(
                        'fields' => array(
                            array('id' => 'field_rating', 'type' => 'radio', 'label' => __('How would you rate our service?', 'kitsune-ai-platform'), 'options' => array(__('Excellent', 'kitsune-ai-platform'), __('Good', 'kitsune-ai-platform'), __('Average', 'kitsune-ai-platform'), __('Poor', 'kitsune-ai-platform')), 'required' => true),
                            array('id' => 'field_feedback', 'type' => 'textarea', 'label' => __('Additional Feedback', 'kitsune-ai-platform'), 'placeholder' => __('Tell us more...', 'kitsune-ai-platform'), 'required' => false),
                            array('id' => 'field_email', 'type' => 'email', 'label' => __('Email (optional)', 'kitsune-ai-platform'), 'placeholder' => __('your@email.com', 'kitsune-ai-platform'), 'required' => false),
                        ),
                        'settings' => array()
                    )
                ),
                array(
                    'id' => 'lead-capture',
                    'name' => __('Lead Capture Form', 'kitsune-ai-platform'),
                    'description' => __('Capture leads with contact info and interest selection.', 'kitsune-ai-platform'),
                    'config' => array(
                        'fields' => array(
                            array('id' => 'field_name', 'type' => 'text', 'label' => __('Name', 'kitsune-ai-platform'), 'placeholder' => __('Your name', 'kitsune-ai-platform'), 'required' => true),
                            array('id' => 'field_email', 'type' => 'email', 'label' => __('Email', 'kitsune-ai-platform'), 'placeholder' => __('your@email.com', 'kitsune-ai-platform'), 'required' => true),
                            array('id' => 'field_phone', 'type' => 'tel', 'label' => __('Phone', 'kitsune-ai-platform'), 'placeholder' => __('+1 (555) 000-0000', 'kitsune-ai-platform'), 'required' => false),
                            array('id' => 'field_interest', 'type' => 'select', 'label' => __('Interest', 'kitsune-ai-platform'), 'placeholder' => __('Select your interest', 'kitsune-ai-platform'), 'options' => array(__('Product Demo', 'kitsune-ai-platform'), __('Pricing', 'kitsune-ai-platform'), __('Partnership', 'kitsune-ai-platform'), __('Other', 'kitsune-ai-platform')), 'required' => true),
                        ),
                        'settings' => array()
                    )
                ),
                array(
                    'id' => 'support-ticket',
                    'name' => __('Support Ticket Form', 'kitsune-ai-platform'),
                    'description' => __('Create support tickets with priority and category selection.', 'kitsune-ai-platform'),
                    'config' => array(
                        'fields' => array(
                            array('id' => 'field_email', 'type' => 'email', 'label' => __('Email', 'kitsune-ai-platform'), 'placeholder' => __('your@email.com', 'kitsune-ai-platform'), 'required' => true),
                            array('id' => 'field_category', 'type' => 'select', 'label' => __('Category', 'kitsune-ai-platform'), 'options' => array(__('Technical Issue', 'kitsune-ai-platform'), __('Billing', 'kitsune-ai-platform'), __('Feature Request', 'kitsune-ai-platform'), __('General Inquiry', 'kitsune-ai-platform')), 'required' => true),
                            array('id' => 'field_priority', 'type' => 'radio', 'label' => __('Priority', 'kitsune-ai-platform'), 'options' => array(__('Low', 'kitsune-ai-platform'), __('Medium', 'kitsune-ai-platform'), __('High', 'kitsune-ai-platform'), __('Critical', 'kitsune-ai-platform')), 'required' => true),
                            array('id' => 'field_subject', 'type' => 'text', 'label' => __('Subject', 'kitsune-ai-platform'), 'placeholder' => __('Brief description of the issue', 'kitsune-ai-platform'), 'required' => true),
                            array('id' => 'field_description', 'type' => 'textarea', 'label' => __('Description', 'kitsune-ai-platform'), 'placeholder' => __('Provide details about your issue...', 'kitsune-ai-platform'), 'required' => true),
                        ),
                        'settings' => array()
                    )
                ),
            )
        );

        if ($type && isset($templates[$type])) {
            wp_send_json_success($templates[$type]);
        } else {
            wp_send_json_success($templates);
        }
    }

    /**
     * AJAX: Install Template
     */
    public function ajax_install_template() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        // Mock install success
        wp_send_json_success(array('message' => __('Template installed successfully', 'kitsune-ai-platform')));
    }

    /**
     * AJAX: Get Webhooks
     */
    public function ajax_get_webhooks() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        $webhooks = get_option('kitsune_ai_platform_webhooks', array());
        wp_send_json_success(array_values($webhooks));
    }

    /**
     * AJAX: Create Webhook
     */
    public function ajax_create_webhook() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        $data = $this->get_post_payload('data', array());
        if (!$data) {
            $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }

        $webhooks = get_option('kitsune_ai_platform_webhooks', array());
        $url = esc_url_raw($data['url'] ?? '');
        if (empty($url)) {
            wp_send_json_error(array('message' => __('Webhook URL is required', 'kitsune-ai-platform')));
            return;
        }

        $validated_url = Kitsune_AI_Platform_Webhook_Dispatcher::validate_webhook_url($url);
        if (is_wp_error($validated_url)) {
            wp_send_json_error(array('message' => $validated_url->get_error_message()));
            return;
        }

        $max_id = 0;
        foreach ($webhooks as $existing) {
            $max_id = max($max_id, intval($existing['id'] ?? 0));
        }
        $new_id = $max_id + 1;
        
        $allowed_events = class_exists('Kitsune_AI_Platform_Webhook_Events') ? Kitsune_AI_Platform_Webhook_Events::all() : array();
        $events = isset($data['events']) ? (array) $data['events'] : array();
        if (!empty($allowed_events)) {
            $events = array_values(array_intersect($events, $allowed_events));
        }
        if (empty($events)) {
            $events = array(class_exists('Kitsune_AI_Platform_Webhook_Events') ? Kitsune_AI_Platform_Webhook_Events::CONVERSATION_CREATED : 'conversation.created');
        }

        $webhook = array(
            'id' => $new_id,
            'name' => sanitize_text_field($data['name'] ?? 'Webhook'),
            'url' => $validated_url,
            'events' => $events,
            'active' => true,
            'created_at' => current_time('mysql')
        );

        $webhooks[] = $webhook;
        update_option('kitsune_ai_platform_webhooks', $webhooks);
        update_option('kitsune_ai_platform_last_webhook_url', $validated_url);

        wp_send_json_success($webhook);
    }

    /**
     * AJAX: Delete Webhook
     */
    public function ajax_delete_webhook() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        
        $webhooks = get_option('kitsune_ai_platform_webhooks', array());
        foreach ($webhooks as $key => $webhook) {
            if ($webhook['id'] == $id) {
                unset($webhooks[$key]);
                break;
            }
        }
        update_option('kitsune_ai_platform_webhooks', array_values($webhooks));

        wp_send_json_success(array('message' => __('Webhook deleted', 'kitsune-ai-platform')));
    }

    /**
     * AJAX: Test Webhook
     */
    public function ajax_test_webhook() {
        if (!$this->verify_admin_request('integrations')) {
            return;
        }

        // Mock test
        wp_send_json_success(array('message' => __('Test event sent successfully', 'kitsune-ai-platform')));
    }

}
