<?php
declare(strict_types=1);
if(PHP_SAPI!=='cli'){http_response_code(403);exit('CLI only');}
require dirname(__DIR__).'/core/bootstrap.php';
$lock=fopen(dirname(__DIR__).'/storage/automation.lock','c+');if(!$lock||!flock($lock,LOCK_EX|LOCK_NB)){exit("Automation already running\n");}
$stmt=db()->query("SELECT * FROM content_automations WHERE is_active=1 AND next_run_at IS NOT NULL AND next_run_at<=NOW() ORDER BY next_run_at LIMIT 5");
foreach($stmt->fetchAll() as $auto){try{$count=run_content_automation($auto);echo $auto['name'].": {$count} içerik\n";}catch(Throwable $e){db()->prepare('UPDATE content_automations SET last_run_at=NOW(),last_result=?,next_run_at=DATE_ADD(NOW(),INTERVAL 1 HOUR),updated_at=NOW() WHERE id=?')->execute(['Hata: '.$e->getMessage(),$auto['id']]);echo $auto['name'].': '.$e->getMessage()."\n";}}
flock($lock,LOCK_UN);fclose($lock);
