<?php

// Utilidades de imágenes: generación de WebP y miniaturas (GD)

function mediaEnsureDirs(): void {
    $base = __DIR__ . '/../assets/img';
    @mkdir($base . '/optimized', 0755, true);
    @mkdir($base . '/thumbs', 0755, true);
}

function mediaSupported(string $path): bool {
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    return in_array($ext, ['jpg', 'jpeg', 'png', 'webp'], true);
}

function mediaLoad(string $path) {
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    switch ($ext) {
        case 'jpg':
        case 'jpeg': return function_exists('imagecreatefromjpeg') ? @imagecreatefromjpeg($path) : null;
        case 'png': return function_exists('imagecreatefrompng') ? @imagecreatefrompng($path) : null;
        case 'webp': return function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($path) : null;
        default: return null;
    }
}

function mediaSaveWebp($image, string $dest, int $quality = 82): bool {
    if (!function_exists('imagewebp')) return false;
    $ok = @imagewebp($image, $dest, $quality);
    if ($ok) { @chmod($dest, 0644); }
    return (bool)$ok;
}

function mediaResize($srcImg, int $targetW, int $targetH) {
    if (!function_exists('imagecreatetruecolor')) return null;
    $w = imagesx($srcImg); $h = imagesy($srcImg);
    $ratio = min($targetW / $w, $targetH / $h);
    $nw = max(1, (int)floor($w * $ratio));
    $nh = max(1, (int)floor($h * $ratio));
    $dst = imagecreatetruecolor($nw, $nh);
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
    imagecopyresampled($dst, $srcImg, 0, 0, 0, 0, $nw, $nh, $w, $h);
    return $dst;
}

// Optimización automática de imágenes para web
function optimizeImageForWeb(string $sourcePath, string $destPath, int $maxWidth = 1200, int $quality = 85): bool {
    if (!function_exists('imagecreatefromjpeg') || !function_exists('imagejpeg')) {
        return false; // GD no disponible
    }
    
    $extension = strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION));
    
    // Cargar imagen según tipo
    $sourceImage = null;
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $sourceImage = @imagecreatefromjpeg($sourcePath);
            break;
        case 'png':
            $sourceImage = @imagecreatefrompng($sourcePath);
            break;
        case 'webp':
            if (function_exists('imagecreatefromwebp')) {
                $sourceImage = @imagecreatefromwebp($sourcePath);
            }
            break;
    }
    
    if (!$sourceImage) return false;
    
    // Obtener dimensiones originales
    $originalWidth = imagesx($sourceImage);
    $originalHeight = imagesy($sourceImage);
    
    // Calcular nuevas dimensiones manteniendo proporción
    if ($originalWidth <= $maxWidth) {
        // No necesita redimensionar
        $newWidth = $originalWidth;
        $newHeight = $originalHeight;
    } else {
        $ratio = $maxWidth / $originalWidth;
        $newWidth = $maxWidth;
        $newHeight = (int)($originalHeight * $ratio);
    }
    
    // Crear nueva imagen redimensionada
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // Preservar transparencia para PNG
    if ($extension === 'png') {
        imagealphablending($newImage, false);
        imagesavealpha($newImage, true);
        $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
        imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
    }
    
    // Redimensionar
    imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    
    // Guardar imagen optimizada
    $success = false;
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $success = @imagejpeg($newImage, $destPath, $quality);
            break;
        case 'png':
            $success = @imagepng($newImage, $destPath, 9); // PNG compression level 0-9
            break;
        case 'webp':
            if (function_exists('imagewebp')) {
                $success = @imagewebp($newImage, $destPath, $quality);
            }
            break;
    }
    
    // Limpiar memoria
    imagedestroy($sourceImage);
    imagedestroy($newImage);
    
    return $success;
}

// Generar múltiples tamaños de imagen
function generateImageSizes(string $sourcePath): array {
    $sizes = [
        'thumb' => ['width' => 300, 'height' => 200],
        'medium' => ['width' => 600, 'height' => 400], 
        'large' => ['width' => 1200, 'height' => 800]
    ];
    
    $results = [];
    $baseName = pathinfo($sourcePath, PATHINFO_FILENAME);
    $extension = pathinfo($sourcePath, PATHINFO_EXTENSION);
    $dir = dirname($sourcePath);
    
    foreach ($sizes as $size => $dimensions) {
        $destPath = $dir . '/optimized/' . $baseName . '_' . $size . '.' . $extension;
        
        // Crear directorio si no existe
        $optimizedDir = dirname($destPath);
        if (!is_dir($optimizedDir)) {
            @mkdir($optimizedDir, 0755, true);
        }
        
        if (optimizeImageForWeb($sourcePath, $destPath, $dimensions['width'])) {
            $results[$size] = $destPath;
        }
    }
    
    return $results;
}

// Empareja imágenes: mapping.json > sufijos -antes/-despues > pares consecutivos
function mediaPairBeforeAfter(string $galleryDir): array {
    $pairs = [];

    // 1) mapping.json
    $mapFile = $galleryDir . '/mapping.json';
    if (file_exists($mapFile)) {
        $json = json_decode(file_get_contents($mapFile), true);
        if (is_array($json)) {
            foreach ($json as $entry) {
                if (!isset($entry['before'], $entry['after'])) continue;
                $b = $galleryDir . '/' . $entry['before'];
                $a = $galleryDir . '/' . $entry['after'];
                if (file_exists($b) && file_exists($a)) {
                    $pairs[] = [$b, $a];
                }
            }
            if ($pairs) return $pairs;
        }
    }

    // 2) sufijos -antes / -despues
    $files = glob($galleryDir . '/*.{jpg,jpeg,png,webp}', GLOB_BRACE) ?: [];
    $byKey = [];
    foreach ($files as $f) {
        $name = pathinfo($f, PATHINFO_FILENAME);
        if (preg_match('/(.+)-(antes|despues)$/i', $name, $m)) {
            $key = strtolower($m[1]);
            $type = strtolower($m[2]);
            if (!isset($byKey[$key])) $byKey[$key] = [];
            $byKey[$key][$type] = $f;
        }
    }
    foreach ($byKey as $key => $group) {
        if (isset($group['antes'], $group['despues'])) {
            $pairs[] = [$group['antes'], $group['despues']];
        }
    }
    if ($pairs) return $pairs;

    // 3) pares consecutivos por nombre
    sort($files, SORT_NATURAL | SORT_FLAG_CASE);
    for ($i = 0; $i + 1 < count($files); $i += 2) {
        $pairs[] = [$files[$i], $files[$i+1]];
    }
    return $pairs;
}

// Genera mapping.json automáticamente: prioriza sufijos -antes/-despues, luego pares por nombre
function mediaGenerateMapping(string $galleryDir, string $mapFile): bool {
    $pairs = [];
    $files = glob($galleryDir . '/*.{jpg,jpeg,png,webp}', GLOB_BRACE) ?: [];
    $byKey = [];
    foreach ($files as $f) {
        $name = pathinfo($f, PATHINFO_FILENAME);
        if (preg_match('/(.+)-(antes|despues)$/i', $name, $m)) {
            $key = strtolower($m[1]);
            $type = strtolower($m[2]);
            if (!isset($byKey[$key])) $byKey[$key] = [];
            $byKey[$key][$type] = basename($f);
        }
    }
    foreach ($byKey as $key => $g) {
        if (isset($g['antes'], $g['despues'])) {
            $pairs[] = ['before' => $g['antes'], 'after' => $g['despues']];
        }
    }
    if (empty($pairs)) {
        sort($files, SORT_NATURAL | SORT_FLAG_CASE);
        for ($i = 0; $i + 1 < count($files); $i += 2) {
            $pairs[] = ['before' => basename($files[$i]), 'after' => basename($files[$i+1])];
        }
    }
    $json = json_encode($pairs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    return (bool)@file_put_contents($mapFile, $json);
}

?>


