<?php
// ============================================================
// Design2Clothes — Generate API
// Handles model generation, artwork application and exporting.
// Currently in MOCK mode until n8n webhook is provided.
// ============================================================
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);
}

$action = $_POST['action'] ?? '';

// Real implementation will use cURL to send this payload to N8N_WEBHOOK_CLOTHES
// For now, we mock responses based on action

// Hardcoded wait to simulate AI generation (useful for UI testing)
sleep(2);

switch ($action) {
    case 'model':
        // Payload: prompt, pose, type, fabric, color, predefined
        $prompt = $_POST['prompt'] ?? 'default_model';
        // Devuelve imagen placeholder generada dinámicamente según texto
        $mockUrl = "https://placehold.co/600x800/1B1B1B/6F2CFF?text=Generated+Model%0A" . rawurlencode($prompt) . "&font=inter";
        d2c_json(['success' => true, 'url' => $mockUrl]);
        break;

    case 'apply':
        // Payload: model_url, asset_url, scale, rotation, opacity, blending, prompt
        $blending = $_POST['blending'] ?? 'overlay';
        $scale = $_POST['scale'] ?? '100';
        $mockUrl = "https://placehold.co/600x800/171717/FF6A00?text=Applied+Design%0A" . rawurlencode("Blend: {$blending} | Scale: {$scale}%") . "&font=inter";
        d2c_json(['success' => true, 'url' => $mockUrl]);
        break;

    case 'export':
        // Payload: source_url, resolution, format
        $format = $_POST['format'] ?? 'png';
        $res = $_POST['resolution'] ?? '4k';
        $mockUrl = "https://placehold.co/1080x1350/000000/FFFFFF?text=Export+Ready%0A{$res}+{$format}&font=inter";
        $filename = "d2c_export_" . date('Ymd_His') . ".{$format}";
        d2c_json(['success' => true, 'url' => $mockUrl, 'filename' => $filename]);
        break;

    default:
        d2c_error("Unknown action: $action");
}
