<?php
// app/database/ScheduledArticleManager.php

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

/**
 * Scheduled Article Manager
 * 
 * Handles operations specific to scheduled article generations
 */
class ContentCraftAI_ScheduledArticleManager
{
    /**
     * Singleton instance of the class
     * @var ContentCraftAI_ScheduledArticleManager|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_ScheduledArticleManager 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 scheduled article generation to the database
     * 
     * @param string $queue_id      Unique identifier for the generation queue
     * @param string $title         Title of the article to generate
     * @param string $scheduled_time MySQL datetime string for when to generate the article
     * @param array  $parameters    Generation parameters (keywords, settings, etc.)
     * @param int    $user_id       WordPress user ID of the article owner
     * 
     * @return bool|int False on failure, number of rows affected on success
     */
    public function add_scheduled_generation($queue_id, $title, $scheduled_time, $parameters, $user_id)
    {
        global $wpdb;

        // Convert the scheduled time to UTC for storage if needed
        try {
            // Get user timezone preference from settings
            $timezone = get_option('timezone_string', 'UTC');

            // Store the original timezone in parameters for reference
            $parameters['original_timezone'] = $timezone;
        } catch (Exception $e) {
            // error_log('Content Craft AI: Error handling timezone: ' . $e->getMessage());
            // Fallback to using the time as provided
        }

        return $wpdb->insert(
            $this->table_name,
            [
                'queue_id' => $queue_id,
                'title' => $title,
                'type' => 'article',
                'status' => 'scheduled',
                'created_at' => current_time('mysql'),
                'user_id' => $user_id,
                'parameters' => json_encode($parameters),
                'scheduled_time' => $scheduled_time,
                'is_scheduled' => 1,
                'category' => $parameters['category'] ?? null,
                'word_count' => $parameters['wordCount'] ?? null
            ],
            [
                '%s', // queue_id
                '%s', // title
                '%s', // type
                '%s', // status
                '%s', // created_at
                '%d', // user_id
                '%s', // parameters
                '%s', // scheduled_time
                '%d', // is_scheduled
                '%d', // category
                '%d'  // word_count
            ]
        );
    }

    /**
     * Get scheduled generations that are due to be processed
     * 
     * @param int $limit Maximum number of scheduled generations to retrieve
     * 
     * @return array Array of scheduled generation records
     */
    public function get_scheduled_generations($limit = 10)
    {
        global $wpdb;

        // Get current UTC time for comparison
        $currentUtcTime = gmdate('Y-m-d H:i:s');

        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name} 
             WHERE status = 'scheduled' 
             AND is_scheduled = 1
             AND scheduled_time <= %s 
             ORDER BY scheduled_time ASC 
             LIMIT %d",
            $currentUtcTime,
            $limit
        ));
    }

    /**
     * Get scheduled generations that are due to be processed
     * Alias for get_scheduled_generations for better naming
     * 
     * @param int $limit Maximum number of scheduled generations to retrieve
     * 
     * @return array Array of scheduled generation records
     */
    public function get_scheduled_generations_due($limit = 10)
    {
        return $this->get_scheduled_generations($limit);
    }

    /**
     * Get a scheduled generation by queue_id
     * 
     * @param string $queue_id Unique identifier for the generation queue
     * 
     * @return object|null The scheduled generation record or null if not found
     */
    public function get_scheduled_generation_by_queue_id($queue_id)
    {
        global $wpdb;

        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$this->table_name} 
             WHERE queue_id = %s 
             AND is_scheduled = 1",
            $queue_id
        ));
    }
}
