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

// Format:
// ### Title
// <html or plain text...>
// ### Next Title
// ...

try{
  $b = smm_read_json_body();
  $text = $b["text"] ?? "";
  if (trim($text)==="") smm_json_response(["ok"=>false,"error"=>"text required"],400);

  $parts = preg_split('/^###\s+/m', $text);
  $created = [];
  $pdo = smm_db();
  $now = smm_now_iso();

  foreach ($parts as $chunk) {
    $chunk = trim($chunk);
    if ($chunk==="") continue;
    $lines = preg_split('/\R/', $chunk);
    $title = trim(array_shift($lines) ?? "");
    $body = trim(implode("\n", $lines));
    if ($title==="") continue;

    // If body looks like plain text, wrap it.
    if (stripos($body, "<h1") === false && stripos($body, "<p") === false) {
      $body = "<h1>".htmlspecialchars($title, ENT_QUOTES)."</h1>\n<p>".nl2br(htmlspecialchars($body, ENT_QUOTES))."</p>";
    } else {
      // ensure h1 exists
      if (preg_match('/<h1/i', $body) !== 1) $body = "<h1>".htmlspecialchars($title, ENT_QUOTES)."</h1>\n".$body;
    }

    $slug = smm_slugify($title);
    $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"=>$body,":c"=>$now,":u"=>$now]);
    $created[] = ["id"=>intval($pdo->lastInsertId()),"title"=>$title];
  }

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

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