<?php

/**
 * Content history management for AI Magic plugin
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.7
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */

/**
 * Manages content generation history
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 * @author     AI Magic <info@insya.com>
 */
class Ai_Magic_History
{
    /**
     * Save generation to history
     *
     * @since    1.0.7
     * @param    array    $data  History data
     * @return   int|false       History ID or false on failure
     */
    public static function save($data)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        $result = $wpdb->insert(
            $table,
            array(
                'user_id' => get_current_user_id(),
                'post_id' => isset($data['post_id']) ? $data['post_id'] : null,
                'title' => sanitize_text_field($data['title']),
                'prompt' => $data['prompt'],
                'content' => $data['content'],
                'model' => sanitize_text_field($data['model']),
                'tokens_used' => intval($data['tokens_used']),
                'generation_time' => floatval($data['generation_time']),
                'cost' => isset($data['cost']) ? floatval($data['cost']) : 0,
                'is_favorite' => 0,
                'created_at' => current_time('mysql')
            ),
            array('%d', '%d', '%s', '%s', '%s', '%s', '%d', '%f', '%f', '%d', '%s')
        );

        return $result ? $wpdb->insert_id : false;
    }

    /**
     * Get history entries
     *
     * @since    1.0.7
     * @param    array    $args  Query arguments
     * @return   array           Array of history objects
     */
    public static function get_history($args = array())
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        $defaults = array(
            'user_id' => null,
            'limit' => 20,
            'offset' => 0,
            'favorites_only' => false,
            'date_from' => null,
            'date_to' => null,
            'order_by' => 'created_at',
            'order' => 'DESC'
        );

        $args = wp_parse_args($args, $defaults);

        $where = array();
        $where_values = array();

        if ($args['user_id']) {
            $where[] = 'user_id = %d';
            $where_values[] = $args['user_id'];
        }

        if ($args['favorites_only']) {
            $where[] = 'is_favorite = 1';
        }

        if ($args['date_from']) {
            $where[] = 'created_at >= %s';
            $where_values[] = $args['date_from'];
        }

        if ($args['date_to']) {
            $where[] = 'created_at <= %s';
            $where_values[] = $args['date_to'];
        }

        $where_clause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

        $query = "SELECT * FROM $table $where_clause ORDER BY {$args['order_by']} {$args['order']} LIMIT %d OFFSET %d";
        $where_values[] = $args['limit'];
        $where_values[] = $args['offset'];

        if (!empty($where_values)) {
            $query = $wpdb->prepare($query, $where_values);
        }

        return $wpdb->get_results($query);
    }

    /**
     * Get history entry by ID
     *
     * @since    1.0.7
     * @param    int    $history_id  History ID
     * @return   object|null         History object or null
     */
    public static function get($history_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE id = %d",
            $history_id
        ));
    }

    /**
     * Toggle favorite status
     *
     * @since    1.0.7
     * @param    int     $history_id  History ID
     * @return   bool                 Success status
     */
    public static function toggle_favorite($history_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        $current = $wpdb->get_var($wpdb->prepare(
            "SELECT is_favorite FROM $table WHERE id = %d",
            $history_id
        ));

        $new_value = $current ? 0 : 1;

        return $wpdb->update(
            $table,
            array('is_favorite' => $new_value),
            array('id' => $history_id),
            array('%d'),
            array('%d')
        ) !== false;
    }

    /**
     * Delete history entry
     *
     * @since    1.0.7
     * @param    int     $history_id  History ID
     * @return   bool                 Success status
     */
    public static function delete($history_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        return $wpdb->delete($table, array('id' => $history_id), array('%d')) !== false;
    }

    /**
     * Get total count
     *
     * @since    1.0.7
     * @param    int     $user_id    Optional user ID filter
     * @param    string  $date_from  Optional date from filter
     * @param    string  $date_to    Optional date to filter
     * @return   int                 Total count
     */
    public static function get_count($user_id = null, $date_from = null, $date_to = null)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        $where = array();
        $where_values = array();

        if ($user_id) {
            $where[] = 'user_id = %d';
            $where_values[] = $user_id;
        }

        if ($date_from) {
            $where[] = 'created_at >= %s';
            $where_values[] = $date_from;
        }

        if ($date_to) {
            $where[] = 'created_at <= %s';
            $where_values[] = $date_to;
        }

        $where_clause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
        $query = "SELECT COUNT(*) FROM $table $where_clause";

        if (!empty($where_values)) {
            return $wpdb->get_var($wpdb->prepare($query, $where_values));
        }

        return $wpdb->get_var($query);
    }

    /**
     * Get total cost
     *
     * @since    1.0.9
     * @param    int     $user_id    Optional user ID filter
     * @param    string  $date_from  Optional date from filter
     * @param    string  $date_to    Optional date to filter
     * @return   float               Total cost
     */
    public static function get_total_cost($user_id = null, $date_from = null, $date_to = null)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        // Check if cost column exists to avoid errors during migration
        $col_exists = $wpdb->get_results("SHOW COLUMNS FROM $table LIKE 'cost'");
        if (empty($col_exists)) {
            return 0.0;
        }

        $where = array();
        $where_values = array();

        if ($user_id) {
            $where[] = 'user_id = %d';
            $where_values[] = $user_id;
        }

        if ($date_from) {
            $where[] = 'created_at >= %s';
            $where_values[] = $date_from;
        }

        if ($date_to) {
            $where[] = 'created_at <= %s';
            $where_values[] = $date_to;
        }

        $where_clause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
        $query = "SELECT SUM(cost) FROM $table $where_clause";

        if (!empty($where_values)) {
            return (float) $wpdb->get_var($wpdb->prepare($query, $where_values));
        }

        return (float) $wpdb->get_var($query);
    }

    /**
     * Search history
     *
     * @since    1.0.7
     * @param    string    $search_term  Search term
     * @param    int       $limit        Results limit
     * @return   array                   Array of history objects
     */
    public static function search($search_term, $limit = 20)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_history';

        $search_term = '%' . $wpdb->esc_like($search_term) . '%';

        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE title LIKE %s OR prompt LIKE %s OR content LIKE %s ORDER BY created_at DESC LIMIT %d",
            $search_term,
            $search_term,
            $search_term,
            $limit
        ));
    }
}
