<?php
// socialmediamanager/api/publish_due.php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/publisher.php";

try{
  $pdo = smm_db();
  $now = smm_now_iso();

  $stmt = $pdo->prepare("SELECT id FROM articles WHERE status='queued' AND publish_at IS NOT NULL AND publish_at <= :now ORDER BY publish_at ASC LIMIT 50");
  $stmt->execute([":now"=>$now]);
  $ids = array_map(fn($r)=>intval($r["id"]), $stmt->fetchAll(PDO::FETCH_ASSOC));

  $results = [];
  foreach ($ids as $id) {
    try {
      $results[] = smm_publish_article($pdo, $id);
    } catch(Throwable $e) {
      $results[] = ["ok"=>false,"article_id"=>$id,"error"=>$e->getMessage()];
    }
  }
  smm_json_response(["ok"=>true,"published"=>$results,"count"=>count($results)]);

} catch(Throwable $e){
  smm_log("publish_due error: ".$e->getMessage(),"ERROR");
  smm_json_response(["ok"=>false,"error"=>$e->getMessage()],500);
}
