<?php

//upload.php   on server download & upload


define('API_KEY', 'Z7F81aKx1LpQw6RtYvBn9o25DsHgUa2f');

$headers = getallheaders();
$auth = $headers['Authorization'] ?? '';
if ($auth !== 'Bearer ' . API_KEY) {
    http_response_code(403);
    die(json_encode(['error'=>'Unauthorized']));
}

if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    http_response_code(405);
    die(json_encode(['error'=>'Method Not Allowed']));
}

$originalName = $_GET['name'] ?? 'unknown';
$fileType     = $_GET['type'] ?? 'misc';

$typeFolders = [
    'photo'    => 'images',
    'video'    => 'videos',
    'voice'    => 'audios',
    'audio'    => 'audios',
    'document' => 'documents',
];
$subDir = $typeFolders[$fileType] ?? 'others';

$ext = pathinfo($originalName, PATHINFO_EXTENSION) ?: 'bin';
$uniqueName = uniqid('file_', true) . '.' . $ext;

$baseUploadDir = __DIR__ . '/../uploads/';
$targetDir = $baseUploadDir . $subDir . '/';
if (!is_dir($targetDir)) mkdir($targetDir, 0755, true);
$destPath = $targetDir . $uniqueName;

// دریافت کل محتوای ورودی
$input = fopen('php://input', 'rb');
$out   = fopen($destPath, 'wb');
$bytes = stream_copy_to_stream($input, $out);
fclose($input);
fclose($out);

// لاگ برای دیباگ
$fileSize = file_exists($destPath) ? filesize($destPath) : 0;
@file_put_contents(__DIR__ . '/upload_debug.log',
    '[' . date('H:i:s') . '] File: ' . $uniqueName .
    ' | Bytes copied: ' . $bytes .
    ' | File size: ' . $fileSize . PHP_EOL,
    FILE_APPEND
);

if ($fileSize === 0) {
    http_response_code(500);
    die(json_encode(['error'=>'File empty after upload', 'bytes_copied'=>$bytes]));
}

$baseUrl = 'https://moh98.ir/uploader_me/';
$fileUrl = $baseUrl . 'api/get.php?file=' . urlencode($subDir . '/' . $uniqueName);

header('Content-Type: application/json');
echo json_encode(['success'=>true, 'url'=>$fileUrl]);

