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

/**
 * Content Model
 *
 * Database operations for AI-generated content using Custom Post Type
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/models
 */

class Kitsune_AI_Platform_Content_Model extends Kitsune_AI_Platform_Base_Model {

    const POST_TYPE = 'kitsune_ai_content';

    /**
     * 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(
            'type'           => '',
            'prompt'         => '',
            'model'          => '',
            'tokens_used'    => 0,
            'cost'           => 0.0000,
            'linked_post_id' => null,
        );
    }

    /**
     * Create a new content item
     *
     * @param array $data Content 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['title']) ? sanitize_text_field($data['title']) : '',
            'post_content' => isset($data['generated_content']) ? wp_kses_post($data['generated_content']) : '',
            'post_status'  => isset($data['status']) ? sanitize_text_field($data['status']) : 'draft',
            '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 content item
     *
     * @param int   $id   Post ID
     * @param array $data Content 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()) {
            return new WP_Error('not_found', __('Content not found', 'kitsune-ai-platform'));
        }

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

        if (isset($data['title'])) {
            $post_data['post_title'] = sanitize_text_field($data['title']);
        }
        if (isset($data['generated_content'])) {
            $post_data['post_content'] = wp_kses_post($data['generated_content']);
        }
        if (isset($data['status'])) {
            $post_data['post_status'] = sanitize_text_field($data['status']);
        }

        $result = wp_update_post($post_data, true);

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

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

        return $id;
    }

    /**
     * Save meta fields for a content item
     *
     * In addition to default meta, handles mapping 'post_id' to 'linked_post_id'
     *
     * @param int   $post_id Post ID
     * @param array $data    Data array
     */
    protected function save_meta($post_id, $data) {
        // Map old field names to new
        if (isset($data['post_id'])) {
            $data['linked_post_id'] = $data['post_id'];
        }
        
        parent::save_meta($post_id, $data);
    }

    /**
     * Format a WP_Post object as content data
     *
     * @param WP_Post $post Post object
     * @return object Formatted content object
     */
    protected function format_post($post) {
        return (object) array(
            'id'                => $post->ID,
            'title'             => $post->post_title,
            'generated_content' => $post->post_content,
            'type'              => get_post_meta($post->ID, $this->get_meta_prefix() . 'type', true),
            'prompt'            => get_post_meta($post->ID, $this->get_meta_prefix() . 'prompt', true),
            'model'             => get_post_meta($post->ID, $this->get_meta_prefix() . 'model', true),
            'tokens_used'       => (int) get_post_meta($post->ID, $this->get_meta_prefix() . 'tokens_used', true),
            'cost'              => (float) get_post_meta($post->ID, $this->get_meta_prefix() . 'cost', true),
            'post_id'           => get_post_meta($post->ID, $this->get_meta_prefix() . 'linked_post_id', true),
            'status'            => $post->post_status,
            'user_id'           => $post->post_author,
            'created_at'        => $post->post_date,
            'updated_at'        => $post->post_modified,
        );
    }
}
