<?php
require_once __DIR__ . "/../app/db.php";
require_once __DIR__ . "/../app/openai_client.php";
require_once __DIR__ . "/../app/tools.php";

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

function smm_media_dir(): string {
  $dir = realpath(__DIR__ . "/../storage/media");
  if (!$dir) {
    $dir = __DIR__ . "/../storage/media";
    if (!is_dir($dir)) mkdir($dir, 0775, true);
  }
  return $dir;
}

function smm_media_public_url(string $relPath): string {
  // relPath stored like storage/media/xxx.png
  $base = "../"; // from public/ in most contexts
  return $base . ltrim($relPath, "/");
}

try{
  $pdo = smm_db();

  if ($action === "list_by_article") {
    $aid = intval($_GET["article_id"] ?? 0);
    $stmt = $pdo->prepare("SELECT * FROM media_assets WHERE article_id=:a ORDER BY created_at DESC");
    $stmt->execute([":a"=>$aid]);
    smm_json_response(["ok"=>true,"items"=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
  }

  if ($action === "upload") {
    $aid = intval($_POST["article_id"] ?? 0);
    $type = trim($_POST["type"] ?? "image");
    $prompt = trim($_POST["prompt"] ?? "upload");
    if ($aid<=0) smm_json_response(["ok"=>false,"error"=>"article_id required"],400);
    if (!isset($_FILES["file"])) smm_json_response(["ok"=>false,"error"=>"file required"],400);

    $f = $_FILES["file"];
    if ($f["error"] !== UPLOAD_ERR_OK) smm_json_response(["ok"=>false,"error"=>"Upload error"],400);

    $ext = strtolower(pathinfo($f["name"], PATHINFO_EXTENSION));
    $allowed = ["png","jpg","jpeg","webp","gif","mp4","mov","webm"];
    if (!in_array($ext, $allowed)) smm_json_response(["ok"=>false,"error"=>"File type not allowed"],400);

    $name = "a{$aid}_" . date("Ymd_His") . "_" . bin2hex(random_bytes(4)) . "." . $ext;
    $abs = smm_media_dir() . "/" . $name;
    if (!move_uploaded_file($f["tmp_name"], $abs)) smm_json_response(["ok"=>false,"error"=>"Failed to save upload"],500);

    $rel = "storage/media/" . $name;
    $now = smm_now_iso();
    $stmt = $pdo->prepare("INSERT INTO media_assets (article_id,type,file_path,source,prompt,tool_name,meta_json,created_at,updated_at)
      VALUES (:a,:t,:p,'upload',:pr,'',:m,:cr,:up)");
    $stmt->execute([
      ":a"=>$aid, ":t"=>$type, ":p"=>$rel, ":pr"=>$prompt, ":m"=>json_encode(new stdClass()),
      ":cr"=>$now, ":up"=>$now
    ]);

    smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId()),"file_path"=>$rel]);
  }

  if ($action === "generate_image") {
    $b = smm_read_json_body();
    $aid = intval($b["article_id"] ?? 0);
    $prompt = trim($b["prompt"] ?? "");
    $toolName = trim($b["tool_name"] ?? "openai_image");
    if ($aid<=0 || $prompt==="") smm_json_response(["ok"=>false,"error"=>"article_id and prompt required"],400);

    $b64 = smm_openai_generate_image_b64($pdo, $toolName, $prompt);
    $bin = base64_decode($b64);
    if ($bin === false) throw new Exception("Failed to decode image");

    $name = "a{$aid}_gen_" . date("Ymd_His") . "_" . bin2hex(random_bytes(4)) . ".png";
    $abs = smm_media_dir() . "/" . $name;
    file_put_contents($abs, $bin);

    $rel = "storage/media/" . $name;
    $now = smm_now_iso();
    $stmt = $pdo->prepare("INSERT INTO media_assets (article_id,type,file_path,source,prompt,tool_name,meta_json,created_at,updated_at)
      VALUES (:a,'image',:p,'generated',:pr,:tn,:m,:cr,:up)");
    $stmt->execute([
      ":a"=>$aid, ":p"=>$rel, ":pr"=>$prompt, ":tn"=>$toolName, ":m"=>json_encode(["format"=>"png"]),
      ":cr"=>$now, ":up"=>$now
    ]);

    smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId()),"file_path"=>$rel]);
  }

  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);
    $stmt = $pdo->prepare("SELECT * FROM media_assets WHERE id=:id");
    $stmt->execute([":id"=>$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) smm_json_response(["ok"=>false,"error"=>"Not found"],404);

    $pdo->prepare("DELETE FROM media_assets WHERE id=:id")->execute([":id"=>$id]);

    // best-effort delete file
    $abs = realpath(__DIR__ . "/../" . $row["file_path"]);
    if ($abs && strpos($abs, realpath(__DIR__ . "/../storage/media")) === 0 && file_exists($abs)) @unlink($abs);

    smm_json_response(["ok"=>true]);
  }



  if ($action === "edit_image") {
    $b = smm_read_json_body();
    $mediaId = intval($b["media_id"] ?? 0);
    $prompt = trim($b["prompt"] ?? "");
    $toolName = trim($b["tool_name"] ?? "openai_image");
    if ($mediaId<=0 || $prompt==="") smm_json_response(["ok"=>false,"error"=>"media_id and prompt required"],400);

    $stmt = $pdo->prepare("SELECT * FROM media_assets WHERE id=:id");
    $stmt->execute([":id"=>$mediaId]);
    $m = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$m) smm_json_response(["ok"=>false,"error"=>"Media not found"],404);
    if ($m["type"] !== "image") smm_json_response(["ok"=>false,"error"=>"Media is not an image"],400);

    $abs = realpath(__DIR__ . "/../" . $m["file_path"]);
    if (!$abs) smm_json_response(["ok"=>false,"error"=>"Source file missing"],404);

    $b64 = smm_openai_image_edit_b64($pdo, $toolName, $prompt, $abs);
    $bin = base64_decode($b64);
    if ($bin === false) throw new Exception("Failed to decode edited image");

    $aid = intval($m["article_id"]);
    $name = "a{$aid}_edit_" . date("Ymd_His") . "_" . bin2hex(random_bytes(4)) . ".png";
    $absOut = smm_media_dir() . "/" . $name;
    file_put_contents($absOut, $bin);

    $rel = "storage/media/" . $name;
    $now = smm_now_iso();
    $stmt = $pdo->prepare("INSERT INTO media_assets (article_id,type,file_path,source,prompt,tool_name,meta_json,created_at,updated_at)
      VALUES (:a,'image',:p,'generated',:pr,:tn,:m,:cr,:up)");
    $stmt->execute([
      ":a"=>$aid, ":p"=>$rel, ":pr"=>$prompt, ":tn"=>$toolName, ":m"=>json_encode(["edited_from"=>$mediaId]),
      ":cr"=>$now, ":up"=>$now
    ]);

    smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId()),"file_path"=>$rel]);
  }

  if ($action === "save_canvas_image") {
    $b = smm_read_json_body();
    $aid = intval($b["article_id"] ?? 0);
    $dataUrl = $b["data_url"] ?? "";
    $prompt = trim($b["prompt"] ?? "canvas-edit");
    if ($aid<=0 || strpos($dataUrl, "data:image/") !== 0) smm_json_response(["ok"=>false,"error"=>"article_id and data_url required"],400);

    $parts = explode(",", $dataUrl, 2);
    if (count($parts) !== 2) smm_json_response(["ok"=>false,"error"=>"Invalid data_url"],400);
    $bin = base64_decode($parts[1]);
    if ($bin === false) smm_json_response(["ok"=>false,"error"=>"Decode failed"],400);

    $name = "a{$aid}_canvas_" . date("Ymd_His") . "_" . bin2hex(random_bytes(4)) . ".png";
    $absOut = smm_media_dir() . "/" . $name;
    file_put_contents($absOut, $bin);

    $rel = "storage/media/" . $name;
    $now = smm_now_iso();
    $stmt = $pdo->prepare("INSERT INTO media_assets (article_id,type,file_path,source,prompt,tool_name,meta_json,created_at,updated_at)
      VALUES (:a,'image',:p,'upload',:pr,'',:m,:cr,:up)");
    $stmt->execute([
      ":a"=>$aid, ":p"=>$rel, ":pr"=>$prompt, ":m"=>json_encode(["canvas"=>true]),
      ":cr"=>$now, ":up"=>$now
    ]);

    smm_json_response(["ok"=>true,"id"=>intval($pdo->lastInsertId()),"file_path"=>$rel]);
  }

  if ($action === "generate_video") {
    $b = smm_read_json_body();
    $aid = intval($b["article_id"] ?? 0);
    $prompt = trim($b["prompt"] ?? "");
    $toolName = trim($b["tool_name"] ?? "openai_video");
    $duration = intval($b["duration"] ?? 6);
    $size = trim($b["size"] ?? "1280x720");
    if ($aid<=0 || $prompt==="") smm_json_response(["ok"=>false,"error"=>"article_id and prompt required"],400);

    $job = smm_openai_create_video_job($pdo, $toolName, $prompt, ["duration"=>$duration, "size"=>$size]);
    $videoId = $job["id"] ?? ($job["video_id"] ?? null);
    $status = $job["status"] ?? "queued";
    if (!$videoId) throw new Exception("Video job id missing from response");

    // store placeholder media entry
    $now = smm_now_iso();
    $stmt = $pdo->prepare("INSERT INTO media_assets (article_id,type,file_path,source,prompt,tool_name,meta_json,created_at,updated_at)
      VALUES (:a,'video','', 'generated',:pr,:tn,:m,:cr,:up)");
    $stmt->execute([
      ":a"=>$aid, ":pr"=>$prompt, ":tn"=>$toolName, ":m"=>json_encode(["video_id"=>$videoId,"status"=>$status,"size"=>$size,"duration"=>$duration]),
      ":cr"=>$now, ":up"=>$now
    ]);
    $mid = intval($pdo->lastInsertId());

    smm_json_response(["ok"=>true,"media_id"=>$mid,"video_id"=>$videoId,"status"=>$status]);
  }

  if ($action === "video_status") {
    $id = intval($_GET["media_id"] ?? 0);
    if ($id<=0) smm_json_response(["ok"=>false,"error"=>"media_id required"],400);

    $stmt = $pdo->prepare("SELECT * FROM media_assets WHERE id=:id");
    $stmt->execute([":id"=>$id]);
    $m = $stmt->fetch(PDO::FETCH_ASSOC);
    if(!$m) smm_json_response(["ok"=>false,"error"=>"Not found"],404);
    if($m["type"] !== "video") smm_json_response(["ok"=>false,"error"=>"Not a video item"],400);

    $meta = json_decode($m["meta_json"] ?? "{}", true); if(!is_array($meta)) $meta=[];
    $videoId = $meta["video_id"] ?? "";
    if($videoId==="") smm_json_response(["ok"=>false,"error"=>"Missing video_id"],400);

    $toolName = $m["tool_name"] ?: "openai_video";
    $job = smm_openai_get_video_job($pdo, $toolName, $videoId);
    $status = $job["status"] ?? "unknown";

    // When completed, download first output URL if present
    if ($status === "completed" && ($m["file_path"] ?? "") === "") {
      $outUrl = $job["output"][0]["url"] ?? ($job["data"][0]["url"] ?? "");
      if ($outUrl === "" && isset($job["output"][0]["content"][0]["url"])) $outUrl = $job["output"][0]["content"][0]["url"];
      if ($outUrl === "") {
        // Some APIs may return base64; handle later if needed
        $meta["status"] = $status;
      } else {
        $aid = intval($m["article_id"]);
        $name = "a{$aid}_video_" . date("Ymd_His") . "_" . bin2hex(random_bytes(4)) . ".mp4";
        $absOut = smm_media_dir() . "/" . $name;
        smm_download_to_file($outUrl, $absOut);
        $rel = "storage/media/" . $name;

        $meta["status"] = $status;
        $meta["downloaded_from"] = $outUrl;

        $pdo->prepare("UPDATE media_assets SET file_path=:p, meta_json=:m, updated_at=:u WHERE id=:id")
            ->execute([":p"=>$rel, ":m"=>json_encode($meta), ":u"=>smm_now_iso(), ":id"=>$id]);
        $m["file_path"] = $rel;
      }
    } else {
      $meta["status"] = $status;
      $pdo->prepare("UPDATE media_assets SET meta_json=:m, updated_at=:u WHERE id=:id")
          ->execute([":m"=>json_encode($meta), ":u"=>smm_now_iso(), ":id"=>$id]);
    }

    smm_json_response(["ok"=>true,"status"=>$status,"job"=>$job,"file_path"=>$m["file_path"] ?? ""]);
  }


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

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