<?php
    session_start();
    /*if(empty($_SESSION['login_appquadrata'])){
        echo"<script language='javascript'>window.location='../../../login/'</script>;";
        exit();
    }*/
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['Upload_Image_File'])) {
    $upload_dir = 'uploads/';
    if (!file_exists($upload_dir) && !is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Generar un nombre único para la imagen
    $file_name = uniqid() . '_' . basename($_FILES['Upload_Image_File']['name']);
    $target_file = $upload_dir . $file_name;

    if (move_uploaded_file($_FILES['Upload_Image_File']['tmp_name'], $target_file)) {
        echo "<script>
                alert('Imagen subida exitosamente.');
                window.opener.postMessage({ success: true, path: '$target_file' }, '*');
                window.close();
              </script>";
        exit;
    } else {
        echo "<script>alert('Error al subir la imagen.');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subir Imagen</title>
    <script src="https://cdn.jsdelivr.net/npm/cropperjs@1.5.13/dist/cropper.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cropperjs@1.5.13/dist/cropper.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f9;
        }
        #preview {
            max-width: 100%;
            max-height: 400px;
            margin-top: 20px;
            display: none;
        }
    </style>
</head>
<body>
    <h2>Subir Imagen</h2>
    <form id="uploadForm" method="POST" enctype="multipart/form-data">
        <input type="file" name="Upload_Image_File" id="fileInput" accept="image/*" required>
        <img id="preview" alt="Vista previa">
        <button type="button" id="cropButton" style="display:none;">Recortar y Subir</button>
        <button type="submit" id="uploadButton">Subir</button>
    </form>

    <script>
        const fileInput = document.getElementById('fileInput');
        const preview = document.getElementById('preview');
        const cropButton = document.getElementById('cropButton');
        const uploadButton = document.getElementById('uploadButton');
        let cropper;

        fileInput.addEventListener('change', () => {
            const file = fileInput.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    if (cropper) cropper.destroy();
                    cropper = new Cropper(preview, {
                        aspectRatio: 1, // Cuadrado perfecto
                        viewMode: 1
                    });
                    cropButton.style.display = 'inline-block';
                    uploadButton.style.display = 'none';
                };
                reader.readAsDataURL(file);
            }
        });

        cropButton.addEventListener('click', () => {
            const canvas = cropper.getCroppedCanvas();
            canvas.toBlob((blob) => {
                const croppedFile = new File([blob], fileInput.files[0].name, { type: 'image/jpeg' });
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(croppedFile);
                fileInput.files = dataTransfer.files;

                // Mostrar botón de subir
                cropButton.style.display = 'none';
                uploadButton.style.display = 'inline-block';
            });
        });
    </script>
</body>
</html>
