<?php
/**
 * Blog cron endpoint — generates one post per run.
 * Protect with the BLOG_CRON_TOKEN query parameter.
 *
 * Server crontab (Mon, Tue, Thu, Fri at 7am GMT):
 *   0 7 * * 1,2,4,5 curl -s "https://edutrack.oricnetwork.com/blog/cron.php?token=oric-blog-cron-b94f2c1e9a37" > /dev/null
 *
 * Or trigger manually from admin.php.
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/generator.php';

// Token gate
$token = trim($_GET['token'] ?? '');
if ($token !== BLOG_CRON_TOKEN) {
    http_response_code(403);
    blog_log('Cron: rejected request — wrong token from IP ' . ($_SERVER['REMOTE_ADDR'] ?? '?'));
    exit('Forbidden');
}

// Prevent simultaneous runs with a lock file
$lock = sys_get_temp_dir() . '/edutrack_blog_cron.lock';
$fp   = fopen($lock, 'c');
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
    blog_log('Cron: already running (lock held) — skipped.');
    exit('Already running');
}

try {
    blog_log('--- Cron run started ---');

    for ($i = 0; $i < POSTS_PER_RUN; $i++) {
        $slug = generate_and_save_post();
        blog_log("Published: " . BLOG_BASE_URL . "/post.php?slug={$slug}");
    }

    blog_log('--- Cron run complete ---');
    echo json_encode(['success' => true, 'message' => POSTS_PER_RUN . ' post(s) generated.']);

} catch (Throwable $e) {
    blog_log('Cron ERROR: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
} finally {
    flock($fp, LOCK_UN);
    fclose($fp);
}
