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

/**
 * Chatbot Model
 *
 * Database operations for chatbots using Custom Post Type
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/models
 */

class Kitsune_AI_Platform_Chatbot_Model extends Kitsune_AI_Platform_Base_Model {

    /**
     * CPT slug for chatbots
     */
    const POST_TYPE = 'kitsune_ai_chatbot';

    /**
     * Get post type slug.
     *
     * @return string
     */
    protected function get_post_type() {
        return self::POST_TYPE;
    }

    /**
     * Get default meta fields.
     *
     * @return array
     */
    protected function get_default_meta() {
        return array(
            'avatar'              => 'ChatDotRound',
            'conversations_count' => 0,
            'satisfaction_score'  => 0.00,
        );
    }

    /**
     * Create a new chatbot
     *
     * @param array $data Chatbot data
     * @return int|WP_Error Post ID on success, WP_Error on failure
     */
    public function create($data) {
        $post_data = array(
            'post_type'    => $this->get_post_type(),
            'post_title'   => isset($data['name']) ? sanitize_text_field($data['name']) : '',
            'post_excerpt' => isset($data['description']) ? sanitize_textarea_field($data['description']) : '',
            'post_content' => isset($data['config']) ? (is_array($data['config']) ? wp_json_encode($data['config']) : $data['config']) : '{}',
            'post_status'  => (isset($data['status']) && $data['status'] === 'inactive') ? 'draft' : 'publish',
            'post_author'  => isset($data['user_id']) ? intval($data['user_id']) : get_current_user_id(),
        );

        $post_id = wp_insert_post($post_data, true);

        if (is_wp_error($post_id)) {
            return $post_id;
        }

        // Save meta fields
        $this->save_meta($post_id, $data);

        return $post_id;
    }

    /**
     * Update an existing chatbot
     *
     * @param int   $id   Post ID
     * @param array $data Chatbot data
     * @return int|WP_Error Post ID on success, WP_Error on failure
     */
    public function update($id, $data) {
        $post = get_post($id);
        
        if (!$post || $post->post_type !== $this->get_post_type()) {
            /* translators: %s: Chatbot not found error */
            return new WP_Error('not_found', __('Chatbot not found', 'kitsune-ai-platform'));
        }

        $post_data = array('ID' => $id);

        if (isset($data['name'])) {
            $post_data['post_title'] = sanitize_text_field($data['name']);
        }
        if (isset($data['description'])) {
            $post_data['post_excerpt'] = sanitize_textarea_field($data['description']);
        }
        if (isset($data['config'])) {
            $post_data['post_content'] = is_array($data['config']) ? wp_json_encode($data['config']) : $data['config'];
        }
        if (isset($data['status'])) {
            $post_data['post_status'] = ($data['status'] === 'inactive') ? 'draft' : 'publish';
        }

        $result = wp_update_post($post_data, true);

        if (is_wp_error($result)) {
            return $result;
        }

        // Update meta fields
        $this->save_meta($id, $data);

        return $id;
    }

    /**
     * Duplicate a chatbot
     *
     * @param int $id Post ID to duplicate
     * @return int|WP_Error New post ID on success, WP_Error on failure
     */
    public function duplicate($id) {
        $original = $this->get($id);
        
        if (!$original) {
            return new WP_Error('not_found', __('Chatbot not found', 'kitsune-ai-platform'));
        }

        $data = array(
            'name'               => sprintf(
                /* translators: %s: Original chatbot name. */
                __('%s (Copy)', 'kitsune-ai-platform'),
                $original->name
            ),
            'description'        => $original->description,
            'config'             => $original->config,
            'status'             => 'inactive',
            'avatar'             => $original->avatar,
            'user_id'            => get_current_user_id(),
        );

        return $this->create($data);
    }

    /**
     * Get chatbot statistics
     *
     * @param int $id Post ID
     * @return array Statistics array
     */
    public function get_stats($id) {
        global $wpdb;
        $conversations_table = $wpdb->prefix . 'kitsune_ai_platform_conversations';

        return array(
            'total_conversations' => $wpdb->get_var(
                $wpdb->prepare("SELECT COUNT(*) FROM {$conversations_table} WHERE chatbot_id = %d", $id)
            ),
            'avg_satisfaction' => $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT AVG(satisfaction_rating) FROM {$conversations_table} WHERE chatbot_id = %d", $id
                )
            ),
        );
    }

    /**
     * Format a WP_Post object as chatbot data
     *
     * @param WP_Post $post Post object
     * @return object Formatted chatbot object
     */
    protected function format_post($post) {
        $config = json_decode($post->post_content, true);
        if (!is_array($config)) {
            $config = array();
        }

        return (object) array(
            'id'                  => $post->ID,
            'name'                => $post->post_title,
            'description'         => $post->post_excerpt,
            'config'              => $config,
            'status'              => ($post->post_status === 'publish') ? 'active' : 'inactive',
            'user_id'             => $post->post_author,
            'avatar'              => get_post_meta($post->ID, $this->get_meta_prefix() . 'avatar', true) ?: 'ChatDotRound',
            'conversations_count' => (int) get_post_meta($post->ID, $this->get_meta_prefix() . 'conversations_count', true),
            'satisfaction_score'  => (float) get_post_meta($post->ID, $this->get_meta_prefix() . 'satisfaction_score', true),
            'created_at'          => $post->post_date,
            'updated_at'          => $post->post_modified,
        );
    }
}
