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

/**
 * Form Model
 *
 * Database operations for AI forms using CPT.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes/models
 */

class Kitsune_AI_Platform_Form_Model extends Kitsune_AI_Platform_Base_Model {

    const POST_TYPE = 'kitsune_ai_form';

    /**
     * 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(
            'submissions_count' => 0,
            'conversion_rate'   => 0.00,
        );
    }

    /**
     * Create a new form
     *
     * @param array $data Form 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 form
     *
     * @param int   $id   Post ID
     * @param array $data Form 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', __('Form 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 form
     *
     * @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', __('Form not found', 'kitsune-ai-platform'));
        }

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

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

    /**
     * Update submission count
     *
     * @param int $id Post ID
     */
    public function update_submission_count($id) {
        $count = (int) get_post_meta($id, $this->get_meta_prefix() . 'submissions_count', true);
        update_post_meta($id, $this->get_meta_prefix() . 'submissions_count', $count + 1);
    }

    /**
     * Get form submissions from the database.
     *
     * @param int $form_id Post ID (0 = all forms).
     * @param int $per_page Number of results per page.
     * @param int $offset   Offset for pagination.
     * @return array Submissions with data decoded.
     */
    public function get_submissions( $form_id = 0, $per_page = 20, $offset = 0 ) {
        global $wpdb;
        $table = $wpdb->prefix . 'kitsune_ai_platform_form_submissions';

        if ( $form_id ) {
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} WHERE form_id = %d ORDER BY created_at DESC LIMIT %d OFFSET %d",
                    $form_id,
                    $per_page,
                    $offset
                ),
                ARRAY_A
            );
        } else {
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} ORDER BY created_at DESC LIMIT %d OFFSET %d",
                    $per_page,
                    $offset
                ),
                ARRAY_A
            );
        }

        if ( ! is_array( $results ) ) {
            return array();
        }

        foreach ( $results as &$row ) {
            $row['id']      = (int) $row['id'];
            $row['form_id'] = (int) $row['form_id'];
            $row['user_id'] = isset( $row['user_id'] ) ? (int) $row['user_id'] : null;
            $decoded = isset( $row['data'] ) ? json_decode( $row['data'], true ) : array();
            $row['data'] = is_array( $decoded ) ? $decoded : array();
            if ( ! empty( $row['ai_result'] ) ) {
                $ai = json_decode( $row['ai_result'], true );
                $row['ai_result'] = is_array( $ai ) ? $ai : null;
            } else {
                $row['ai_result'] = null;
            }
        }
        unset( $row );

        return $results;
    }

    /**
     * Count submissions for a form (or all forms).
     *
     * @param int $form_id Post ID (0 = all forms).
     * @return int
     */
    public function count_submissions( $form_id = 0 ) {
        global $wpdb;
        $table = $wpdb->prefix . 'kitsune_ai_platform_form_submissions';

        if ( $form_id ) {
            return (int) $wpdb->get_var(
                $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE form_id = %d", $form_id )
            );
        }
        return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i", $table ) );
    }

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

        $total_submissions = $wpdb->get_var(
            $wpdb->prepare("SELECT COUNT(*) FROM {$submissions_table} WHERE form_id = %d", $id)
        );

        return array(
            'total_submissions' => (int) $total_submissions,
            'conversion_rate'   => 0.0, // TODO: Implement views tracking to calculate this
        );
    }

    /**
     * Format a WP_Post object as form data
     *
     * @param WP_Post $post Post object
     * @return object Formatted form 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,
            'submissions_count'   => (int) get_post_meta($post->ID, $this->get_meta_prefix() . 'submissions_count', true),
            'conversion_rate'     => (float) get_post_meta($post->ID, $this->get_meta_prefix() . 'conversion_rate', true),
            'created_at'          => $post->post_date,
            'updated_at'          => $post->post_modified,
        );
    }
}
