<?php
// ============================================================
// Design2Clothes — Upload API
// Handle file uploads (PNG, JPG, SVG) into session-scoped directories
// ============================================================
session_name('d2c_session');
session_start();
require_once __DIR__ . '/../config.php';

d2c_cors_headers();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    d2c_error('Method not allowed', 405);
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    d2c_error('No file uploaded or upload error');
}

$file = $_FILES['file'];

// Validate file size
if ($file['size'] > MAX_UPLOAD_SIZE) {
    d2c_error('File exceeds max size limit (' . (MAX_UPLOAD_SIZE / 1024 / 1024) . 'MB)');
}

// Validate mime
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mime, ALLOWED_MIMES)) {
    // Check fallback for SVG
    if ($mime !== 'text/plain' || pathinfo($file['name'], PATHINFO_EXTENSION) !== 'svg') {
         d2c_error("Unsupported file type: $mime. Allowed: " . implode(', ', ALLOWED_MIMES));
    }
}

// Validate extension
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXTS)) {
    d2c_error("Unsupported extension: .$ext");
}

// Session scoping: group uploads by session ID to avoid clutter
$sessId = session_id() ?: 'shared';
$uploadDir = UPLOAD_DIR . $sessId . '/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Sanitize filename & prevent overwriting easily
$filename = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $file['name']);
$filename = uniqid() . '_' . $filename;
$targetPath = $uploadDir . $filename;

if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
    d2c_error('Failed to save file to server directory');
}

// Generate URL for frontend
$url = APP_BASE_URL . '/media/uploads/' . $sessId . '/' . $filename;

d2c_json([
    'success'  => true,
    'filename' => $filename,
    'url'      => $url,
    'type'     => $mime,
    'size'     => $file['size']
]);
