<?php
/**
 * TOPBD API — Secure 1:1 Image Upload Handler
 */

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['image'])) {
    json_response(['success' => false, 'message' => 'No image uploaded'], 400);
}

$file = $_FILES['image'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    json_response(['success' => false, 'message' => 'File upload failed with error code ' . $file['error']], 400);
}

// Size limit: 3MB
if ($file['size'] > 3 * 1024 * 1024) {
    json_response(['success' => false, 'message' => 'Image size exceeds maximum limit of 3MB'], 400);
}

// MIME type validation
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);

$allowedMimes = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/webp' => 'webp',
];

if (!isset($allowedMimes[$mime])) {
    json_response(['success' => false, 'message' => 'Invalid file format. Only JPG, PNG, and WebP are allowed.'], 400);
}

$ext = $allowedMimes[$mime];
$filename = 'topbd_avatar_' . bin2hex(random_bytes(10)) . '.' . $ext;
$uploadDir = __DIR__ . '/../uploads/';

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

$targetPath = $uploadDir . $filename;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    $publicUrl = '/uploads/' . $filename;
    json_response([
        'success' => true,
        'image_url' => $publicUrl,
        'message' => 'Image uploaded successfully'
    ]);
} else {
    json_response(['success' => false, 'message' => 'Failed to save uploaded file'], 500);
}
