<?php
/**
 * API de Upload - Plataforma Especificar
 * Integração: Bubble.io → Servidor Devon
 * Criado: 2025-11-12
 * Versão: 1.0
 */

// Configurações
define('BASE_PATH', '/var/www/images/especificar');
define('LOG_FILE', '/var/log/upload-especificar.log');
define('MAX_FILE_SIZE', 5 * 1024 * 1024); // 5MB
define('ALLOWED_TYPES', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);

// Headers CORS
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Função de log
function logMessage($message, $data = null) {
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[{$timestamp}] {$message}";
    if ($data !== null) {
        $logEntry .= " | " . json_encode($data);
    }
    $logEntry .= PHP_EOL;
    
    if (!file_exists(LOG_FILE)) {
        touch(LOG_FILE);
        chmod(LOG_FILE, 0644);
    }
    
    file_put_contents(LOG_FILE, $logEntry, FILE_APPEND);
}

// Sanitizar nome
function sanitizeFilename($name) {
    $name = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $name);
    $name = strtolower($name);
    $name = preg_replace('/[^a-z0-9-]/', '-', $name);
    $name = preg_replace('/-+/', '-', $name);
    return trim($name, '-');
}

// Processar upload
try {
    
    logMessage('Nova requisição', [
        'method' => $_SERVER['REQUEST_METHOD'],
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Método não permitido. Use POST.');
    }
    
    if (!isset($_FILES['image'])) {
        throw new Exception('Nenhuma imagem enviada');
    }
    
    // Parâmetros
    $tipo = $_POST['tipo'] ?? 'brands';
    $identificador = $_POST['identificador'] ?? 'sem-identificador';
    $nomeArquivo = $_POST['nome_arquivo'] ?? 'imagem';
    
    logMessage('Parâmetros', compact('tipo', 'identificador', 'nomeArquivo'));
    
    // Validar tipo
    $tiposPermitidos = ['brands', 'pdvs', 'campanhas', 'especificadores', 'sistema'];
    if (!in_array($tipo, $tiposPermitidos)) {
        throw new Exception("Tipo inválido. Use: " . implode(', ', $tiposPermitidos));
    }
    
    // Sanitizar
    $identificador = sanitizeFilename($identificador);
    $nomeArquivo = sanitizeFilename($nomeArquivo);
    
    // Arquivo
    $tmpFile = $_FILES['image']['tmp_name'];
    $fileSize = $_FILES['image']['size'];
    $fileError = $_FILES['image']['error'];
    
    if ($fileError !== UPLOAD_ERR_OK) {
        throw new Exception("Erro no upload: código {$fileError}");
    }
    
    if ($fileSize > MAX_FILE_SIZE) {
        throw new Exception('Arquivo muito grande (máximo 5MB)');
    }
    
    if ($fileSize === 0) {
        throw new Exception('Arquivo vazio');
    }
    
    // Validar MIME
    $fileType = mime_content_type($tmpFile);
    if (!in_array($fileType, ALLOWED_TYPES)) {
        throw new Exception('Tipo não permitido. Use: JPG, PNG, GIF ou WebP');
    }
    
    logMessage('Validado', ['size' => $fileSize, 'type' => $fileType]);
    
    // Extensão
    $extension = match($fileType) {
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/gif' => 'gif',
        'image/webp' => 'webp',
        default => 'jpg'
    };
    
    // Timestamp
    $timestamp = time();
    $filename = "{$nomeArquivo}-{$timestamp}.{$extension}";
    
    // Caminho
    $relativePath = "/{$tipo}/{$identificador}";
    $fullPath = BASE_PATH . $relativePath;
    
    logMessage('Salvando', ['filename' => $filename, 'path' => $fullPath]);
    
    // Criar diretório
    if (!file_exists($fullPath)) {
        if (!mkdir($fullPath, 0755, true)) {
            throw new Exception('Erro ao criar diretório');
        }
        logMessage('Diretório criado', ['path' => $fullPath]);
    }
    
    // Destino
    $destinationPath = $fullPath . '/' . $filename;
    
    // Mover arquivo
    if (!move_uploaded_file($tmpFile, $destinationPath)) {
        throw new Exception('Erro ao salvar arquivo');
    }
    
    chmod($destinationPath, 0644);
    
    logMessage('Salvo', ['destination' => $destinationPath]);
    
    // URLs
    $urlOriginal = "https://imagens.devon.studio/especificar" . $relativePath . '/' . $filename;
    $urlWebp = $urlOriginal . '.webp';
    
    // Aguardar WebP (imagewatch)
    // Adiciona .webp apenas se ainda não tiver
    $webpPath = (pathinfo($destinationPath, PATHINFO_EXTENSION) === 'webp') 
        ? $destinationPath 
        : $destinationPath . '.webp';
    $waitTime = 0;
    $maxWait = 5;
    
    while (!file_exists($webpPath) && $waitTime < $maxWait) {
        sleep(1);
        $waitTime++;
    }
    
    $webpCreated = file_exists($webpPath);

    // Remove arquivo original após WebP ser criado (só se não for WebP)
    if ($webpCreated && pathinfo($destinationPath, PATHINFO_EXTENSION) !== 'webp') {
        unlink($destinationPath);
        logMessage('Original removido', ['path' => $destinationPath]);
    }
    
    logMessage('WebP', ['created' => $webpCreated, 'wait' => $waitTime]);
    
    // Resposta
    $response = [
        'success' => true,
        'url_original' => $urlOriginal,
        'url_webp' => $urlWebp,
        'webp_ready' => $webpCreated,
        'filename' => $filename,
        'size_original' => filesize($destinationPath),
        'size_webp' => $webpCreated ? filesize($webpPath) : null,
        'path' => $relativePath . '/' . $filename,
        'wait_time' => $waitTime,
        'timestamp' => $timestamp
    ];
    
    logMessage('Sucesso', $response);
    
    echo json_encode($response);
    
} catch (Exception $e) {
    
    logMessage('ERRO: ' . $e->getMessage());
    
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
