<?php
// socialmediamanager/api/tagx_run.php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/tagx.php";

try{
  $b = smm_read_json_body();
  $id = intval($b["article_id"] ?? 0);
  if ($id<=0) smm_json_response(["ok"=>false,"error"=>"article_id required"],400);

  $pdo=smm_db();
  $stmt=$pdo->prepare("SELECT * FROM articles WHERE id=:id");
  $stmt->execute([":id"=>$id]);
  $a=$stmt->fetch(PDO::FETCH_ASSOC);
  if(!$a) smm_json_response(["ok"=>false,"error"=>"Not found"],404);

  $out = smm_tagx_extract($a["title"], $a["body_html"]);
  $pdo->prepare("UPDATE articles SET tags_json=:tj, meta_json=:mj, updated_at=:u WHERE id=:id")
      ->execute([":tj"=>json_encode($out["tags"]),":mj"=>json_encode($out),":u"=>smm_now_iso(),":id"=>$id]);

  smm_json_response(["ok"=>true,"result"=>$out]);

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