<?php
declare(strict_types=1);

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

$pdo = smm_db();
$b = smm_read_json_body();

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

$st = $pdo->prepare("SELECT * FROM articles WHERE id=?");
$st->execute([$articleId]);
$a = $st->fetch(PDO::FETCH_ASSOC);
if (!$a) smm_json_response(["ok"=>false,"error"=>"Article not found"],404);

// Load Zapier tool
$tool = smm_get_tool($pdo, "zapier_webhook");
if (!$tool || empty($tool['enabled'])) {
  smm_json_response(["ok"=>false,"error"=>"Zapier webhook not configured"],500);
}

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

// Build payload
$payload = [
  "request_id"   => uniqid("manual_", true),
  "event"        => "manual_send",
  "article_id"   => $a['id'],
  "title"        => $a['title'],
  "caption"      => strip_tags($a['body_html']),
  "url"          => $a['published_url'] ?? "",
  "image_url"    => json_decode($a['media_json'], true)['image_url'] ?? null,
  "video_url"    => json_decode($a['media_json'], true)['video_url'] ?? null,
  "content_type" => $b['content_type'] ?? 'text',
  "region"       => $b['region'] ?? 'US',
  "platforms"    => $b['platforms'] ?? [],
  "source"       => "smm_manual"
];

// Send webhook
$ch = curl_init($hook);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST           => true,
  CURLOPT_HTTPHEADER     => ["Content-Type: application/json"],
  CURLOPT_POSTFIELDS     => json_encode($payload),
  CURLOPT_TIMEOUT        => intval($cfg['timeout_sec'] ?? 20),
]);

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

if ($out === false || $code >= 400) {
  smm_log("Zapier manual send failed: {$err}", "ERROR");
  smm_json_response(["ok"=>false,"error"=>"Zapier send failed"],500);
}

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