<?php

namespace App\Models;

use App\Core\Model;

class Site extends Model
{
    protected static string $table = 'sites';

    public static function findActive(): array
    {
        return self::where('is_active = 1', [], 'last_published_at ASC');
    }

    public static function findDueForPublishing(): array
    {
        $sql = "SELECT * FROM sites
                WHERE is_active = 1
                AND (
                    last_published_at IS NULL
                    OR DATE_ADD(last_published_at, INTERVAL publish_interval_hours HOUR) <= NOW()
                )
                ORDER BY last_published_at ASC";
        $stmt = self::db()->query($sql);
        return $stmt->fetchAll();
    }

    public static function updateLastPublished(int $id): void
    {
        self::update($id, ['last_published_at' => date('Y-m-d H:i:s')]);
    }

    public static function findNextDueForSeoSync(string $metricMonth): ?array
    {
        $sql = "SELECT s.*
                FROM sites s
                LEFT JOIN site_seo_metrics m
                    ON m.site_id = s.id
                    AND m.metric_month = :metric_month
                WHERE s.is_active = 1
                  AND (
                    m.id IS NULL
                    OR m.source_payload IS NULL
                    OR m.source_payload NOT LIKE '%\"dataforseo\"%'
                    OR m.source_payload LIKE '%\"dataforseo\":null%'
                  )
                ORDER BY s.id ASC
                LIMIT 1";

        $stmt = self::db()->prepare($sql);
        $stmt->execute(['metric_month' => $metricMonth]);
        $row = $stmt->fetch();

        return $row ?: null;
    }
}
