<?php
// chat_api/upload.php
// Upload simples para anexos do chat (imagem/pdf).
// - Recebe multipart/form-data: room, kind, file
// - Salva em /uploads/chat/{room}/{yyyymm}/
// - Para imagens: tenta converter para WEBP (GD). Se falhar, salva original.
// Retorna JSON: {ok:true,url:"/uploads/..."}

declare(strict_types=1);

header("Content-Type: application/json; charset=utf-8");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: 0");

function jexit(array $j, int $code=200): void {
  http_response_code($code);
  echo json_encode($j, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  jexit(["ok"=>false,"error"=>"method_not_allowed"], 405);
}

$room = isset($_POST['room']) ? trim((string)$_POST['room']) : 'geral';
$kind = isset($_POST['kind']) ? trim((string)$_POST['kind']) : '';

if ($room === '') $room = 'geral';
$roomSafe = preg_replace('~[^a-zA-Z0-9_-]+~', '', $room);
if ($roomSafe === '') $roomSafe = 'geral';

$kind = strtolower($kind);
if (!in_array($kind, ['image','pdf'], true)) {
  jexit(["ok"=>false,"error"=>"bad_kind"], 400);
}

if (!isset($_FILES['file'])) {
  jexit(["ok"=>false,"error"=>"no_file"], 400);
}

$f = $_FILES['file'];
if (!is_array($f) || !isset($f['tmp_name'])) {
  jexit(["ok"=>false,"error"=>"bad_upload"], 400);
}
if (($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
  jexit(["ok"=>false,"error"=>"upload_error","code"=>$f['error']], 400);
}

$tmp = (string)$f['tmp_name'];
$origName = (string)($f['name'] ?? 'file');
$size = (int)($f['size'] ?? 0);
if ($size <= 0) {
  jexit(["ok"=>false,"error"=>"empty_file"], 400);
}

$maxBytes = ($kind === 'pdf') ? (40 * 1024 * 1024) : (16 * 1024 * 1024);
if ($size > $maxBytes) {
  jexit(["ok"=>false,"error"=>"file_too_large"], 413);
}

$baseDir = realpath(__DIR__ . '/..');
if ($baseDir === false) $baseDir = __DIR__ . '/..';

$ym = gmdate('Ym'); // pasta por mês (UTC)
$relDir = '/uploads/chat/' . $roomSafe . '/' . $ym;
$absDir = rtrim($baseDir, '/') . $relDir;

if (!is_dir($absDir)) {
  @mkdir($absDir, 0755, true);
}

if (!is_dir($absDir) || !is_writable($absDir)) {
  jexit(["ok"=>false,"error"=>"dir_not_writable"], 500);
}

$ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
$stem = preg_replace('~[^a-zA-Z0-9_-]+~', '_', pathinfo($origName, PATHINFO_FILENAME));
if ($stem === '' || $stem === '_') $stem = 'file';

$rand = bin2hex(random_bytes(6));
$ts = gmdate('Ymd_His');

if ($kind === 'pdf') {
  // valida mimetype
  $mime = @mime_content_type($tmp) ?: '';
  if ($mime !== 'application/pdf') {
    // alguns servidores retornam application/octet-stream; ainda aceitamos se extensão for pdf
    if ($ext !== 'pdf') {
      jexit(["ok"=>false,"error"=>"not_pdf","mime"=>$mime], 400);
    }
  }

  $finalName = $stem . '_' . $ts . '_' . $rand . '.pdf';
  $absPath = $absDir . '/' . $finalName;

  if (!@move_uploaded_file($tmp, $absPath)) {
    jexit(["ok"=>false,"error"=>"move_failed"], 500);
  }

  $url = $relDir . '/' . $finalName;
  jexit(["ok"=>true,"url"=>$url,"name"=>$finalName,"size"=>filesize($absPath)]);
}

// kind=image
$mime = @mime_content_type($tmp) ?: '';
if (strpos($mime, 'image/') !== 0) {
  jexit(["ok"=>false,"error"=>"not_image","mime"=>$mime], 400);
}

// tenta converter para webp
$finalNameWebp = $stem . '_' . $ts . '_' . $rand . '.webp';
$absWebp = $absDir . '/' . $finalNameWebp;

$converted = false;
if (function_exists('imagecreatefromstring') && function_exists('imagewebp')) {
  $bin = @file_get_contents($tmp);
  if ($bin !== false) {
    $im = @imagecreatefromstring($bin);
    if ($im !== false) {
      if (function_exists('imagesavealpha')) @imagesavealpha($im, true);
      $q = 82;
      $converted = @imagewebp($im, $absWebp, $q);
      @imagedestroy($im);
    }
  }
}

if ($converted && file_exists($absWebp)) {
  $url = $relDir . '/' . $finalNameWebp;
  jexit(["ok"=>true,"url"=>$url,"name"=>$finalNameWebp,"size"=>filesize($absWebp)]);
}

// fallback: salva original
$finalExt = $ext ?: 'img';
$finalName = $stem . '_' . $ts . '_' . $rand . '.' . $finalExt;
$absPath = $absDir . '/' . $finalName;

if (!@move_uploaded_file($tmp, $absPath)) {
  jexit(["ok"=>false,"error"=>"move_failed"], 500);
}

$url = $relDir . '/' . $finalName;
jexit(["ok"=>true,"url"=>$url,"name"=>$finalName,"size"=>filesize($absPath)]);
