<?php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/sharepack.php";

try{
  $pdo = smm_db();
  $auto = smm_get_setting($pdo, "auto_sharepack_after_publish", "1");
  if (strval($auto) !== "1") smm_json_response(["ok"=>true,"skipped"=>true,"reason"=>"auto_sharepack_after_publish disabled"]);

  $platforms = smm_get_setting($pdo, "default_share_platforms", ["facebook","instagram","tiktok","pinterest"]);
  if (!is_array($platforms) || !count($platforms)) $platforms = ["facebook","instagram","tiktok","pinterest"];

  $sql = "
    SELECT a.*
    FROM articles a
    LEFT JOIN share_packs sp ON sp.article_id = a.id
    WHERE a.status='published' AND sp.id IS NULL
    ORDER BY a.updated_at DESC
    LIMIT 50
  ";
  $articles = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

  $made = [];
  foreach ($articles as $a) {
    if (!$a["site_profile_id"]) continue;
    $stmt=$pdo->prepare("SELECT * FROM sites WHERE id=:id");
    $stmt->execute([":id"=>intval($a["site_profile_id"])]);
    $site=$stmt->fetch(PDO::FETCH_ASSOC);
    if(!$site) continue;

    $pack = smm_sharepack_build_from_article($pdo, $a, $site, $platforms);
    $id = smm_sharepack_save($pdo, intval($a["id"]), intval($a["site_profile_id"]), $pack);
    $made[] = ["share_pack_id"=>$id,"article_id"=>intval($a["id"]), "url"=>$pack["url"]];
  }

  smm_json_response(["ok"=>true,"created"=>$made,"count"=>count($made)]);

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