<?php
// socialmediamanager/api/chat_draft.php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/openai.php";

try {
  if (!smm_openai_enabled()) smm_json_response(["ok"=>false,"error"=>"OpenAI disabled. Set openai_api_key in app/config.php"],400);

  $b = smm_read_json_body();
  $prompt = trim($b["prompt"] ?? "");
  $tone = trim($b["tone"] ?? "friendly and clear");
  $word_count = intval($b["word_count"] ?? 1200);
  if ($prompt==="") smm_json_response(["ok"=>false,"error"=>"Prompt required"],400);

  $system = "You write high-quality blog posts. Output STRICT HTML only (no markdown fences). Use headings, bullet points, and a short FAQ at the end.";
  $user = "Write a blog article about: {$prompt}\nTone: {$tone}\nTarget length: about {$word_count} words.\nReturn HTML with <h1> title and good structure.";

  $resp = smm_openai_chat([["role"=>"system","content"=>$system],["role"=>"user","content"=>$user]], ["temperature"=>0.7]);
  $content = $resp["choices"][0]["message"]["content"] ?? "";
  if (trim($content)==="") throw new Exception("Empty model response.");

  $title = "Draft";
  if (preg_match("/<h1[^>]*>(.*?)<\/h1>/is", $content, $m)) $title = trim(strip_tags($m[1])) ?: "Draft";
  $slug = smm_slugify($title);

  $pdo=smm_db(); $now=smm_now_iso();
  $pdo->prepare("INSERT INTO articles (title,slug,body_html,status,created_at,updated_at) VALUES (:t,:s,:b,'draft',:c,:u)")
      ->execute([":t"=>$title,":s"=>$slug,":b"=>$content,":c"=>$now,":u"=>$now]);

  smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId()),"title"=>$title,"slug"=>$slug,"body_html"=>$content]);

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