<?php
// socialmediamanager/api/tools.php
declare(strict_types=1);

require_once __DIR__ . "/../app/db.php";

$action = $_GET["action"] ?? "";

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

try {
  $pdo = smm_db();

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

  if ($action === "get") {
    $id = intval($_GET["id"] ?? 0);
    $key = trim((string)($_GET["key"] ?? ""));
    if ($id > 0) {
      $st = $pdo->prepare("SELECT * FROM tools 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 ($key !== "") {
      $st = $pdo->prepare("SELECT * FROM tools WHERE key=:k");
      $st->execute([":k"=>$key]);
      $row = $st->fetch(PDO::FETCH_ASSOC);
      if (!$row) smm_json_response(["ok"=>false,"error"=>"Not found"],404);
      smm_json_response(["ok"=>true,"item"=>$row]);
    }
    smm_json_response(["ok"=>false,"error"=>"Provide id or key"],400);
  }

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

    // accept both "key" and "tool_key" from UI
    $key  = trim((string)($b["key"] ?? ($b["tool_key"] ?? "")));
    $name = trim((string)($b["name"] ?? ""));
    // accept both "type" and "kind"
    $type = trim((string)($b["type"] ?? ($b["kind"] ?? "builtin")));
    if ($type === "openai") $type = "open_ai";

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

    if ($key === "" || $name === "" || $type === "") {
      smm_json_response(["ok"=>false,"error"=>"key/tool_key, name, type/kind required"],400);
    }

    // validate JSON string
    json_decode($cfg, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
      smm_json_response(["ok"=>false,"error"=>"config_json must be valid JSON"],400);
    }

    $now = smm_now_iso();

    if ($id > 0) {
      $st = $pdo->prepare("UPDATE tools SET key=:k,name=:n,type=:t,config_json=:c,updated_at=:u WHERE id=:id");
      $st->execute([":k"=>$key,":n"=>$name,":t"=>$type,":c"=>$cfg,":u"=>$now,":id"=>$id]);
      smm_json_response(["ok"=>true,"id"=>$id]);
    } else {
      $st = $pdo->prepare("INSERT INTO tools (key,name,type,config_json,created_at,updated_at) VALUES (:k,:n,:t,:c,:cr,:u)");
      $st->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") {
    $b = smm_read_json_body_safe();
    $id = intval($b["id"] ?? 0);
    if ($id <= 0) smm_json_response(["ok"=>false,"error"=>"id required"],400);
    $pdo->prepare("DELETE FROM tools 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 = "Tool key already exists. Choose a different key.";
  }
  smm_log("tools error: ".$e->getMessage(), "ERROR");
  smm_json_response(["ok"=>false,"error"=>$msg],500);
}
