<?php
session_start();
require __DIR__ . "/../db.php";

if (!isset($_SESSION["user_id"])) {
  http_response_code(401);
  exit("login required");
}

if (!isset($_FILES["file"])) {
  http_response_code(400);
  exit("no file");
}

$f = $_FILES["file"];
if ($f["error"] !== UPLOAD_ERR_OK) {
  http_response_code(400);
  exit("upload error");
}

// محدودیت حجم: 10MB
$max = 10 * 1024 * 1024;
if ($f["size"] > $max) {
  http_response_code(413);
  exit("file too large");
}

$allowed = [
     "audio/webm" ,
  "image/jpeg","image/png","image/webp","image/gif",
  "application/pdf",
  "text/plain"
 // <-- اضافه شده برای پشتیبانی از ویس
];

$tmp = $f["tmp_name"];
$mime = mime_content_type($tmp);
if (!in_array($mime, $allowed, true)) {
  http_response_code(415);
  exit("type not allowed");
}

// اسم امن
$origName = basename($f["name"]);
$origName = preg_replace('/[^a-zA-Z0-9\.\-\_\(\)\s]/', '_', $origName);
$ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

$rand = bin2hex(random_bytes(8));
$finalName = date("Ymd_His") . "_" . $rand . ($ext ? ".".$ext : "");

$uploadDir = realpath(__DIR__ . "/../uploads");
if (!$uploadDir) {
  http_response_code(500);
  exit("upload dir missing");
}

$dest = $uploadDir . DIRECTORY_SEPARATOR . $finalName;
if (!move_uploaded_file($tmp, $dest)) {
  http_response_code(500);
  exit("cannot move");
}

header("Content-Type: application/json; charset=utf-8");
echo json_encode([
  "ok" => true,
  "file_name" => $origName,
  "file_path" => "/uploads/" . $finalName,
  "mime_type" => $mime,
  "file_size" => (int)$f["size"]
], JSON_UNESCAPED_UNICODE);
