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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $item_id = $_POST['item_id'];
    $nombre_completo = isset($_POST['nombre_completo']) ? trim($_POST['nombre_completo']) : 'Anónimo';
    $email = isset($_POST['email']) ? trim($_POST['email']) : 'no-email@anonimo.com';
    $monto_fijo = floatval($_POST['monto_fijo']);
    $es_anonimo = isset($_POST['es_anonimo']) && $_POST['es_anonimo'] == '1';
    
    // Si es anónimo, forzar valores anónimos
    if ($es_anonimo) {
        $nombre_completo = 'Anónimo';
        $email = 'no-email@anonimo.com';
    }
    
    // Obtener información del item CON IMAGEN
    $sql = "SELECT * FROM items WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$item_id]);
    $item = $stmt->fetch(PDO::FETCH_ASSOC);
    
    try {
        // Registrar donante
        $sql = "INSERT INTO donantes (nombre_completo, email) VALUES (?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$nombre_completo, $email]);
        $donante_id = $pdo->lastInsertId();
        
        // Registrar donación
        $sql = "INSERT INTO donaciones (donante_id, item_id, monto, motivo, codigo_transaccion) 
                VALUES (?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $codigo_transaccion = uniqid('DON_');
        $motivo = 'S/ ' . $monto_fijo;
        $stmt->execute([$donante_id, $item_id, $monto_fijo, $motivo, $codigo_transaccion]);
        $donacion_id = $pdo->lastInsertId();
        
    } catch(PDOException $e) {
        die("ERROR: No se pudo procesar la donación. " . $e->getMessage());
    }
} else {
    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">
    <title>Pago con QR - 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 */
            --adra-deep-red: #992A31;      /* CHRISTMAS DEEP RED */
            --adra-cream: #F8F0E4;         /* CREAM */
            
            /* Colores Secundarios ADRA */
            --adra-gold: #C1A01E;          /* GOLD 20 */
            --adra-pale-blue: #E6F5FA;     /* PALE BLUE */
            --adra-white: #FFFFFF;         /* WHITE */
            
            /* Colores de Texto */
            --text-dark: #333333;
            --text-medium: #666666;
            --text-light: #999999;
        }

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

        html, body {
            height: 100%;
            overflow: hidden;
        }

        /* ========================================== */
        /* BODY - FONDO CON IMAGEN NAVIDEÑA */
        /* ========================================== */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: url('fondo-navidad.jpeg') no-repeat center center fixed;
            background-size: cover;
            color: var(--text-dark);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 8px;
        }

        /* ========================================== */
        /* CONTENEDOR PRINCIPAL */
        /* ========================================== */
        .payment-container {
            width: 100%;
            max-width: 400px;
            height: 100%;
            max-height: 98vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* ========================================== */
        /* TARJETA DE PAGO */
        /* ========================================== */
        .payment-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25);
            width: 100%;
            border: 2px solid var(--adra-deep-red);
            display: flex;
            flex-direction: column;
            height: auto;
            max-height: 98vh;
            overflow: hidden;
            backdrop-filter: blur(3px);
        }

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

        /* ========================================== */
        /* ENCABEZADO - Gradiente ADRA */
        /* ========================================== */
        .payment-header {
            background: linear-gradient(135deg, 
                var(--adra-deep-red) 0%, 
                var(--adra-red) 50%, 
                var(--adra-gold) 100%
            );
            color: var(--adra-white);
            padding: 8px 12px;
            text-align: center;
            border-bottom: 2px solid var(--adra-deep-red);
            flex-shrink: 0;
        }

        .payment-header h1 {
            font-size: 0.95rem;
            font-weight: 800;
            margin-bottom: 0;
        }

        .payment-header p {
            font-size: 0.7rem;
            opacity: 0.9;
            margin-bottom: 0;
        }

        /* ========================================== */
        /* CUERPO DEL FORMULARIO DE PAGO */
        /* ========================================== */
        .payment-body {
            padding: 10px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            flex: 1;
        }

        .content-wrapper {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;
        }

        /* ========================================== */
        /* INFORMACIÓN DEL ITEM */
        /* ========================================== */
        .beneficiary-info {
            text-align: center;
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 1px solid var(--adra-cream);
            flex-shrink: 0;
        }

        /* ===== IMAGEN PROTAGONISTA GIGANTE ===== */
        .beneficiary-image {
            width: 150px;        /* GIGANTE - Elemento protagonista */
            height: 150px;
            border-radius: 50%;
            overflow: hidden;
            border: 3px solid var(--adra-red);
            margin: 0 auto 6px auto;
            background: linear-gradient(135deg, 
                var(--adra-cream), 
                var(--adra-pale-blue)
            );
            box-shadow: 0 6px 20px 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: 4rem;
            color: var(--adra-red);
        }

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

        /* PRECIO DIMINUTO - No compite con imagen */
        .beneficiary-price {
            font-size: 0.95rem;      /* Discreto */
            font-weight: 700;
            color: var(--adra-red);
            background: var(--adra-cream);
            padding: 3px 10px;
            border-radius: 12px;
            display: inline-block;
            margin-top: 3px;
            border: 1px solid var(--adra-gold);
        }

        /* ========================================== */
        /* SECCIÓN DE MONTO */
        /* ========================================== */
        .amount-section {
            text-align: center;
            margin-bottom: 8px;
            padding: 6px;
            background: var(--adra-pale-blue);
            border-radius: 6px;
            border-left: 3px solid var(--adra-red);
            flex-shrink: 0;
        }

        .amount-label {
            font-size: 0.7rem;
            color: var(--text-medium);
            margin-bottom: 2px;
        }

        .amount-value {
            font-size: 1.1rem;
            font-weight: 800;
            color: var(--adra-red);
        }

        /* ========================================== */
        /* CÓDIGO QR - Compacto */
        /* ========================================== */
        .qr-section {
            text-align: center;
            margin-bottom: 8px;
            flex-shrink: 0;
        }

        .qr-code {
            background: var(--adra-white);
            padding: 0.5rem;
            border-radius: 6px;
            border: 1px solid var(--adra-gold);
            display: inline-block;
            margin-bottom: 0.5rem;
        }

        .qr-code img {
            width: 100px;      /* Compacto */
            height: 100px;
        }

        .qr-instructions {
            font-size: 0.65rem;
            color: var(--text-medium);
            margin-bottom: 0;
        }

        /* ========================================== */
        /* INSTRUCCIONES DE PAGO */
        /* ========================================== */
        .instructions {
            background: var(--adra-cream);
            border: 1px solid var(--adra-gold);
            border-radius: 6px;
            padding: 6px;
            margin-bottom: 8px;
            font-size: 0.65rem;
            flex-shrink: 0;
        }

        .instructions h4 {
            color: var(--adra-red);
            font-weight: 700;
            margin-bottom: 3px;
            font-size: 0.7rem;
        }

        .instructions ol {
            padding-left: 1rem;
            margin-bottom: 0;
        }

        .instructions li {
            margin-bottom: 2px;
            line-height: 1.2;
        }

        /* ========================================== */
        /* BOTÓN DE CONFIRMACIÓN */
        /* ========================================== */
        .confirm-btn {
            background: linear-gradient(135deg, 
                var(--adra-red) 0%, 
                var(--adra-deep-red) 100%
            );
            color: var(--adra-white);
            border: none;
            border-radius: 6px;
            padding: 10px;
            font-size: 0.8rem;
            font-weight: 700;
            width: 100%;
            transition: all 0.3s ease;
            box-shadow: 0 2px 6px rgba(213, 0, 50, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            gap: 4px;
            cursor: pointer;
            position: relative;
        }

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

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

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

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

        .confirm-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;
        }

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

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

        /* ========================================== */
        /* ENLACE PARA VOLVER */
        /* ========================================== */
        .back-link {
            text-align: center;
            margin-top: 6px;
            flex-shrink: 0;
        }

        .back-link a {
            color: var(--adra-red);
            text-decoration: none;
            font-weight: 600;
            transition: color 0.3s ease;
            font-size: 0.65rem;
        }

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

        /* ========================================== */
        /* RESPONSIVE - TABLETS */
        /* ========================================== */
        @media (min-width: 768px) {
            body {
                padding: 15px;
            }

            .payment-card {
                max-width: 450px;
                border-radius: 12px;
            }

            .beneficiary-image {
                width: 180px;
                height: 180px;
            }

            .beneficiary-image i {
                font-size: 5rem;
            }
        }

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

            .beneficiary-image i {
                font-size: 3.5rem;
            }
        }

        /* ========================================== */
        /* RESPONSIVE - PANTALLAS BAJAS */
        /* ========================================== */
        @media (max-height: 650px) {
            .beneficiary-image {
                width: 120px;
                height: 120px;
                margin-bottom: 4px;
            }

            .beneficiary-image i {
                font-size: 3rem;
            }

            .qr-code img {
                width: 90px;
                height: 90px;
            }

            .payment-body {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="payment-container">
        <div class="payment-card">
            <!-- ENCABEZADO -->
            <div class="payment-header">
                <h1>PAGO CON CÓDIGO QR</h1>
                <p>Escanea el código para completar tu donación</p>
            </div>
            
            <!-- CUERPO -->
            <div class="payment-body">
                <div class="content-wrapper">
                    <!-- INFORMACIÓN DEL ITEM CON IMAGEN GIGANTE -->
                    <div class="beneficiary-info">
                        <!-- IMAGEN PROTAGONISTA GIGANTE -->
                        <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 DIMINUTO -->
                            <div class="beneficiary-price">S/ <?php echo number_format($monto_fijo, 2); ?></div>
                        </div>
                    </div>


                    <!-- CÓDIGO QR -->
                    <div class="qr-section">
                        <div class="qr-code">
                            <img src="img/qr-oficial.jpg" alt="Código QR oficial para pago">
                        </div>
                        <p class="qr-instructions">Escanea con tu app de billetera móvil</p>
                    </div>

                    <!-- BOTÓN DE CONFIRMACIÓN -->
                    <form action="confirmacion_pago.php" method="POST" id="confirmationForm">
                        <input type="hidden" name="donacion_id" value="<?php echo $donacion_id; ?>">
                        <input type="hidden" name="codigo_transaccion" value="<?php echo $codigo_transaccion; ?>">
                        <button type="submit" class="btn confirm-btn" id="confirmBtn">
                            <span class="btn-text">
                                <i class="bi bi-check-circle-fill"></i> Ya realicé la donación
                            </span>
                            <span class="processing-text">
                                <i class="bi bi-hourglass-split"></i> Procesando...
                            </span>
                        </button>
                    </form>

                    <!-- ENLACE PARA VOLVER -->
                    <div class="back-link">
                        <a href="index.php" id="backLink">← Volver a la máquina de donaciones</a>
                    </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() {
            // Crear elemento de audio para el sonido de click
            const clickSound = new Audio('sounds/click.mp3');
            
            const confirmForm = document.getElementById('confirmationForm');
            const confirmBtn = document.getElementById('confirmBtn');
            const backLink = document.getElementById('backLink');
            let isProcessing = false;

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

            // Manejar el envío del formulario de confirmación
            confirmForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Si ya está procesando, no hacer nada
                if (isProcessing) return;
                
                // Reproducir sonido de click
                playClickSound();
                
                // Deshabilitar botón y mostrar "Procesando..."
                isProcessing = true;
                confirmBtn.disabled = true;
                confirmBtn.classList.add('processing');
                
                // Esperar a que termine el sonido (500ms)
                setTimeout(() => {
                    // Enviar el formulario
                    confirmForm.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);
                });
            }

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