<?php
declare(strict_types=1);

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => ['message' => 'method_not_allowed']]);
    exit;
}

if (!isset($_FILES['image']) || !is_array($_FILES['image'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => ['message' => 'missing_image_file']]);
    exit;
}

$file = $_FILES['image'];
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => ['message' => 'upload_error_' . (string)$file['error']]]);
    exit;
}

$maxBytes = 12 * 1024 * 1024;
$size = (int)($file['size'] ?? 0);
if ($size <= 0 || $size > $maxBytes) {
    http_response_code(413);
    echo json_encode(['success' => false, 'error' => ['message' => 'file_too_large_or_empty']]);
    exit;
}

$tmpPath = (string)($file['tmp_name'] ?? '');
if ($tmpPath === '' || !is_uploaded_file($tmpPath)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => ['message' => 'invalid_upload_source']]);
    exit;
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = $finfo ? (string)finfo_file($finfo, $tmpPath) : '';
if ($finfo) finfo_close($finfo);
if (stripos($mime, 'image/') !== 0) {
    http_response_code(415);
    echo json_encode(['success' => false, 'error' => ['message' => 'file_is_not_image']]);
    exit;
}

$dim = @getimagesize($tmpPath);
if (!$dim || !isset($dim[0], $dim[1])) {
    http_response_code(415);
    echo json_encode(['success' => false, 'error' => ['message' => 'image_dimension_unreadable']]);
    exit;
}
$maxDim = 4000;
if ((int)$dim[0] > $maxDim || (int)$dim[1] > $maxDim) {
    http_response_code(413);
    echo json_encode(['success' => false, 'error' => ['message' => 'image_dimensions_too_large']]);
    exit;
}

$provider = strtolower(trim((string)($_GET['provider'] ?? 'imgbb')));
$imgbbKey = trim((string)(getenv('SB_IMGBB_API_KEY') ?: ''));
$daimanKey = trim((string)(getenv('SB_DAIMAN_API_KEY') ?: ''));

$targetUrl = '';
$headers = [];
if ($provider === 'daiman') {
    $targetUrl = 'https://image.daiman.shop/api/upload.php';
    if ($daimanKey !== '') {
        $targetUrl .= '?key=' . rawurlencode($daimanKey);
        $headers[] = 'X-API-Key: ' . $daimanKey;
    }
} else {
    if ($imgbbKey === '') {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => ['message' => 'imgbb_key_not_configured_on_server']]);
        exit;
    }
    $targetUrl = 'https://api.imgbb.com/1/upload?key=' . rawurlencode($imgbbKey);
}

$postFields = [
    'image' => new CURLFile($tmpPath, $mime, (string)($file['name'] ?? 'image')),
];

$ch = curl_init($targetUrl);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postFields,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS => 3,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_USERAGENT => 'AhadMartUploadProxy/1.0',
]);
$body = curl_exec($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if (!is_string($body) || $body === '') {
    http_response_code(502);
    echo json_encode(['success' => false, 'error' => ['message' => 'upstream_upload_failed', 'detail' => $curlError]]);
    exit;
}

http_response_code($httpCode > 0 ? $httpCode : 502);
echo $body;
