<?php
defined( 'ABSPATH' ) || exit;

class NASEO_Scheduler {

    public function __construct() {
        add_action( 'naseo_publish_cron', [ $this, 'run' ] );
        add_action( 'naseo_license_check', [ 'NASEO_License', 'validate' ] );
    }

    /**
     * Запускається щодня о 09:00 — доступно у Free
     */
    public function run(): void {
        // Перевіряємо частоту: twice_week = тільки пн (1) і чт (4)
        $frequency = get_option( 'naseo_publish_frequency', 'daily' );
        if ( $frequency === 'twice_week' ) {
            $dow = (int) gmdate( 'N' ); // 1=пн ... 7=нд
            if ( ! in_array( $dow, [ 1, 4 ], true ) ) {
                return; // не пн і не чт — пропускаємо
            }
        }

        $items = $this->get_pending_items( 1 );

        if ( empty( $items ) ) {
            NASEO_Logger::log( 'info', 'Cron: черга порожня.' );
            return;
        }

        foreach ( $items as $item ) {
            NASEO_Publisher::publish_item( $item );
        }
    }

    /**
     * Миттєва публікація N статей
     */
    public function run_now( int $limit = 1 ): array {
        $items     = $this->get_pending_items( $limit );
        $published = 0;

        foreach ( $items as $item ) {
            if ( NASEO_Publisher::publish_item( $item ) ) {
                $published++;
            }
        }

        return [
            'success' => true,
            'message' => sprintf( /* translators: %d is the number of published articles */ __( 'Опубліковано: %d статей.', 'nemynai-seo-autopilot' ), $published ),
            'count'   => $published,
        ];
    }

    private function get_pending_items( int $limit ): array {
        global $wpdb;
        $table = $wpdb->prefix . 'naseo_queue';
        $today = gmdate( 'Y-m-d' );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM `" . esc_sql( $table ) . "`
             WHERE status = 'pending'
             AND (scheduled_date IS NULL OR scheduled_date <= %s)
             ORDER BY scheduled_date ASC, id ASC
             LIMIT %d",
            $today,
            $limit
        ) );
    }

    /**
     * Статистика для дашборду
     */
    public static function get_stats(): array {
        global $wpdb;
        $table = $wpdb->prefix . 'naseo_queue';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
        $stats = $wpdb->get_results(
            "SELECT status, COUNT(*) as cnt FROM `" . esc_sql( $table ) . "` GROUP BY status",
            OBJECT_K
        );

        return [
            'pending'    => (int) ( $stats['pending']->cnt ?? 0 ),
            'processing' => (int) ( $stats['processing']->cnt ?? 0 ),
            'published'  => (int) ( $stats['published']->cnt ?? 0 ),
            'error'      => (int) ( $stats['error']->cnt ?? 0 ),
        ];
    }
}
