<?php
require_once __DIR__ . "/db.php";
require_once __DIR__ . "/tagx.php";

function smm_get_setting(PDO $pdo, string $key, $default=null) {
  $stmt = $pdo->prepare("SELECT value FROM settings WHERE key=:k");
  $stmt->execute([":k"=>$key]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$row) return $default;
  $val = $row["value"];
  $json = json_decode($val, true);
  return (json_last_error() === JSON_ERROR_NONE) ? $json : $val;
}

function smm_set_setting(PDO $pdo, string $key, $value): void {
  if (is_array($value) || is_object($value)) $value = json_encode($value, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  $stmt = $pdo->prepare("INSERT INTO settings (key,value) VALUES (:k,:v)
    ON CONFLICT(key) DO UPDATE SET value=excluded.value");
  $stmt->execute([":k"=>$key,":v"=>strval($value)]);
}

function smm_sharepack_build_from_article(PDO $pdo, array $article, array $site, array $platforms): array {
  $title = trim($article["title"] ?? "");
  $body = $article["body_html"] ?? "";

  // TagX extract (local HTML)
  $tx = smm_tagx_extract($title, $body);
  $hashtags = implode(" ", $tx["hashtags"] ?? []);

  $slug = $article["slug"] ?: $title;
  $url = rtrim($site["base_url"], "/") . "/" . smm_slugify($slug) . "/";

  $plain = trim(preg_replace('/\s+/', ' ', strip_tags($body)));
  $hook = $plain;
  if (strlen($hook) > 140) $hook = substr($hook, 0, 137) . "...";
  if ($hook === "") $hook = "New post is live!";

  $caption = "🚀 New post: {$title}\n\n{$hook}";
  $full = $caption . "\n\n" . $url . "\n\n" . $hashtags;

  return [
    "platforms"=>$platforms,
    "url"=>$url,
    "caption"=>$caption,
    "hashtags"=>$hashtags,
    "full_post"=>$full,
    "tagx"=>$tx
  ];
}

function smm_sharepack_save(PDO $pdo, int $articleId, int $siteId, array $pack): int {
  $now = smm_now_iso();
  $stmt = $pdo->prepare("INSERT INTO share_packs (article_id,site_profile_id,platforms_json,url,caption,hashtags,full_post,status,created_at,updated_at)
    VALUES (:a,:s,:p,:u,:c,:h,:f,'due',:cr,:up)");
  $stmt->execute([
    ":a"=>$articleId,
    ":s"=>$siteId,
    ":p"=>json_encode($pack["platforms"], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
    ":u"=>$pack["url"],
    ":c"=>$pack["caption"],
    ":h"=>$pack["hashtags"],
    ":f"=>$pack["full_post"],
    ":cr"=>$now,
    ":up"=>$now
  ]);
  return intval($pdo->lastInsertId());
}
