<?php
require_once __DIR__ . '/../config.php';

header('Content-Type: application/json; charset=utf-8');

function json_fail(string $msg, int $code = 400) {
  http_response_code($code);
  echo json_encode(["success" => false, "error" => $msg]);
  exit;
}

function ensure_dir(string $dir) {
  if (!is_dir($dir)) {
    @mkdir($dir, 0755, true);
  }
  if (!is_writable($dir)) {
    // Try to continue but warn clearly
    json_fail("Server folder not writable: " . $dir . " (set permissions 755/775)", 500);
  }
}

function safe_random_name(string $prefix, string $ext): string {
  return $prefix . "_" . date("Ymd_His") . "_" . bin2hex(random_bytes(6)) . "." . $ext;
}

function curl_post_json(string $url, array $payload, array $headers = [], int $timeout = 60): array {
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array_merge(["Content-Type: application/json"], $headers),
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_TIMEOUT => $timeout,
    CURLOPT_CONNECTTIMEOUT => 20,
  ]);
  $raw = curl_exec($ch);
  $errno = curl_errno($ch);
  $err = curl_error($ch);
  $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($errno) {
    return ["ok" => false, "http" => 0, "error" => "cURL error {$errno}: {$err}", "raw" => $raw];
  }

  $json = json_decode($raw, true);
  return ["ok" => ($http >= 200 && $http < 300), "http" => $http, "json" => $json, "raw" => $raw];
}

function download_file(string $url, string $destPath): bool {
  // Use cURL (more reliable than file_get_contents for redirects)
  $ch = curl_init($url);
  $fp = fopen($destPath, 'wb');
  if (!$fp) return false;

  curl_setopt_array($ch, [
    CURLOPT_FILE => $fp,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 90,
    CURLOPT_CONNECTTIMEOUT => 20,
    CURLOPT_SSL_VERIFYPEER => true,
  ]);

  $ok = curl_exec($ch);
  $errno = curl_errno($ch);
  curl_close($ch);
  fclose($fp);

  if (!$ok || $errno) {
    @unlink($destPath);
    return false;
  }
  return true;
}

function find_first_url_deep($data): ?string {
  // Find first http(s) url anywhere inside nested arrays
  if (is_string($data)) {
    if (preg_match('~^https?://~i', $data)) return $data;
    return null;
  }
  if (is_array($data)) {
    foreach ($data as $v) {
      $found = find_first_url_deep($v);
      if ($found) return $found;
    }
  }
  return null;
}

// -------------------------------
// Validate inputs
// -------------------------------
$themeId  = $_POST['themeId'] ?? '';
$avatarId = $_POST['avatarId'] ?? '';

if (!$themeId || !$avatarId) {
  json_fail("Missing themeId or avatarId.");
}

$found = find_avatar($themeId, $avatarId);
if (!$found) {
  json_fail("Invalid theme/avatar selection.");
}

$avatar = $found['avatar'];
$prompt = $avatar['prompt'] ?? '';
if (!$prompt) {
  json_fail("Avatar prompt missing in config.");
}

if (!isset($_FILES['selfie'])) {
  json_fail("Missing selfie file.");
}

$file = $_FILES['selfie'];

if ($file['error'] !== UPLOAD_ERR_OK) {
  json_fail("Upload error: " . $file['error']);
}

if ($file['size'] > 6 * 1024 * 1024) { // 6MB limit
  json_fail("Selfie too large. Max 6MB.");
}

// Check mime type
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];

if (!isset($allowed[$mime])) {
  json_fail("Invalid image type. Use JPG/PNG/WebP.");
}

// -------------------------------
// Save selfie locally
// -------------------------------
ensure_dir(SELFIE_DIR);
ensure_dir(OUTPUT_DIR);

$ext = $allowed[$mime];
$selfieName = safe_random_name("selfie", $ext);
$selfiePath = SELFIE_DIR . $selfieName;

if (!move_uploaded_file($file['tmp_name'], $selfiePath)) {
  json_fail("Failed to save selfie on server.", 500);
}

// Public URL for LightX to fetch
$selfieUrl = SELFIE_URL_BASE . $selfieName;

// -------------------------------
// Call LightX AI Filter (works from your server ✅)
// -------------------------------
$payload = [
  "imageUrl" => $selfieUrl,
  "styleImageUrl" => "",      // optional (we can add later)
  "textPrompt" => $prompt
];

$resp = curl_post_json(
  LIGHTX_AIFILTER_URL,
  $payload,
  ["x-api-key: " . LIGHTX_API_KEY],
  60
);

if (!$resp["ok"] || !is_array($resp["json"])) {
  json_fail("LightX aifilter failed. HTTP {$resp['http']} | {$resp['raw']}", 500);
}

$orderId = $resp["json"]["body"]["orderId"] ?? null;
if (!$orderId) {
  json_fail("LightX did not return orderId. Response: " . $resp["raw"], 500);
}

// -------------------------------
// Poll LightX Order Status
// -------------------------------
$maxTries = 14;   // about ~70 seconds if sleep=5
$sleepSec = 5;

$outputUrl = null;
$lastRaw = null;

for ($i = 1; $i <= $maxTries; $i++) {
  $statusResp = curl_post_json(
    LIGHTX_ORDER_STATUS_URL,
    ["orderId" => $orderId],
    ["x-api-key: " . LIGHTX_API_KEY],
    60
  );

  $lastRaw = $statusResp["raw"] ?? '';
  $json = $statusResp["json"] ?? null;

  if (is_array($json)) {
    // Try common locations
    $body = $json["body"] ?? $json;

    // 1) direct common keys
    $keys = ["outputImageUrl","outputUrl","resultUrl","generatedImageUrl","imageUrl","url"];
    foreach ($keys as $k) {
      if (!empty($body[$k]) && is_string($body[$k]) && preg_match('~^https?://~i', $body[$k])) {
        $outputUrl = $body[$k];
        break;
      }
    }

    // 2) Sometimes nested arrays like body.output or body.result etc.
    if (!$outputUrl) {
      $outputUrl = find_first_url_deep($body);
    }

    // If we got output URL -> break
    if ($outputUrl) break;
  }

  sleep($sleepSec);
}

if (!$outputUrl) {
  json_fail("LightX output not ready (orderId: {$orderId}). Last response: {$lastRaw}", 504);
}

// -------------------------------
// Download output image and save
// -------------------------------
$outName = safe_random_name("generated", "jpg");
$outPath = OUTPUT_DIR . $outName;

$ok = download_file($outputUrl, $outPath);
if (!$ok) {
  json_fail("Could not download generated image from LightX output URL.", 500);
}

$generatedUrl = OUTPUT_URL_BASE . $outName;

// -------------------------------
// Success response to frontend
// -------------------------------
echo json_encode([
  "success" => true,
  "orderId" => $orderId,
  "selfieUrl" => $selfieUrl,
  "generatedUrl" => $generatedUrl,
  "whatsappNumber" => WHATSAPP_NUMBER
]);
