<?php
// cms/solution-update.php
header('Content-Type: application/json');

// 1. INCLUIR OPTIMIZADOR Y DB
require_once('image_optimizer.php'); 
require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método No Permitido']);
    exit;
}

// Directorios y variables
$uploadDirBase = 'uploads/solution/';
$uploadDirFull = '../' . $uploadDirBase; 

if (!is_dir($uploadDirFull)) {
    mkdir($uploadDirFull, 0777, true);
}

/**
 * Procesa la subida de archivo: optimiza, redimensiona y fuerza la conversi\u00f3n a WebP.
 * @param string $fileInputName Nombre del campo en $_FILES.
 * @param string $baseUploadDir Ruta base para guardar en DB.
 * @return string|null La ruta relativa final para la DB (ej: 'uploads/solution/nombre.webp'), o null si no se subi\u00f3 un nuevo archivo.
 */
function handleOptimizedUpload($fileInputName, $baseUploadDir) {
    if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] !== UPLOAD_ERR_OK) {
        return null;
    }
    
    $file = $_FILES[$fileInputName];
    $tempPath = $file['tmp_name'];

    // *** REGLA DE RESOLUCIÓN Y WEBP ***
    $maxWidth = 1280; // Ancho para imagen lateral
    
    $fileName = uniqid('solution_img_') . '.webp'; // Fuerza la extensi\u00f3n a WEBP
    $destinationPathFull = '../' . $baseUploadDir . $fileName;

    // Llama a la funci\u00f3n de optimizaci\u00f3n
    $success = optimizeAndSaveImage($tempPath, $destinationPathFull, $maxWidth);

    if (!$success) {
        throw new Exception("Error al optimizar la imagen '{$fileInputName}'. Método No Permitido");
    }
    
    // Devuelve la ruta relativa para guardar en la base de datos
    return $baseUploadDir . $fileName;
}

/**
 * Elimina un archivo si existe y si no es una ruta de fallback o URL absoluta.
 * @param string|null $dbPath La ruta guardada en la base de datos.
 */
function deleteOldImage(?string $dbPath): void {
    if ($dbPath && !str_starts_with($dbPath, 'img/') && !str_starts_with($dbPath, 'https://') && !str_starts_with($dbPath, 'http://')) {
        $fullPath = '../' . $dbPath; 
        if (file_exists($fullPath) && is_writable($fullPath)) {
            unlink($fullPath);
            // error_log("Old solution image deleted: " . $fullPath); 
        }
    }
}

try {
    $pdo->beginTransaction();
    
    // 1. Obtener la ruta de imagen actual antes de subir la nueva
    $stmtCurrent = $pdo->query("SELECT solution_main_image FROM cms_solution WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    $old_main_image = $stmtCurrent ? $stmtCurrent['solution_main_image'] : null;
    $main_image_path = $old_main_image; // Valor por defecto

    // 2. Procesar la subida y optimizaci\u00f3n de la imagen principal
    $new_main_path = handleOptimizedUpload('solution-main-image-upload', $uploadDirBase);
    
    if ($new_main_path) {
        $main_image_path = $new_main_path;
        deleteOldImage($old_main_image); // Eliminar la imagen anterior
    } elseif (isset($_POST['current-main-image']) && !empty($_POST['current-main-image'])) {
        // Mantener la ruta existente del campo oculto si no se subió un archivo nuevo
        $main_image_path = strip_tags($_POST['current-main-image']);
    } else {
        // Si no hay imagen nueva y el campo oculto está vacío, se pone nulo.
        $main_image_path = null; 
    }

    // 3. LIMPIAR Y PREPARAR DATOS DE TEXTO (Usando strip_tags despu\u00e9s de html_entity_decode)
    $badge = strip_tags(html_entity_decode($_POST['solution-badge'] ?? '', ENT_QUOTES, 'UTF-8'));
    $title1 = strip_tags(html_entity_decode($_POST['solution-title-1'] ?? '', ENT_QUOTES, 'UTF-8'));
    $title2 = strip_tags(html_entity_decode($_POST['solution-title-2'] ?? '', ENT_QUOTES, 'UTF-8'));
    $description = strip_tags(html_entity_decode($_POST['solution-description'] ?? '', ENT_QUOTES, 'UTF-8'));

    // 4. ACTUALIZAR DATOS GENERALES
    $sql = "UPDATE cms_solution SET 
                solution_badge = ?, 
                solution_title_1 = ?, 
                solution_title_2 = ?, 
                solution_description = ?, 
                solution_main_image = ? 
            WHERE id = 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$badge, $title1, $title2, $description, $main_image_path]);

    // 5. MANEJO DE BENEFICIOS
    $benefits_json = $_POST['benefits_json'] ?? '[]';
    $benefits = json_decode($benefits_json, true);

    $pdo->prepare("DELETE FROM cms_solution_benefits WHERE solution_id = 1")->execute();

    if (is_array($benefits) && !empty($benefits)) {
        $sql_insert = "INSERT INTO cms_solution_benefits (solution_id, benefit_icon, benefit_title, benefit_description) VALUES (1, ?, ?, ?)";
        $stmt_insert = $pdo->prepare($sql_insert);
        foreach ($benefits as $benefit) {
            $b_icon = strip_tags(html_entity_decode($benefit['icon'] ?? 'check-circle', ENT_QUOTES, 'UTF-8'));
            $b_title = strip_tags(html_entity_decode($benefit['title'] ?? '', ENT_QUOTES, 'UTF-8'));
            $b_description = strip_tags(html_entity_decode($benefit['description'] ?? '', ENT_QUOTES, 'UTF-8'));
            
            if (!empty($b_title)) {
                 $stmt_insert->execute([$b_icon, $b_title, $b_description]);
            }
        }
    }

    $pdo->commit();
    echo json_encode([
        'success' => true, 
        'message' => 'SiteFlow Actualizado Exitosamente',
        'data' => [
            'solution_main_image' => $main_image_path
        ]
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error al guardar: ' . $e->getMessage()]);
}
?>