<?php
// ============================================================
//  Shared bootstrap for cron scripts in cron/*.php
// ============================================================
//
//  Each cron script requires this file at the top. It:
//    1. Enforces CLI-or-secret-key access (guards against public triggering)
//    2. Opens a row in cron_runs; returns its ID for later finalisation
//    3. Exposes cron_finish(id, outcome, rows, detail)
//
//  Usage inside a cron script:
//     require_once __DIR__ . '/_bootstrap.php';
//     $run_id = cron_begin('renewal-reminder');
//     ... do the work ...
//     cron_finish($run_id, 'ok', $rows_processed);
//
// ============================================================

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mailchimp.php';

/** Gate: allow from CLI, or require ?secret= matching CRON_SECRET */
function cron_authenticate(): void {
    if (PHP_SAPI === 'cli') return;

    $secret = $_GET['secret'] ?? '';
    if (!defined('CRON_SECRET') || CRON_SECRET === '' || CRON_SECRET === 'CHANGE-ME-long-random-string-here') {
        http_response_code(503);
        exit('Cron not configured. Set CRON_SECRET in config.php.');
    }

    if (!hash_equals(CRON_SECRET, $secret)) {
        // Sleep a bit to slow down brute-forcing
        usleep(300000);
        http_response_code(403);
        exit('Forbidden');
    }

    // Emit plain text so status is legible in a browser
    header('Content-Type: text/plain');
}

/** Open a cron_runs row. Returns the inserted ID. */
function cron_begin(string $job_name): int {
    cron_authenticate();
    echo "[" . date('Y-m-d H:i:s') . "] $job_name starting...\n";
    return db_insert('cron_runs', [
        'job_name'   => $job_name,
        'outcome'    => 'running',
    ]);
}

/** Mark a cron run done. */
function cron_finish(int $id, string $outcome, int $rows = 0, ?string $detail = null): void {
    db_exec(
        'UPDATE cron_runs
            SET finished_at = NOW(), outcome = :o, rows_processed = :r, detail = :d
            WHERE id = :id',
        ['o' => $outcome, 'r' => $rows, 'd' => $detail, 'id' => $id]
    );
    echo "[" . date('Y-m-d H:i:s') . "] done ($outcome, $rows rows)\n";
}
