<?php
include 'includes/config.php';

$item_id = $_GET['item_id'] ?? 0;
$precio_fijo = $_GET['precio'] ?? 0;

// Verificar que el item existe
$sql = "SELECT * FROM items WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$item_id]);
$item = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$item) {
    header("Location: index.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Formulario de Donación ADRA</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
    /* ========================================== */
    /* VARIABLES DE COLORES - PALETA OFICIAL ADRA */
    /* ========================================== */
    :root {
        /* Colores Primarios ADRA */
        --adra-red: #D50032;           /* CHRISTMAS RED - Color principal */
        --adra-deep-red: #992A31;      /* CHRISTMAS DEEP RED - Color oscuro */
        --adra-cream: #F8F0E4;         /* CREAM - Fondo suave */
        
        /* Colores Secundarios ADRA */
        --adra-gold: #C1A01E;          /* GOLD 20 - Acentos dorados */
        --adra-pale-blue: #E6F5FA;     /* PALE BLUE - Fondos información */
        --adra-white: #FFFFFF;         /* WHITE - Fondos principales */
        
        /* Colores de Texto */
        --text-dark: #333333;          /* Texto principal */
        --text-medium: #666666;        /* Texto secundario */
        --text-light: #999999;         /* Texto terciario */
        
        /* Metal plomo para el dispensador */
        --solid-metal: #3E3E3E;
        --solid-metal-dark: #2C2C2C;
        --solid-metal-light: #505050;
        --solid-metal-border: #555555;
    }

    /* ========================================== */
    /* RESET Y CONFIGURACIÓN BASE */
    /* ========================================== */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    /* Prevención de scroll en toda la página */
    html, body {
        height: 100%;
        width: 100%;
        overflow: hidden;
        position: fixed;
        /* Fondo negro de respaldo */
        background-color: #000000;
    }

    /* ========================================== */
    /* BODY - FONDO CON IMAGEN NAVIDEÑA */
    /* ========================================== */
    body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
        /* FONDO NAVIDEÑO CON GRADIENTE OSCURO PARA CONTRASTE */
        background: 
            linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)),
            url('fondo-navidad.jpeg') no-repeat center center fixed;
        background-size: cover;
        background-color: #000000; /* Color de respaldo */
        color: var(--text-dark);
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 16px;
        -webkit-text-size-adjust: 100%;
        min-height: 100vh;
        min-width: 100vw;
    }

    /* Media query para modo claro - asegurar que el fondo se vea bien */
    @media (prefers-color-scheme: light) {
        body {
            background: 
                linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)),
                url('fondo-navidad.jpeg') no-repeat center center fixed;
            background-size: cover;
            background-color: #000000;
        }
    }

    /* ========================================== */
    /* CONTENEDOR PRINCIPAL DEL FORMULARIO */
    /* ========================================== */
    .donation-container {
        width: 100%;
        max-width: 100%;
        height: auto;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    /* ========================================== */
    /* TARJETA DEL FORMULARIO */
    /* ========================================== */
    .donation-card {
        background: rgba(255, 255, 255, 0.95);
        border-radius: 12px;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.25);
        width: 100%;
        /* Borde rojo profundo ADRA */
        border: 2px solid var(--adra-deep-red);
        overflow: hidden;
        max-width: 380px;
        margin: 0 auto;
        backdrop-filter: blur(3px);
    }

    @supports not (backdrop-filter: blur(3px)) {
        .donation-card {
            background: rgba(255, 255, 255, 0.98);
        }
    }

    /* ========================================== */
    /* ENCABEZADO DEL FORMULARIO */
    /* ========================================== */
    .donation-header {
        /* Gradiente ADRA en el encabezado */
        background: linear-gradient(135deg, 
            var(--adra-deep-red) 0%, 
            var(--adra-red) 50%, 
            var(--adra-gold) 100%
        );
        color: var(--adra-white);
        padding: 14px 16px;
        text-align: center;
        border-bottom: 2px solid var(--adra-deep-red);
    }

    .donation-header h1 {
        font-size: 16px;
        font-weight: 800;
        margin-bottom: 4px;
        line-height: 1.2;
    }

    .donation-header p {
        font-size: 12px;
        opacity: 0.9;
        margin-bottom: 0;
        line-height: 1.3;
    }

    /* ========================================== */
    /* CUERPO DEL FORMULARIO */
    /* ========================================== */
    .donation-body {
        padding: 16px;
    }

    /* ========================================== */
    /* INFORMACIÓN DEL BENEFICIARIO */
    /* ========================================== */
    .beneficiary-info {
        text-align: center;
        margin-bottom: 16px;
        padding-bottom: 14px;
        border-bottom: 1px solid var(--adra-cream);
    }

    /* IMAGEN PROTAGONISTA DEL ITEM */
    .beneficiary-image {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        overflow: hidden;
        /* Borde rojo ADRA */
        border: 3px solid var(--adra-red);
        margin: 0 auto 8px auto;
        /* Fondo degradado ADRA si no hay imagen */
        background: linear-gradient(135deg, 
            var(--adra-cream), 
            var(--adra-pale-blue)
        );
        box-shadow: 0 4px 12px rgba(213, 0, 50, 0.3);
    }

    .beneficiary-image img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .beneficiary-image i {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2.5rem;
        color: var(--adra-red);
    }

    /* NOMBRE DEL ITEM */
    .beneficiary-details h2 {
        color: var(--adra-red);
        font-weight: 700;
        margin-bottom: 4px;
        font-size: 15px;
        line-height: 1.2;
    }

    /* PRECIO DISCRETO DEL ITEM */
    .beneficiary-price {
        font-size: 0.95rem;
        font-weight: 700;
        color: var(--adra-red);
        /* Fondo crema suave ADRA */
        background: var(--adra-cream);
        padding: 4px 12px;
        border-radius: 15px;
        display: inline-block;
        margin-top: 4px;
        /* Borde dorado ADRA */
        border: 1px solid var(--adra-gold);
    }

    /* ========================================== */
    /* SECCIONES DEL FORMULARIO */
    /* ========================================== */
    .form-section {
        margin-bottom: 14px;
    }

    /* Títulos de las secciones */
    .section-title {
        font-weight: 700;
        color: var(--text-dark);
        margin-bottom: 6px;
        font-size: 14px;
        line-height: 1.2;
    }

    /* Indicador de campo requerido */
    .required::after {
        content: " *";
        color: var(--adra-red);
    }

    /* ========================================== */
    /* CAMPOS DE ENTRADA (INPUTS) */
    /* ========================================== */
    .form-control {
        border: none;
        /* Borde inferior estilo ADRA */
        border-bottom: 1px solid var(--adra-gold);
        border-radius: 0;
        padding: 8px 0;
        font-size: 14px;
        transition: all 0.3s ease;
        background: transparent;
        width: 100%;
    }

    .form-control::placeholder {
        color: var(--text-light);
        font-size: 13px;
    }

    /* Estado focus de los inputs */
    .form-control:focus {
        border-color: var(--adra-red);
        box-shadow: none;
        outline: none;
    }

    /* ========================================== */
    /* CHECKBOX DE DONACIÓN ANÓNIMA */
    /* ========================================== */
    .anonymous-section {
        /* Fondo azul pálido ADRA */
        background: var(--adra-pale-blue);
        padding: 10px;
        border-radius: 6px;
        margin-bottom: 14px;
        /* Borde dorado ADRA */
        border: 1px solid var(--adra-gold);
    }

    .form-check-input {
        /* Borde rojo ADRA */
        border-color: var(--adra-red);
    }

    .form-check-input:checked {
        /* Fondo rojo ADRA cuando está marcado */
        background-color: var(--adra-red);
        border-color: var(--adra-red);
    }

    .form-check-label {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-dark);
        margin-left: 6px;
    }

    .anonymous-note {
        font-size: 11px;
        color: var(--text-medium);
        margin-top: 4px;
        font-style: italic;
    }

    /* ========================================== */
    /* BOTONES DE ACCIÓN */
    /* ========================================== */
    .buttons-section {
        margin-top: 18px;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    /* Botón principal de donar */
    .donate-btn {
        /* Gradiente rojo ADRA */
        background: linear-gradient(135deg, 
            var(--adra-red) 0%, 
            var(--adra-deep-red) 100%
        );
        color: var(--adra-white);
        border: none;
        border-radius: 8px;
        padding: 12px;
        font-size: 14px;
        font-weight: 700;
        width: 100%;
        transition: all 0.3s ease;
        /* Sombra roja ADRA */
        box-shadow: 0 4px 10px rgba(213, 0, 50, 0.3);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        position: relative;
    }

    .donate-btn:hover {
        background: linear-gradient(135deg, 
            var(--adra-deep-red) 0%, 
            var(--adra-red) 100%
        );
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(213, 0, 50, 0.4);
    }

    .donate-btn:disabled {
        opacity: 0.7;
        cursor: not-allowed;
        transform: none;
    }

    .donate-btn.processing {
        background: linear-gradient(135deg, 
            #6c757d 0%, 
            #495057 100%
        );
    }

    .donate-btn .btn-text {
        transition: opacity 0.3s ease;
    }

    .donate-btn .processing-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0;
        transition: opacity 0.3s ease;
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .donate-btn.processing .btn-text {
        opacity: 0;
    }

    .donate-btn.processing .processing-text {
        opacity: 1;
    }

    /* ========================================== */
    /* ENLACE PARA VOLVER */
    /* ========================================== */
    .back-link {
        text-align: center;
    }

    .back-link a {
        color: var(--adra-red);
        text-decoration: none;
        font-weight: 600;
        transition: color 0.3s ease;
        font-size: 12px;
        display: inline-block;
        padding: 4px 0;
    }

    .back-link a:hover {
        color: var(--adra-deep-red);
        text-decoration: underline;
    }

    /* ========================================== */
    /* RESPONSIVE - ADAPTACIÓN A TABLETS */
    /* ========================================== */
    @media (min-width: 768px) {
        body {
            padding: 20px;
        }
        
        .donation-card {
            max-width: 420px;
            border-radius: 14px;
        }
        
        .beneficiary-image {
            width: 130px;
            height: 130px;
        }

        .beneficiary-details h2 {
            font-size: 17px;
        }
    }

    /* ========================================== */
    /* RESPONSIVE - MÓVILES PEQUEÑOS */
    /* ========================================== */
    @media (max-width: 360px) {
        .beneficiary-image {
            width: 90px;
            height: 90px;
        }
    }

    /* ========================================== */
    /* RESPONSIVE - PANTALLAS BAJAS */
    /* ========================================== */
    @media (max-height: 650px) {
        .donation-body {
            padding: 12px;
        }

        .beneficiary-image {
            width: 90px;
            height: 90px;
            margin-bottom: 6px;
        }

        .form-section {
            margin-bottom: 10px;
        }

        .buttons-section {
            margin-top: 12px;
        }
    }

    /* Prevenir zoom en iOS móvil */
    @media (max-width: 480px) {
        input, select, textarea {
            font-size: 16px !important;
        }
    }

    /* Estilos específicos para modo claro */
    @media (prefers-color-scheme: light) {
        html, body {
            background-color: #000000 !important;
        }
    }
</style>
</head>
<body>
    <div class="donation-container">
        <div class="donation-card">
            <!-- ENCABEZADO -->
            <div class="donation-header">
                <h1>DATOS DEL DONANTE</h1>
                <p>Completa tu información para continuar</p>
            </div>
            
            <!-- CUERPO DEL FORMULARIO -->
            <div class="donation-body">
                <div class="form-content">
                    <!-- INFORMACIÓN DEL BENEFICIARIO -->
                    <div class="beneficiary-info">
                        <!-- IMAGEN PROTAGONISTA -->
                        <div class="beneficiary-image">
                            <?php if(!empty($item['imagen'])): ?>
                                <img src="<?php echo htmlspecialchars($item['imagen']); ?>" alt="<?php echo htmlspecialchars($item['nombre']); ?>">
                            <?php else: ?>
                                <i class="bi bi-gift"></i>
                            <?php endif; ?>
                        </div>
                        <div class="beneficiary-details">
                            <h2><?php echo htmlspecialchars($item['nombre']); ?></h2>
                            <!-- PRECIO DISCRETO -->
                            <div class="beneficiary-price">S/ <?php echo number_format($precio_fijo, 2); ?></div>
                        </div>
                    </div>

                    <!-- FORMULARIO -->
                    <form action="pago_qr.php" method="POST" id="formDonacion">
                        <input type="hidden" name="item_id" value="<?php echo $item['id']; ?>">
                        <input type="hidden" name="monto_fijo" value="<?php echo $precio_fijo; ?>">

                        <!-- CHECKBOX DONACIÓN ANÓNIMA -->
                        <div class="anonymous-section">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="anonimo" name="anonimo">
                                <label class="form-check-label" for="anonimo">
                                    Donar como anónimo
                                </label>
                            </div>
                            <div class="anonymous-note">
                                Si marcas esta opción, tu donación será completamente anónima
                            </div>
                        </div>

                        <!-- SECCIÓN NOMBRE (se oculta si es anónimo) -->
                        <div class="form-section" id="nombreSection">
                            <div class="section-title required">Nombre completo</div>
                            <input type="text" class="form-control" id="nombre_completo" name="nombre_completo" placeholder="Ingresa tu nombre completo" required>
                        </div>
                        
                        <!-- SECCIÓN EMAIL (se oculta si es anónimo, siempre opcional) -->
                        <div class="form-section" id="emailSection">
                            <!-- <div class="section-title">Correo electrónico (opcional)</div>-->
                            <!-- <input type="email" class="form-control" id="email" name="email" placeholder="ejemplo@correo.com">-->
                        </div>
                    </form>
                    
                    <!-- BOTONES -->
                    <div class="buttons-section">
                        <button type="submit" form="formDonacion" class="btn donate-btn" id="submitBtn">
                            <span class="btn-text">
                                <i class="bi bi-heart-fill"></i> Continuar
                            </span>
                            <span class="processing-text">
                                <i class="bi bi-hourglass-split"></i> Procesando...
                            </span>
                        </button>
                        
                        <div class="back-link">
                            <a href="index.php" id="backLink">← Volver a la máquina de donaciones</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Precargar la imagen de fondo para evitar parpadeos
            const bgImage = new Image();
            bgImage.src = 'fondo-navidad.jpeg';
            
            // Forzar modo oscuro en la página si está en modo claro
            if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
                document.documentElement.style.backgroundColor = '#000000';
                document.body.style.backgroundColor = '#000000';
            }

            // Crear elemento de audio para el sonido de click
            const clickSound = new Audio('sounds/click.mp3');
            
            const anonimoCheckbox = document.getElementById('anonimo');
            const nombreSection = document.getElementById('nombreSection');
            const emailSection = document.getElementById('emailSection');
            const nombreInput = document.getElementById('nombre_completo');
            const emailInput = document.getElementById('email');
            const form = document.getElementById('formDonacion');
            const submitBtn = document.getElementById('submitBtn');
            const backLink = document.getElementById('backLink');
            const formCheckboxes = document.querySelectorAll('.form-check-input');
            let isProcessing = false;

            // Función para reproducir sonido de click
            function playClickSound() {
                clickSound.currentTime = 0;
                clickSound.play();
            }

            // Manejar el envío del formulario
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Si ya está procesando, no hacer nada
                if (isProcessing) return;
                
                // Validar el formulario
                if (!form.checkValidity()) {
                    // Mostrar mensajes de validación
                    form.classList.add('was-validated');
                    return;
                }
                
                // Reproducir sonido de click
                playClickSound();
                
                // Deshabilitar botón y mostrar "Procesando..."
                isProcessing = true;
                submitBtn.disabled = true;
                submitBtn.classList.add('processing');
                
                // Esperar a que termine el sonido (500ms)
                setTimeout(() => {
                    // Enviar el formulario
                    form.submit();
                }, 500);
            });

            // Añadir sonido al enlace de Volver
            if (backLink) {
                backLink.addEventListener('click', function(e) {
                    e.preventDefault();
                    playClickSound();
                    
                    // Permitir que se escuche el sonido antes de redirigir
                    setTimeout(() => {
                        window.location.href = this.getAttribute('href');
                    }, 300);
                });
            }

            // Añadir sonido a los checkboxes
            formCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    playClickSound();
                });
            });

            // Manejar checkbox de anónimo
            anonimoCheckbox.addEventListener('change', function() {
                if (this.checked) {
                    // OCULTAR campos completamente
                    nombreSection.style.display = 'none';
                    emailSection.style.display = 'none';
                    
                    // Valores por defecto para anónimo
                    nombreInput.value = 'Anónimo';
                    emailInput.value = 'no-email@anonimo.com';
                    nombreInput.required = false;
                } else {
                    // MOSTRAR campos
                    nombreSection.style.display = 'block';
                    emailSection.style.display = 'block';
                    
                    // Limpiar valores
                    nombreInput.value = '';
                    emailInput.value = '';
                    nombreInput.required = true;
                }
            });

            // Crear campo hidden para indicar si es anónimo
            const originalSubmit = form.submit;
            form.submit = function() {
                const esAnonimoInput = document.createElement('input');
                esAnonimoInput.type = 'hidden';
                esAnonimoInput.name = 'es_anonimo';
                esAnonimoInput.value = anonimoCheckbox.checked ? '1' : '0';
                form.appendChild(esAnonimoInput);
                
                // Llamar al submit original
                originalSubmit.call(form);
            };

            // Prevenir zoom en iOS
            document.addEventListener('touchstart', function(event) {
                if (event.touches.length > 1) {
                    event.preventDefault();
                }
            }, { passive: false });
        });
    </script>
</body>
</html>