{% extends 'h_tmp_usr/z_tmp.html' %}

{% block css %}

<!-- {# Librería de aos.js [animaciones] #} -->
<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

<!-- {# bootstrap datatables #} -->
<link rel="stylesheet" href="https://cdn.datatables.net/2.2.2/css/dataTables.bootstrap5.css">

<!-- {# cdn download xlsx #} -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

{% endblock css %}



{% block body %}
<h1>Solicitudes de Contacto</h1>

{% if is_admin %}
{% include 'z_comps/download_xlsx.html' %}
{% endif %}




<table id="dbContact" class="table table-striped" style="width:100%" data-aos="fade-right" data-aos-delay="0" data-aos-duration="800" data-aos-easing="ease-in-out">
    <thead>
        <tr>
            <th>Fecha</th>
            <th>Nombre Completo</th>
            <th>Estado</th>
            <th>Tamaño Empresa</th>
            <th>Rol Contacto</th>
            <th>Tipo Industria</th>
            <th>Estatus</th>
        </tr>
    </thead>
    <tbody>
        {% for item in data_contact %}
            <tr data-id="{{item[0]}}">
                <td>
                    <button data-id="{{item[0]}}" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalContactData">
                        {{item[1]}}
                    </button>
                </td>
                <td>
                    {{item[2]}} {{item[3]}}
                </td>
                <td>{{item[4]}}</td>
                <td>{{item[5]}}</td>
                <td>{{item[6]}}</td>
                <td>{{item[7]}}</td>
                <td>
                    <select class="form-select" data-id="{{ item[0] }}">
                        <option value="Null" {% if item[8] is none %}selected{% endif %}></option>
                        <option value="Opción 1" {% if item[8] == 'Opción 1' %}selected{% endif %}>Opción 1</option>
                        <option value="Opción 2" {% if item[8] == 'Opción 2' %}selected{% endif %}>Opción 2</option>
                        <option value="Opción 3" {% if item[8] == 'Opción 3' %}selected{% endif %}>Opción 3</option>
                        <option value="Opción 4" {% if item[8] == 'Opción 4' %}selected{% endif %}>Opción 4</option>
                        <option value="Opción 5" {% if item[8] == 'Opción 5' %}selected{% endif %}>Opción 5</option>
                        <option value="Opción 6" {% if item[8] == 'Opción 6' %}selected{% endif %}>Opción 6</option>
                        <option value="Opción 7" {% if item[8] == 'Opción 7' %}selected{% endif %}>Opción 7</option>
                        <option value="Archivado" >Archivar</option>
                    </select>
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>

<!-- Modal -->
<div class="modal fade" id="modalContactData" tabindex="-1" aria-labelledby="modalContactDataLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalContactDataLabel"><i class="bi bi-database-fill-check"></i> Información del Registro:</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="modalBody">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>


{% endblock body %}

{% block js %}



<!-- {# if flash #} -->
{% include 'z_comps/if_flash.html' %}

<!-- {# aos script #} -->
{% include 'z_comps/aos_script.html' %}

<script>
    function getFechaHoraFormato() {
    const now = new Date();
    const pad = (n) => n.toString().padStart(2, '0');
    const dia = pad(now.getDate());
    const mes = pad(now.getMonth() + 1); // Enero es 0
    const anio = now.getFullYear();
    const hora = pad(now.getHours());
    const minuto = pad(now.getMinutes());
    return `${dia}.${mes}.${anio}_${hora}_${minuto}`;
}
</script>


<script>
async function get_contact_data(btn) {
    try {
        let id = btn.dataset.id;
        let modalBody = document.querySelector("#modalBody");
        
        let response = await fetch('/user/get-contact-data', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id }),
            credentials: 'include'
        });

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        let { data } = await response.json();

        let contact = {
            fecha: data[0],
            fecha_hora: data[1],
            nombre: data[2],
            apellido: data[3],
            correo: data[4],
            estado: data[5],
            telefono: data[6],
            tamano_empresa: data[7],
            rol_contacto: data[8],
            tipo_industria: data[9],
            comentarios: data[10],
            estatus: data[11] ?? "Sin Estatus"
        };

        modalBody.innerHTML = `
            <p><b><i class="bi bi-calendar4-week"></i></b> ${contact.fecha} - ${contact.fecha_hora}</p>
            <p><b><i class="bi bi-person-fill"></i></b> ${contact.nombre} ${contact.apellido}</p>
            <p><b><i class="bi bi-envelope-at-fill"></i></b> ${contact.correo}</p>
            <p><b><i class="bi bi-pin-map-fill"></i></b> ${contact.estado}</p>
            <p><b><i class="bi bi-telephone-fill"></i></b> ${contact.telefono}</p>
            <p><b><i class="bi bi-people-fill"></i></b> ${contact.tamano_empresa}</p>
            <p><b><i class="bi bi-person-vcard"></i></b> ${contact.rol_contacto}</p>
            <p><b><i class="bi bi-shop"></i></b> ${contact.tipo_industria}</p>
            <p><b><i class="bi bi-wrench-adjustable"></i></b> ${contact.estatus}</p>
            <p><b><i class="bi bi-file-earmark-font-fill"></i></b> ${contact.comentarios}</p>
        `;

    } catch (error) {
        console.error('Error al obtener datos:', error);
    }
}

document.getElementById('dbContact').addEventListener('click', (event) => {
    const button = event.target.closest('button.btn-primary[data-id]');
    if (button) {
        get_contact_data(button);
    }
});


</script>

<script>


    function send_data(target) {
        let id = target.dataset.id;
        let valor = target.value != "Null" ? target.value : null;
        let data = { id, value: valor };


        if (valor === 'Archivado') {
            let table = $('#dbContact').DataTable();
            let row = table.row(`tr[data-id="${id}"]`);
            row.remove().draw();
        }

        fetch('/user/manage-record', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
            credentials: 'include'
        });
    }

    document.getElementById('dbContact').addEventListener('change', (event) => {
        if (event.target.matches('select.form-select[data-id]')) {
            send_data(event.target);
        }
    });

</script>

<script>

</script>


<!-- js datatables -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<!-- jQuery (necesario para DataTables) -->
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<!-- Popper.js (necesario para los dropdowns de Bootstrap) -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<!-- Bootstrap JS Bundle con Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables JS -->
<script src="https://cdn.datatables.net/2.2.2/js/dataTables.js"></script>
<!-- DataTables Bootstrap 5 JS -->
<script src="https://cdn.datatables.net/2.2.2/js/dataTables.bootstrap5.js"></script>


<script>
    new DataTable('#dbContact', {
        initComplete: function() {
            // Agrega campos de filtro para cada columna
            this.api().columns().every(function() {
                let column = this;
                let header = $(column.header());
                let title = header.text().trim();

                // Excluir la columna "Estatus" del filtro
                if (title !== 'Estatus') {
                    // Crea input de filtro
                    header.append('<div class="filter"><input type="text" class="form-control" placeholder="'+title+'" /></div>');
                    
                    // Aplica el filtro al escribir
                    $('input', header)
                        .on('keyup change', function() {
                            if (column.search() !== this.value) {
                                column.search(this.value).draw();
                            }
                        });
                }
            });
        }
    });
</script>

<!-- <script>
    new DataTable('#dbContact', {
    initComplete: function() {
        // Agrega campos de filtro para cada columna
        this.api().columns().every(function() {
            let column = this;
            let header = $(column.header());
            let title = header.text().trim();

            // Crea input de filtro
            // <i class="bi bi-filter"></i>
            header.append('<div class="filter"><input type="text" class="form-control" placeholder="'+title+'" /></div>');        
            // Aplica el filtro al escribir
            $('input', header)
                .on('keyup change', function() {
                    if (column.search() !== this.value) {
                        column.search(this.value).draw();
                    }
                });
        });
    }
    });
</script> -->

<script>
    let exp = "{{exp}}";
</script>

<script src="{{ url_for('static', filename='z_comps/save_exp_timestamp.js') }}"></script>

{% endblock js %}