<?php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/sharepack.php";

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

try {
  $pdo = smm_db();

  if ($action === "list") {
    $status = $_GET["status"] ?? "due";
    $sql = "SELECT sp.*, a.title AS article_title, s.name AS site_name
            FROM share_packs sp
            LEFT JOIN articles a ON a.id = sp.article_id
            LEFT JOIN sites s ON s.id = sp.site_profile_id
            WHERE 1=1";
    $params = [];
    if ($status !== "") { $sql .= " AND sp.status = :st"; $params[":st"] = $status; }
    $sql .= " ORDER BY sp.updated_at DESC LIMIT 300";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    smm_json_response(["ok"=>true,"items"=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
  }

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

  if ($action === "mark_done") {
    $b = smm_read_json_body();
    $id = intval($b["id"] ?? 0);
    if ($id<=0) smm_json_response(["ok"=>false,"error"=>"Invalid id"],400);
    $pdo->prepare("UPDATE share_packs SET status='done', updated_at=:u WHERE id=:id")
        ->execute([":u"=>smm_now_iso(),":id"=>$id]);
    smm_json_response(["ok"=>true]);
  }

  if ($action === "delete") {
    $b=smm_read_json_body(); $id=intval($b["id"]??0);
    if($id<=0) smm_json_response(["ok"=>false,"error"=>"Invalid id"],400);
    $pdo->prepare("DELETE FROM share_packs WHERE id=:id")->execute([":id"=>$id]);
    smm_json_response(["ok"=>true]);
  }

  if ($action === "generate_from_article") {
    $b = smm_read_json_body();
    $articleId = intval($b["article_id"] ?? 0);
    if ($articleId<=0) smm_json_response(["ok"=>false,"error"=>"article_id required"],400);

    $stmt=$pdo->prepare("SELECT * FROM articles WHERE id=:id");
    $stmt->execute([":id"=>$articleId]);
    $a=$stmt->fetch(PDO::FETCH_ASSOC);
    if(!$a) smm_json_response(["ok"=>false,"error"=>"Article not found"],404);
    if(!$a["site_profile_id"]) smm_json_response(["ok"=>false,"error"=>"Article must have a site selected first."],400);

    $stmt=$pdo->prepare("SELECT * FROM sites WHERE id=:id");
    $stmt->execute([":id"=>intval($a["site_profile_id"])]);
    $site=$stmt->fetch(PDO::FETCH_ASSOC);
    if(!$site) smm_json_response(["ok"=>false,"error"=>"Site not found"],404);

    $platforms = $b["platforms"] ?? smm_get_setting($pdo, "default_share_platforms", ["facebook","instagram","tiktok","pinterest"]);
    if (!is_array($platforms) || !count($platforms)) $platforms = ["facebook","instagram","tiktok","pinterest"];

    $pack = smm_sharepack_build_from_article($pdo, $a, $site, $platforms);
    $id = smm_sharepack_save($pdo, $articleId, intval($a["site_profile_id"]), $pack);

    smm_json_response(["ok"=>true,"id"=>$id,"pack"=>$pack]);
  }

  if ($action === "settings_get") {
    $auto = smm_get_setting($pdo, "auto_sharepack_after_publish", "1");
    $plats = smm_get_setting($pdo, "default_share_platforms", ["facebook","instagram","tiktok","pinterest"]);
    smm_json_response(["ok"=>true,"settings"=>[
      "auto_sharepack_after_publish"=>$auto,
      "default_share_platforms"=>$plats
    ]]);
  }

  if ($action === "settings_save") {
    $b=smm_read_json_body();
    $auto = strval($b["auto_sharepack_after_publish"] ?? "1");
    $plats = $b["default_share_platforms"] ?? ["facebook","instagram","tiktok","pinterest"];
    if (!is_array($plats)) $plats = ["facebook","instagram","tiktok","pinterest"];
    smm_set_setting($pdo, "auto_sharepack_after_publish", $auto);
    smm_set_setting($pdo, "default_share_platforms", $plats);
    smm_json_response(["ok"=>true]);
  }

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

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