<?php
declare(strict_types=1);

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

/**
 * POST /api/zapier.php?action=send  { id: 123 }
 * Sends a draft/published article to the Zapier webhook tool (key = zapier_webhook).
 */

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

function public_base_url(): string {
  $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
  $scheme = $https ? "https" : "http";
  $host = $_SERVER['HTTP_HOST'] ?? "localhost";

  // /ashley/media3/social-media-manager/api -> /ashley/media3/social-media-manager
  $dir = rtrim(str_replace("\\","/", dirname($_SERVER['SCRIPT_NAME'] ?? "/")), "/");
  $root = preg_replace('#/api$#', '', $dir);

  return $scheme . "://" . $host . $root;
}

function find_tool(PDO $pdo, string $key): ?array {
  $st = $pdo->prepare("SELECT * FROM tools WHERE `key`=:k LIMIT 1");
  $st->execute([":k"=>$key]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  return $row ?: null;
}

function http_post_json(string $url, array $payload, array $headers = [], int $timeoutSec = 25): array {
  $json = json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

  $hdrs = [
    "Content-Type: application/json",
    "Content-Length: " . strlen((string)$json),
  ];
  foreach($headers as $k=>$v){
    $hdrs[] = $k . ": " . $v;
  }

  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_POST            => true,
    CURLOPT_POSTFIELDS      => $json,
    CURLOPT_HTTPHEADER      => $hdrs,
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_TIMEOUT         => max(5, $timeoutSec),
  ]);

  $out = curl_exec($ch);
  $err = curl_error($ch);
  $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  return ["ok"=>($out !== false && $code < 400), "code"=>$code, "err"=>$err, "body"=>$out];
}

try {
  $action = $_GET["action"] ?? "";
  if ($action !== "send") {
    smm_json_response(["ok"=>false, "error"=>"Unknown action"], 400);
  }

  $b = read_json_body();
  $id = (int)($b["id"] ?? 0);
  if ($id <= 0) smm_json_response(["ok"=>false, "error"=>"id required"], 400);

  $pdo = smm_db();

  // Load article
  $st = $pdo->prepare("SELECT a.*, s.name AS site_name, s.base_url AS site_base_url
                       FROM articles a
                       LEFT JOIN sites s ON s.id = a.site_profile_id
                       WHERE a.id=:id LIMIT 1");
  $st->execute([":id"=>$id]);
  $a = $st->fetch(PDO::FETCH_ASSOC);
  if(!$a) smm_json_response(["ok"=>false, "error"=>"Article not found"], 404);

  // Find latest media (best-effort)
  $img = null; $vid = null;
  try {
    $m = $pdo->prepare("SELECT * FROM media WHERE article_id=:id ORDER BY id DESC");
    $m->execute([":id"=>$id]);
    foreach($m->fetchAll(PDO::FETCH_ASSOC) as $row){
      if(!$img && ($row["type"] ?? "") === "image" && !empty($row["file_path"])) $img = $row;
      if(!$vid && ($row["type"] ?? "") === "video" && !empty($row["file_path"])) $vid = $row;
      if($img && $vid) break;
    }
  } catch(Throwable $e){
    // ignore if your schema doesn't have media table in this version
  }

  $tool = find_tool($pdo, "zapier_webhook");
  if(!$tool) smm_json_response(["ok"=>false, "error"=>"Zapier tool not found (key=zapier_webhook)"], 500);

  $cfg = json_decode((string)($tool["config_json"] ?? "{}"), true);
  if(!is_array($cfg)) $cfg = [];
  $hook = (string)($cfg["url"] ?? "");
  if(!filter_var($hook, FILTER_VALIDATE_URL)) {
    smm_json_response(["ok"=>false, "error"=>"Invalid Zapier webhook URL in tools.config_json"], 500);
  }

  $base = public_base_url();
  $image_url = $img && !empty($img["file_path"]) ? ($base . "/" . ltrim((string)$img["file_path"], "/")) : "";
  $video_url = $vid && !empty($vid["file_path"]) ? ($base . "/" . ltrim((string)$vid["file_path"], "/")) : "";

  // If you want Zapier to delay, include the scheduler time result too (optional)
  $request_id = "manual_" . $id . "_" . bin2hex(random_bytes(6));

  $payload = [
    "request_id"   => $request_id,
    "event"        => "manual_send",
    "article_id"   => (int)$a["id"],
    "status"       => (string)$a["status"],
    "title"        => (string)$a["title"],
    "slug"         => (string)($a["slug"] ?? ""),
    "site_name"    => (string)($a["site_name"] ?? ""),
    "caption"      => (string)$a["title"],               // simplest safe default
    "body_html"    => (string)($a["body_html"] ?? ""),
    "image_url"    => $image_url,
    "video_url"    => $video_url,
    "published_url"=> (string)($a["published_url"] ?? ""), // if your schema has it
    "sent_at"      => smm_now_iso(),
  ];

  $headers = is_array($cfg["headers"] ?? null) ? $cfg["headers"] : [];
  $timeout = (int)($cfg["timeout_sec"] ?? 25);

  // Retry lightly (2 retries)
  $tries = 3;
  $last = null;
  for($i=1;$i<=$tries;$i++){
    $last = http_post_json($hook, $payload, $headers, $timeout);
    if($last["ok"]) break;
    if($i < $tries) sleep(2);
  }

  if(!$last || !$last["ok"]){
    smm_log("Zapier send failed: HTTP ".($last["code"]??0)." ".($last["err"]??"")." ".substr((string)($last["body"]??""),0,200), "ERROR");
    smm_json_response(["ok"=>false, "error"=>"Zapier webhook failed", "details"=>$last], 500);
  }

  smm_log("Zapier send ok: request_id=".$request_id." HTTP ".$last["code"], "INFO");
  smm_json_response(["ok"=>true, "request_id"=>$request_id, "http_code"=>$last["code"]]);

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