<?php

declare(strict_types=1);

/**
 * bin/process_recurring_campaigns.php
 *
 * Run once daily. Finds every recurring campaign parent
 * (is_recurring_parent = 1) and generates its next occurrence as a
 * real, individually-manageable child campaign (draft status — an
 * admin still reviews before it sends, matching how recurring
 * appointments work in Phase 3: real rows, never virtual/computed).
 */

require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/app/Core/Autoloader.php';

use App\Core\Autoloader;
use App\Core\Database;
use App\Core\Env;
use App\Services\CampaignService;

Autoloader::register(dirname(__DIR__));
Env::load(dirname(__DIR__) . '/.env');
require dirname(__DIR__) . '/app/Helpers/functions.php';

$service = new CampaignService();
$pdo = Database::connection();

$parentIds = $pdo->query(
    "SELECT id FROM campaigns WHERE is_recurring_parent = 1 AND deleted_at IS NULL"
)->fetchAll(PDO::FETCH_COLUMN);

$generated = 0;
foreach ($parentIds as $parentId) {
    if ($service->generateNextOccurrence((int) $parentId) !== null) {
        $generated++;
    }
}

echo date('Y-m-d H:i:s') . " — generated {$generated} recurring campaign occurrence(s) from " . count($parentIds) . " series\n";
