<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-gap-topic-queue.php
// Description: Gap topic queue -- push/pop/count/getAll/delete for blog generator integration - NUCLEAR+++
// Last Edited: 2026-05-18
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class GapTopicQueue
{
    public const MAX_QUEUE = 10;
    public const STALE_DAYS = 30;

    // --------------------------------------------------
    // Push a topic onto the queue.
    // Returns the new count on success, or null if the queue is full
    // or the topic is a duplicate.
    // --------------------------------------------------
    public static function push(string $topic, string $competitor_url = ''): ?int
    {
        $topic = trim($topic);
        if ($topic === '') {
            return null;
        }

        global $wpdb;
        $table = $wpdb->prefix . 'amai_gap_topic_queue';

        $current = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}`");
        if ($current >= self::MAX_QUEUE) {
            return null;
        }

        // Reject duplicate topic text (case-insensitive)
        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM `{$table}` WHERE LOWER(topic) = LOWER(%s) LIMIT 1",
            $topic
        ));
        if ($exists !== null) {
            return null;
        }

        $now = gmdate('Y-m-d H:i:s');
        $wpdb->insert($table, [
            'topic'          => $topic,
            'competitor_url' => $competitor_url,
            'queued_at'      => $now,
            'created_at'     => $now,
        ]);

        if ($wpdb->insert_id <= 0) {
            return null;
        }

        return (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}`");
    }

    // --------------------------------------------------
    // Pop the oldest topic from the queue and return it.
    // Returns null if the queue is empty.
    // --------------------------------------------------
    public static function pop(): ?string
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_gap_topic_queue';

        $row = $wpdb->get_row(
            "SELECT id, topic FROM `{$table}` ORDER BY queued_at ASC, id ASC LIMIT 1",
            ARRAY_A
        );

        if (!is_array($row)) {
            return null;
        }

        $wpdb->delete($table, ['id' => (int) $row['id']]);

        return (string) $row['topic'];
    }

    // --------------------------------------------------
    // Return the current queue depth.
    // --------------------------------------------------
    public static function count(): int
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_gap_topic_queue';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") !== $table) {
            return 0;
        }
        return (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}`");
    }

    // --------------------------------------------------
    // Return all queued rows ordered oldest-first.
    // Each row: id, topic, competitor_url, queued_at, is_stale (bool)
    // --------------------------------------------------
    public static function getAll(): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_gap_topic_queue';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") !== $table) {
            return [];
        }

        $rows = $wpdb->get_results(
            "SELECT id, topic, competitor_url, queued_at FROM `{$table}` ORDER BY queued_at ASC, id ASC",
            ARRAY_A
        );

        if (!is_array($rows)) {
            return [];
        }

        $stale_threshold = time() - (self::STALE_DAYS * DAY_IN_SECONDS);

        foreach ($rows as &$row) {
            $queued_ts      = (int) strtotime((string) $row['queued_at']);
            $row['is_stale'] = $queued_ts > 0 && $queued_ts < $stale_threshold;
            $row['days_ago'] = $queued_ts > 0 ? (int) floor((time() - $queued_ts) / DAY_IN_SECONDS) : 0;
        }
        unset($row);

        return $rows;
    }

    // --------------------------------------------------
    // Delete a specific queued topic by ID.
    // --------------------------------------------------
    public static function delete(int $id): bool
    {
        if ($id <= 0) {
            return false;
        }
        global $wpdb;
        $table  = $wpdb->prefix . 'amai_gap_topic_queue';
        $result = $wpdb->delete($table, ['id' => $id]);
        return $result !== false && $result > 0;
    }
}