<?php
declare(strict_types=1);

// socialmediamanager/api/crud.php
require_once __DIR__ . "/../app/db.php";

$action = (string)($_GET["action"] ?? "");

function smm_body(): array {
  $raw = file_get_contents("php://input");
  $b = json_decode($raw ?: "{}", true);
  return is_array($b) ? $b : [];
}

function smm_need(bool $ok, string $msg, int $code=400): void {
  if (!$ok) smm_json_response(["ok"=>false,"error"=>$msg], $code);
}

try {
  $pdo = smm_db();

  if ($action === "ping") {
    smm_json_response(["ok"=>true,"time"=>smm_now_iso()]);
  }

  // ---------------- TOOLS ----------------
  if ($action === "list_tools") {
    $rows = $pdo->query("SELECT * FROM tools ORDER BY updated_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    smm_json_response(["ok"=>true,"items"=>$rows]);
  }

  if ($action === "save_tool") {
    $b = smm_body();
    $id   = intval($b["id"] ?? 0);
    $key  = trim((string)($b["key"] ?? ($b["tool_key"] ?? "")));
    $name = trim((string)($b["name"] ?? ""));
    $type = trim((string)($b["type"] ?? ($b["kind"] ?? "builtin")));
    if ($type === "openai") $type = "open_ai";

    $cfg = $b["config_json"] ?? ($b["config"] ?? "{}");
    if (!is_string($cfg)) $cfg = json_encode($cfg, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

    smm_need($key !== "" && $name !== "" && $type !== "", "key/tool_key, name, type/kind required");

    json_decode($cfg, true);
    smm_need(json_last_error() === JSON_ERROR_NONE, "config_json must be valid JSON");

    $now = smm_now_iso();

    if ($id > 0) {
      $pdo->prepare("UPDATE tools SET key=:k,name=:n,type=:t,config_json=:c,updated_at=:u WHERE id=:id")
          ->execute([":k"=>$key,":n"=>$name,":t"=>$type,":c"=>$cfg,":u"=>$now,":id"=>$id]);
      smm_json_response(["ok"=>true,"id"=>$id]);
    } else {
      $pdo->prepare("INSERT INTO tools (key,name,type,config_json,created_at,updated_at) VALUES (:k,:n,:t,:c,:cr,:u)")
          ->execute([":k"=>$key,":n"=>$name,":t"=>$type,":c"=>$cfg,":cr"=>$now,":u"=>$now]);
      smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId())]);
    }
  }

  if ($action === "delete_tool") {
    $b = smm_body();
    $id = intval($b["id"] ?? 0);
    smm_need($id > 0, "id required");
    $pdo->prepare("DELETE FROM tools WHERE id=:id")->execute([":id"=>$id]);
    smm_json_response(["ok"=>true]);
  }

  // ---------------- SITES ----------------
  if ($action === "list_sites") {
    $rows = $pdo->query("SELECT * FROM sites ORDER BY updated_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    smm_json_response(["ok"=>true,"items"=>$rows]);
  }

  if ($action === "save_site") {
    $b = smm_body();
    $id = intval($b["id"] ?? 0);

    $name = trim((string)($b["name"] ?? ""));
    $base_url = trim((string)($b["base_url"] ?? ""));
    $publish_dir = trim((string)($b["publish_dir"] ?? ""));
    $posts_index_path = trim((string)($b["posts_index_path"] ?? ""));

    smm_need($name!=="" && $base_url!=="" && $publish_dir!=="" && $posts_index_path!=="",
      "name, base_url, publish_dir, posts_index_path required");

    $now = smm_now_iso();

    if ($id > 0) {
      $pdo->prepare("UPDATE sites SET name=:n, base_url=:b, publish_dir=:p, posts_index_path=:i, updated_at=:u WHERE id=:id")
          ->execute([":n"=>$name,":b"=>$base_url,":p"=>$publish_dir,":i"=>$posts_index_path,":u"=>$now,":id"=>$id]);
      smm_json_response(["ok"=>true,"id"=>$id]);
    } else {
      $pdo->prepare("INSERT INTO sites (name,base_url,publish_dir,posts_index_path,created_at,updated_at)
                     VALUES (:n,:b,:p,:i,:cr,:u)")
          ->execute([":n"=>$name,":b"=>$base_url,":p"=>$publish_dir,":i"=>$posts_index_path,":cr"=>$now,":u"=>$now]);
      smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId())]);
    }
  }

  if ($action === "delete_site") {
    $b = smm_body();
    $id = intval($b["id"] ?? 0);
    smm_need($id > 0, "id required");
    $pdo->prepare("DELETE FROM sites WHERE id=:id")->execute([":id"=>$id]);
    smm_json_response(["ok"=>true]);
  }

// ---- AGENTS ----
if ($action === "list_agents") {
  // If you haven't built agents yet, return empty array instead of 400.
  try {
    $rows = $pdo->query("SELECT * FROM agents ORDER BY updated_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    smm_json_response(["ok"=>true, "items"=>$rows]);
  } catch (Throwable $e) {
    // agents table may not exist in older sqlite — return empty instead of breaking UI
    smm_json_response(["ok"=>true, "items"=>[]]);
  }
}

if ($action === "save_agent") {
  $b = smm_read_json_body();
  $id = intval($b["id"] ?? 0);
  $key = trim((string)($b["key"] ?? ""));
  $name = trim((string)($b["name"] ?? ""));
  $description = trim((string)($b["description"] ?? ""));
  $preferred_tool_key = trim((string)($b["preferred_tool_key"] ?? ""));
  $cfg = $b["config_json"] ?? "{}";
  if (!is_string($cfg)) $cfg = json_encode($cfg, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

  if ($key==="" || $name==="") smm_json_response(["ok"=>false,"error"=>"key and name required"], 400);

  $now = smm_now_iso();

  // create table if missing (safe)
  $pdo->exec("CREATE TABLE IF NOT EXISTS agents (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    key TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    description TEXT NULL,
    preferred_tool_key TEXT NULL,
    config_json TEXT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
  )");

  if ($id > 0) {
    $st = $pdo->prepare("UPDATE agents SET key=?, name=?, description=?, preferred_tool_key=?, config_json=?, updated_at=? WHERE id=?");
    $st->execute([$key,$name,$description,$preferred_tool_key,$cfg,$now,$id]);
    smm_json_response(["ok"=>true,"id"=>$id]);
  } else {
    $st = $pdo->prepare("INSERT INTO agents (key,name,description,preferred_tool_key,config_json,created_at,updated_at)
                         VALUES (?,?,?,?,?,?,?)");
    $st->execute([$key,$name,$description,$preferred_tool_key,$cfg,$now,$now]);
    smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId())]);
  }
}

  // ---------------- ARTICLES ----------------
  if ($action === "list_articles") {
    $rows = $pdo->query("SELECT * FROM articles ORDER BY updated_at DESC LIMIT 400")->fetchAll(PDO::FETCH_ASSOC);
    smm_json_response(["ok"=>true,"items"=>$rows]);
  }

  if ($action === "get_article") {
    $id = intval($_GET["id"] ?? 0);
    smm_need($id > 0, "id required");
    $st = $pdo->prepare("SELECT * FROM articles WHERE id=:id");
    $st->execute([":id"=>$id]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) smm_json_response(["ok"=>false,"error"=>"Not found"], 404);
    smm_json_response(["ok"=>true,"item"=>$row]);
  }

  if ($action === "save_article") {
    $b = smm_body();
    $id = intval($b["id"] ?? 0);

    $title = trim((string)($b["title"] ?? ""));
    $slug  = trim((string)($b["slug"] ?? ""));
    $body  = (string)($b["body_html"] ?? "");
    $status = trim((string)($b["status"] ?? "draft"));
    $siteId = intval($b["site_profile_id"] ?? 0);

    smm_need($title !== "", "title required");
    if ($slug === "") $slug = smm_slugify($title);

    $tags_json = $b["tags_json"] ?? "[]";
    $meta_json = $b["meta_json"] ?? "{}";
    if (!is_string($tags_json)) $tags_json = json_encode($tags_json, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    if (!is_string($meta_json)) $meta_json = json_encode($meta_json, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

    json_decode($tags_json,true); smm_need(json_last_error()===JSON_ERROR_NONE, "tags_json must be valid JSON");
    json_decode($meta_json,true); smm_need(json_last_error()===JSON_ERROR_NONE, "meta_json must be valid JSON");

    $now = smm_now_iso();

    if ($id > 0) {
      $pdo->prepare("UPDATE articles SET title=:t, slug=:s, body_html=:b, status=:st, site_profile_id=:sid,
                     tags_json=:tj, meta_json=:mj, updated_at=:u WHERE id=:id")
          ->execute([":t"=>$title,":s"=>$slug,":b"=>$body,":st"=>$status,":sid"=>($siteId?:null),
                     ":tj"=>$tags_json,":mj"=>$meta_json,":u"=>$now,":id"=>$id]);
      smm_json_response(["ok"=>true,"id"=>$id,"slug"=>$slug]);
    } else {
      $pdo->prepare("INSERT INTO articles (title,slug,body_html,status,site_profile_id,publish_at,tags_json,meta_json,created_at,updated_at)
                     VALUES (:t,:s,:b,:st,:sid,NULL,:tj,:mj,:cr,:u)")
          ->execute([":t"=>$title,":s"=>$slug,":b"=>$body,":st"=>$status,":sid"=>($siteId?:null),
                     ":tj"=>$tags_json,":mj"=>$meta_json,":cr"=>$now,":u"=>$now]);
      smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId()),"slug"=>$slug]);
    }
  }

  if ($action === "delete_article") {
    $b = smm_body();
    $id = intval($b["id"] ?? 0);
    smm_need($id > 0, "id required");
    $pdo->prepare("DELETE FROM articles WHERE id=:id")->execute([":id"=>$id]);
    smm_json_response(["ok"=>true]);
  }

  smm_json_response(["ok"=>false,"error"=>"Unknown action"], 400);

} catch (Throwable $e) {
  $msg = $e->getMessage();
  if (strpos($msg, "UNIQUE constraint failed") !== false) $msg = "Duplicate key (already exists).";
  smm_log("crud error: ".$e->getMessage(), "ERROR");
  smm_json_response(["ok"=>false,"error"=>$msg], 500);
}
