<?php
$uploadDir = 'uploads/';
$success = false;
$errors = [];

// Ruta de la marca de agua
$watermarkPath = 'https://anacondatraveltours.com/wp-content/uploads/2024/06/anacondita.png';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_POST['download_zip'])) {
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $name) {
            $tmpName = $_FILES['images']['tmp_name'][$key];
            $fileSize = $_FILES['images']['size'][$key];
            $fileType = $_FILES['images']['type'][$key];
            $fileExt = strtolower(pathinfo($name, PATHINFO_EXTENSION));

            $validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            if (!in_array($fileExt, $validExtensions)) {
                $errors[] = "$name no es un formato válido. Solo se permiten JPG, JPEG, PNG, GIF y WEBP.";
                continue;
            }

            if ($fileSize > 9000000) {
                $errors[] = "$name es demasiado grande. El tamaño máximo es 9MB.";
                continue;
            }

            $newName = uniqid('', true) . ".$fileExt";
            $uploadFile = $uploadDir . $newName;

            if (move_uploaded_file($tmpName, $uploadFile)) {
                // Redimensionar imagen
                if (resizeImage($uploadFile, $uploadFile, 800, 600)) {
                    // Agregar la marca de agua
                    addWatermark($uploadFile, $watermarkPath);
                    $success = true;
                } else {
                    $errors[] = "Hubo un problema al redimensionar la imagen $name.";
                }
            } else {
                $errors[] = "Hubo un problema al subir $name.";
            }
        }
    } else {
        $errors[] = "No se seleccionaron imágenes para subir.";
    }

    if ($success) {
        // Redireccionar a la misma página para evitar resubir al actualizar
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit();
    }
}

if (isset($_POST['download_zip'])) {
    $zip = new ZipArchive();
    $zipName = 'imagenes.zip';
    if ($zip->open($zipName, ZipArchive::CREATE) !== TRUE) {
        exit("No se puede abrir el archivo ZIP.");
    }

    foreach (glob($uploadDir . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE) as $file) {
        $zip->addFile($file, basename($file));
    }

    $zip->close();

    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename=' . $zipName);
    header('Content-Length: ' . filesize($zipName));

    readfile($zipName);
    unlink($zipName);
    exit;
}

function resizeImage($source, $destination, $maxWidth, $maxHeight) {
    $imageInfo = getimagesize($source);
    $sourceWidth = $imageInfo[0];
    $sourceHeight = $imageInfo[1];
    $mime = $imageInfo['mime'];

    $ratio = $sourceWidth / $sourceHeight;
    if ($maxWidth / $maxHeight > $ratio) {
        $newHeight = $maxHeight;
        $newWidth = $maxHeight * $ratio;
    } else {
        $newWidth = $maxWidth;
        $newHeight = $maxWidth / $ratio;
    }

    switch ($mime) {
        case 'image/jpeg':
            $sourceImage = imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $sourceImage = imagecreatefrompng($source);
            break;
        case 'image/gif':
            $sourceImage = imagecreatefromgif($source);
            break;
        default:
            return false;
    }

    $targetImage = imagecreatetruecolor($newWidth, $newHeight);
    if ($mime == 'image/png' || $mime == 'image/gif') {
        imagecolortransparent($targetImage, imagecolorallocatealpha($targetImage, 0, 0, 0, 127));
        imagealphablending($targetImage, false);
        imagesavealpha($targetImage, true);
    }
    imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);

    switch ($mime) {
        case 'image/jpeg':
            imagejpeg($targetImage, $destination, 90);
            break;
        case 'image/png':
            imagepng($targetImage, $destination, 9);
            break;
        case 'image/gif':
            imagegif($targetImage, $destination);
            break;
    }

    imagedestroy($sourceImage);
    imagedestroy($targetImage);

    return true;
}

function addWatermark($imagePath, $watermarkPath) {
    $image = imagecreatefromstring(file_get_contents($imagePath));
    $watermark = imagecreatefrompng($watermarkPath);

    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);
    $watermarkWidth = imagesx($watermark);
    $watermarkHeight = imagesy($watermark);

    // Redimensionar la marca de agua proporcionalmente al 30% del ancho de la imagen
    $newWatermarkWidth = $imageWidth * 0.3;
    $newWatermarkHeight = ($newWatermarkWidth / $watermarkWidth) * $watermarkHeight;

    $resizedWatermark = imagecreatetruecolor($newWatermarkWidth, $newWatermarkHeight);
    imagealphablending($resizedWatermark, false);
    imagesavealpha($resizedWatermark, true);
    imagecopyresampled($resizedWatermark, $watermark, 0, 0, 0, 0, $newWatermarkWidth, $newWatermarkHeight, $watermarkWidth, $watermarkHeight);

    // Posicionar la marca de agua en la esquina inferior derecha
    $x = $imageWidth - $newWatermarkWidth - 10; // 10px de margen desde la derecha
    $y = $imageHeight - $newWatermarkHeight - 10; // 10px de margen desde abajo

    imagecopy($image, $resizedWatermark, $x, $y, 0, 0, $newWatermarkWidth, $newWatermarkHeight);
    imagejpeg($image, $imagePath, 90);

    imagedestroy($image);
    imagedestroy($watermark);
    imagedestroy($resizedWatermark);
}
?>

<!DOCTYPE html>
<html>
<head>
    
    <title>Subir y procesar imagenes</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #B5FFB5;
            padding: 20px;
        }
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 20px;
            background-color: #fff;
            border-bottom: 2px solid #ccc;
        }
        .header img {
            height: 50px;
        }
        .header nav a {
            margin-left: 20px;
            text-decoration: none;
            color: #000;
            font-weight: bold;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #fff;
            padding: 50px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
        }
        form {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        input[type="file"] {
            margin: 20px 0;
        }
        .buttons {
            display: flex;
            justify-content: space-between;
            width: 100%;
        }
        .buttons button, .buttons a {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            color: #fff;
            background-color: #008000;
            text-align: center;
        }
        .buttons button:hover, .buttons a:hover {
            background-color: #0056b3;
        }
        .message {
            margin: 20px 0;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
        .progress-container {
            width: 100%;
            background-color: #f3f3f3;
            border-radius: 5px;
            overflow: hidden;
            margin-top: 20px;
        }
        .progress-bar {
            height: 25px;
            background-color: #007bff;
            width: 0%;
            text-align: center;
            line-height: 25px;
            color: white;
            transition: width 0.4s ease;
        }
    </style>
    <script>
        function uploadImages(event) {
            event.preventDefault();
            const fileInput = document.querySelector('input[type="file"]');
            if (fileInput.files.length === 0) {
                alert('Por favor, selecciona al menos una imagen para subir.');
                return;
            }

            const formData = new FormData(event.target);
            const xhr = new XMLHttpRequest();
            const progressBar = document.getElementById('progress-bar');

            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressBar.style.width = percentComplete + '%';
                    progressBar.textContent = Math.round(percentComplete) + '%';
                }
            });

            xhr.addEventListener('load', function() {
                if (xhr.status == 200) {
                    alert('Las imágenes se han subido y procesado correctamente.');
                    location.reload();
                } else {
                    alert('Error al subir las imágenes.');
                }
            });

            xhr.open('POST', '', true);
            xhr.send(formData);
        }
    </script>
</head>
<body>
    <div class="header">
        <img src="http://descubresanmartin.com/images/Desc.SanMartin2.png" alt="Logo">
        <nav>
            <a href="index.php">Inicio</a>
            <a href="about.php">Acerca de</a>
            <a href="contact.php">Contacto</a>
        </nav>
    </div>

    <div class="container">
        <h1>Subir y procesar imagenes</h1>
        <form method="post" enctype="multipart/form-data" onsubmit="uploadImages(event)">
            <input type="file" name="images[]" multiple>
            <div class="buttons">
                <button type="submit">Subir imagenes</button>
            </div>
            <div class="progress-container">
                <div id="progress-bar" class="progress-bar">0%</div>
            </div>
        </form>
        
        <form method="post" style="margin-top: 20px;">
            <div class="buttons">
                <button type="submit" name="download_zip">Descargar todas las imagenes</button>
                <a href="ver.php" class="button">Visualizar imagenes</a>
            </div>
        </form>

        <?php if ($success): ?>
            <div class="message success">Imagenes subidas y procesadas con exito.</div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div class="message error">
                <?php foreach ($errors as $error): ?>
                    <p><?php echo $error; ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
