<?php
// app/database/ArticleGenerationManager.php

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Article Generation Manager
 * 
 * Handles database operations for article generations
 */
class ContentCraftAI_ArticleGenerationManager
{
    /**
     * Singleton instance of the class
     * @var ContentCraftAI_ArticleGenerationManager|null
     */
    private static $instance = null;

    /**
     * Name of the generations database table
     * @var string
     */
    private $table_name;

    /**
     * Get the singleton instance of the class
     * 
     * @return ContentCraftAI_ArticleGenerationManager The singleton instance
     */
    public static function get_instance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Private constructor to prevent direct instantiation
     * Sets up table names
     */
    private function __construct()
    {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'content_craft_ai_generations';
    }

    /**
     * Add a new generation record to the database
     * 
     * @param string $queue_id Unique identifier for the generation queue
     * @param array  $data     Generation data including title, word count, and other parameters
     * 
     * @return bool|int False on failure, number of rows affected on success
     */
    public function add_generation($queue_id, $data)
    {
        global $wpdb;
        return $wpdb->insert(
            $this->table_name,
            [
                'queue_id' => $queue_id,
                'title' => $data['title'],
                'word_count' => $data['wordCount'],
                'created_at' => current_time('mysql'),
                'user_id' => get_current_user_id(),
                'category' => $data['category'] ?? null,
                'parameters' => json_encode($data),
                'status' => 'pending'
            ]
        );
    }

    /**
     * Update the status of a generation
     * 
     * @param string   $queue_id  Queue identifier of the generation to update
     * @param string   $status    New status value (pending, processing, completed, failed)
     * @param int|null $post_id   WordPress post ID if the generation was published
     * 
     * @return bool|int False on failure, number of rows affected on success
     */
    public function update_generation_status($queue_id, $status, $post_id = null)
    {
        global $wpdb;

        $data = [
            'status' => $status
        ];

        $format = ['%s']; // status

        if ($status === 'completed' || $status === 'failed') {
            $data['completed_at'] = current_time('mysql');
            $format[] = '%s'; // completed_at
        }

        if ($post_id) {
            $data['post_id'] = $post_id;
            $format[] = '%d'; // post_id
        }

        return $wpdb->update(
            $this->table_name,
            $data,
            ['queue_id' => $queue_id],
            $format,
            ['%s'] // queue_id format
        );
    }

    /**
     * Get a generation record by its queue ID
     * 
     * @param string $queue_id Queue identifier to look up
     * 
     * @return object|null Database row object or null if not found
     */
    public function get_generation_by_queue_id($queue_id)
    {
        global $wpdb;
        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$this->table_name} WHERE queue_id = %s",
                $queue_id
            )
        );
    }

    /**
     * Get pending or processing article generations
     * 
     * @param int $limit Maximum number of pending generations to retrieve
     * 
     * @return array Array of pending generation records
     */
    public function get_pending_generations($limit = 10)
    {
        global $wpdb;
        return $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$this->table_name} 
                 WHERE status IN ('pending', 'processing') 
                 AND type = 'article'
                 ORDER BY created_at ASC
                 LIMIT %d",
                $limit
            )
        );
    }
}
