#!/usr/bin/env php
<?php
/**
 * Excellent Blog - Automated Tasks
 * This script runs hourly to perform automated crawling and publishing
 */

// Set the working directory
chdir(dirname(__DIR__));

// Include configuration
require_once 'config/config.php';

echo "[" . date('Y-m-d H:i:s') . "] Starting automated tasks...\n";

try {
    // Initialize classes
    $crawler = new Crawler();
    $publisher = new Publisher();
    $article = new Article();

    // Task 1: Crawl external sources for new content
    echo "[" . date('Y-m-d H:i:s') . "] Starting content crawling...\n";

    $crawlSuccess = $crawler->crawlSources();
    if ($crawlSuccess) {
        echo "[" . date('Y-m-d H:i:s') . "] Content crawling completed successfully\n";
    } else {
        echo "[" . date('Y-m-d H:i:s') . "] Content crawling encountered issues\n";
    }

    // Task 2: Publish recent external articles to international platforms
    echo "[" . date('Y-m-d H:i:s') . "] Starting international publishing...\n";

    // Get recently published external articles that haven't been published yet
    $recentArticles = getRecentUnpublishedArticles();
    $publishedCount = 0;

    foreach ($recentArticles as $articleData) {
        if ($publisher->publishToExternalPlatforms($articleData['id'])) {
            $publishedCount++;
            echo "[" . date('Y-m-d H:i:s') . "] Published article: {$articleData['title']}\n";
        }

        // Add small delay to avoid overwhelming APIs
        sleep(2);
    }

    echo "[" . date('Y-m-d H:i:s') . "] Published {$publishedCount} articles to international platforms\n";

    // Task 3: Retry failed publishing attempts
    echo "[" . date('Y-m-d H:i:s') . "] Retrying failed publishing attempts...\n";

    $retryCount = $publisher->retryFailedPublishing();
    echo "[" . date('Y-m-d H:i:s') . "] Retried {$retryCount} failed publishing attempts\n";

    // Task 4: Cleanup old data (optional)
    echo "[" . date('Y-m-d H:i:s') . "] Running cleanup tasks...\n";
    cleanupOldChatMessages();
    echo "[" . date('Y-m-d H:i:s') . "] Cleanup completed\n";

    echo "[" . date('Y-m-d H:i:s') . "] All automated tasks completed successfully!\n";

} catch (Exception $e) {
    echo "[" . date('Y-m-d H:i:s') . "] ERROR: " . $e->getMessage() . "\n";
    error_log("Auto-tasks error: " . $e->getMessage());
}

/**
 * Get recent external articles that haven't been published to platforms yet
 */
function getRecentUnpublishedArticles() {
    try {
        $database = new Database();
        $db = $database->getConnection();

        $query = "SELECT a.id, a.title, a.published_at
                  FROM articles a
                  WHERE a.type = 'external'
                    AND a.status = 'published'
                    AND a.published_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                    AND a.id NOT IN (
                        SELECT DISTINCT pa.article_id
                        FROM published_articles pa
                        WHERE pa.status = 'published'
                    )
                  ORDER BY a.published_at DESC
                  LIMIT 10";

        $stmt = $db->prepare($query);
        $stmt->execute();

        return $stmt->fetchAll();
    } catch (Exception $e) {
        error_log("Get recent unpublished articles error: " . $e->getMessage());
        return [];
    }
}

/**
 * Clean up old chat messages to prevent database bloat
 */
function cleanupOldChatMessages() {
    try {
        $database = new Database();
        $db = $database->getConnection();

        // Delete chat messages older than 30 days
        $query = "DELETE FROM chat_messages WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)";
        $stmt = $db->prepare($query);
        $deleted = $stmt->execute();

        if ($deleted) {
            echo "[" . date('Y-m-d H:i:s') . "] Cleaned up old chat messages\n";
        }

        return $deleted;
    } catch (Exception $e) {
        error_log("Cleanup chat messages error: " . $e->getMessage());
        return false;
    }
}
?>