<?php
// ==========================================
// 1. CONFIGURACIÓN Y SEGURIDAD
// ==========================================
// Forzamos la codificación UTF-8 para evitar símbolos raros
header('Content-Type: text/html; charset=utf-8');

session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado. Por favor inicie sesión.");
}

// 2. VARIABLES DE CONFIGURACIÓN
$prefijo = isset($IDU) ? $IDU : ($_SESSION['IDU'] ?? '0'); 
$tb_prov = $prefijo . "-Proveedores"; 
$nombre_bd = "MS_Datos";
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    body { background-color: #f4f7f6; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    
    /* Métricas */
    .card-metric {
        border: none; border-radius: 12px; transition: transform 0.2s;
        background: white; box-shadow: 0 4px 6px rgba(0,0,0,0.05);
    }
    .card-metric:hover { transform: translateY(-3px); }
     
    /* Tabla */
    .table-prov thead th {
        font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px;
        color: #6c757d; border-bottom: 2px solid #e9ecef; background: #f8f9fa;
    }
    .avatar-prov {
        width: 45px; height: 45px; 
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white; border-radius: 10px; 
        display: flex; align-items: center; justify-content: center;
        font-weight: bold; font-size: 1.2rem;
    }
    
    /* Badges */
    .badge-credito { font-size: 0.8rem; padding: 5px 10px; border-radius: 20px; }
    .credito-contado { background: #e0f2fe; color: #0284c7; }
    .credito-corto { background: #fef3c7; color: #d97706; }
    .credito-largo { background: #fee2e2; color: #dc2626; }

    /* Modal y Formularios */
    .modal-fullscreen .modal-dialog { width: 95%; max-width: 95%; margin: 10px auto; }
    .input-hero { font-size: 1.3rem; font-weight: 700; height: 50px; }
    .fiscal-header {
        background: #f8fafc; border-bottom: 1px solid #e2e8f0;
        padding: 10px 15px; margin-bottom: 15px; border-radius: 5px;
        font-weight: bold; color: #475569; text-transform: uppercase; font-size: 0.85rem;
    }
</style>

<div class="container-fluid p-3">
    
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card card-metric p-3 border-left-primary">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted text-uppercase font-weight-bold">Total Proveedores</small>
                        <h3 class="mb-0 text-dark font-weight-bold" id="kpi_total">0</h3>
                    </div>
                    <div class="icon-shape bg-light text-primary rounded-circle p-3"><i class="fas fa-truck-loading fa-2x"></i></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card card-metric p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted text-uppercase font-weight-bold">Crédito Promedio</small>
                        <h3 class="mb-0 text-dark font-weight-bold" id="kpi_credito">0 Días</h3>
                    </div>
                    <div class="icon-shape bg-light text-warning rounded-circle p-3"><i class="fas fa-clock fa-2x"></i></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card card-metric p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted text-uppercase font-weight-bold">Activos</small>
                        <h3 class="mb-0 text-success font-weight-bold" id="kpi_activos">0</h3>
                    </div>
                    <div class="icon-shape bg-light text-success rounded-circle p-3"><i class="fas fa-check-circle fa-2x"></i></div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0 rounded-3">
        <div class="card-header bg-white py-3">
            <div class="row align-items-center">
                <div class="col-md-5">
                    <h5 class="mb-0 font-weight-bold text-dark"><i class="fas fa-users-cog mr-2"></i>Directorio de Proveedores</h5>
                </div>
                <div class="col-md-7 text-right">
                    <div class="d-flex justify-content-end gap-2">
                        <button class="btn btn-success text-white shadow-sm mr-2" onclick="exportarExcel()">
                            <i class="fas fa-file-excel mr-1"></i> Excel
                        </button>
                        <div class="input-group" style="width: 300px;">
                            <span class="input-group-text bg-white border-right-0"><i class="fas fa-search text-muted"></i></span>
                            <input type="text" id="buscador" class="form-control border-left-0 pl-0" placeholder="Buscar Razón Social, RFC o Contacto...">
                            <button class="btn btn-dark ml-2 rounded" onclick="abrirModal()">
                                <i class="fas fa-plus mr-1"></i> Nuevo
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle table-prov mb-0">
                <thead>
                    <tr>
                        <th width="60" class="pl-4">#</th>
                        <th>Razón Social / RFC</th>
                        <th>Contacto Principal</th>
                        <th>Medios de Contacto</th>
                        <th class="text-center">Días Crédito</th>
                        <th class="text-center">Estado</th>
                        <th class="text-right pr-4">Acciones</th>
                    </tr>
                </thead>
                <tbody id="tabla_body"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade modal-fullscreen" id="modalEdicion" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-dark text-white py-3">
                <h5 class="modal-title font-weight-bold"><i class="fas fa-handshake mr-2"></i>Gestión de Proveedor</h5>
                <button type="button" class="btn btn-outline-light btn-sm ml-auto mr-2" data-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-success btn-sm px-4 font-weight-bold shadow" onclick="guardarProveedor()">
                    <i class="fas fa-save mr-1"></i> GUARDAR
                </button>
            </div>
            
            <div class="modal-body bg-light p-4">
                <form id="formProv">
                    <input type="hidden" id="IDP">
                    
                    <div class="row">
                        <div class="col-lg-5 mb-4">
                            <div class="card border-0 shadow-sm h-100">
                                <div class="card-header bg-white font-weight-bold text-uppercase text-primary">Información General</div>
                                <div class="card-body">
                                    <div class="form-group mb-4">
                                        <label class="form-label font-weight-bold text-dark">Razón Social / Nombre *</label>
                                        <input type="text" class="form-control input-hero border-primary" id="razon_social" placeholder="Ej: Distribuidora Nacional S.A. de C.V.">
                                    </div>
                                    
                                    <div class="row mb-3">
                                        <div class="col-6">
                                            <label class="form-label text-muted">Nombre Contacto</label>
                                            <div class="input-group"><span class="input-group-text bg-light"><i class="fas fa-user"></i></span><input type="text" class="form-control" id="nombre_contacto"></div>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label text-muted">Teléfono</label>
                                            <div class="input-group"><span class="input-group-text bg-light"><i class="fas fa-phone"></i></span><input type="text" class="form-control" id="telefono"></div>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group mb-3">
                                        <label class="form-label text-muted">Correo Electrónico</label>
                                        <div class="input-group"><span class="input-group-text bg-light"><i class="fas fa-envelope"></i></span><input type="email" class="form-control" id="email"></div>
                                    </div>

                                    <div class="row mt-4">
                                        <div class="col-6 form-group">
                                            <label class="form-label text-muted">Días de Crédito</label>
                                            <div class="input-group"><span class="input-group-text"><i class="fas fa-calendar-day"></i></span><input type="number" class="form-control" id="dias_credito" value="0"></div>
                                        </div>
                                        <div class="col-6 form-group">
                                            <label class="form-label text-muted">Estado</label>
                                            <select class="form-control" id="activo">
                                                <option value="1">?? Activo</option>
                                                <option value="0">?? Inactivo</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group mt-3">
                                        <label class="form-label text-muted small">Notas Internas (JSON)</label>
                                        <textarea class="form-control json-editor bg-light" id="Datos" rows="2" placeholder='{"banco": "BBVA"}'></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-7 mb-4">
                            <div class="card border-0 shadow-sm h-100">
                                <div class="card-header bg-white font-weight-bold text-uppercase text-info">
                                    <i class="fas fa-file-invoice-dollar mr-2"></i>Datos Fiscales (Facturación)
                                </div>
                                <div class="card-body">
                                    <div class="form-group mb-3">
                                        <label class="form-label font-weight-bold">RFC *</label>
                                        <input type="text" class="form-control font-weight-bold text-uppercase border-info" id="rfc" placeholder="AAA010101AAA">
                                    </div>

                                    <div class="fiscal-header"><i class="fas fa-map-marker-alt mr-2"></i>Domicilio Fiscal</div>
                                    
                                    <div class="row mb-2">
                                        <div class="col-md-8 mb-2">
                                            <label class="small text-muted">Calle</label>
                                            <input type="text" class="form-control fis-field" id="fis_calle">
                                        </div>
                                        <div class="col-md-2 mb-2">
                                            <label class="small text-muted">No. Ext</label>
                                            <input type="text" class="form-control fis-field" id="fis_num_ext">
                                        </div>
                                        <div class="col-md-2 mb-2">
                                            <label class="small text-muted">No. Int</label>
                                            <input type="text" class="form-control fis-field" id="fis_num_int">
                                        </div>
                                    </div>

                                    <div class="row mb-2">
                                        <div class="col-md-6 mb-2">
                                            <label class="small text-muted">Colonia</label>
                                            <input type="text" class="form-control fis-field" id="fis_colonia">
                                        </div>
                                        <div class="col-md-6 mb-2">
                                            <label class="small text-muted">Código Postal (CP)</label>
                                            <input type="text" class="form-control fis-field" id="fis_cp">
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-4 mb-2">
                                            <label class="small text-muted">Municipio</label>
                                            <input type="text" class="form-control fis-field" id="fis_municipio">
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <label class="small text-muted">Estado</label>
                                            <input type="text" class="form-control fis-field" id="fis_estado">
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <label class="small text-muted">País</label>
                                            <input type="text" class="form-control fis-field" id="fis_pais" value="México">
                                        </div>
                                    </div>

                                    <div class="fiscal-header"><i class="fas fa-list-alt mr-2"></i>Configuración CFDI</div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label class="small text-muted">Régimen Fiscal</label>
                                            <select class="form-control fis-field" id="fis_regimen">
                                                <option value="">Seleccione...</option>
                                                <option value="601">601 - General de Ley Personas Morales</option>
                                                <option value="612">612 - Personas Físicas con Actividades Empresariales</option>
                                                <option value="626">626 - Régimen Simplificado de Confianza</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="small text-muted">Uso de CFDI Habitual</label>
                                            <select class="form-control fis-field" id="fis_uso_cfdi">
                                                <option value="G03">G03 - Gastos en general</option>
                                                <option value="G01">G01 - Adquisición de mercancías</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Configuraciones pasadas desde PHP
    const DB_NAME = "<?php echo $nombre_bd; ?>";
    const TABLE_RAW = "<?php echo $tb_prov; ?>"; // ej: 101-Proveedores

    // Función Helper para escapar comillas simples y evitar romper SQL
    const escapeSQL = (str) => {
        if (!str) return '';
        return String(str).replace(/'/g, "\\'"); 
    };

    document.addEventListener('DOMContentLoaded', () => {
        listarProveedores();
        
        // Filtro rápido en cliente
        document.getElementById('buscador').addEventListener('keyup', function(e) {
            const term = e.target.value.toLowerCase();
            document.querySelectorAll('#tabla_body tr').forEach(row => {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(term) ? '' : 'none';
            });
        });
    });

    // --- 1. LISTAR (SELECT) ---
    function listarProveedores() {
        const tbody = document.getElementById('tabla_body');
        tbody.innerHTML = '<tr><td colspan="7" class="text-center p-4"><i class="fas fa-circle-notch fa-spin text-muted"></i> Cargando...</td></tr>';

        // IMPORTANTE: Usamos comillas invertidas ` ` alrededor del nombre de la tabla porque tiene un guion
        const sql = `SELECT * FROM ${DB_NAME}.\`${TABLE_RAW}\` ORDER BY IDPr DESC`;

        fetch('../librerias/AJAX/Select.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `sql=${encodeURIComponent(sql)}&db=${DB_NAME}`
        })
        .then(r => r.json())
        .then(res => {
            tbody.innerHTML = '';
            let total = 0, activos = 0, sumaCredito = 0;

            if(res.status === 'success' && res.data && res.data.length > 0) {
                res.data.forEach(row => {
                    total++;
                    if(row.activo == 1) activos++;
                    sumaCredito += parseInt(row.dias_credito || 0);

                    const inicial = row.razon_social ? row.razon_social.substring(0,2).toUpperCase() : 'PV';
                    const dias = parseInt(row.dias_credito || 0);
                    
                    let badgeClass = 'credito-contado'; let badgeText = 'Contado';
                    if(dias > 0 && dias <= 30) { badgeClass = 'credito-corto'; badgeText = dias + ' Días'; }
                    if(dias > 30) { badgeClass = 'credito-largo'; badgeText = dias + ' Días'; }

                    const estadoIcon = row.activo == 1 
                        ? `<i class="fas fa-check-circle text-success" title="Activo"></i>` 
                        : `<i class="fas fa-times-circle text-danger" title="Inactivo"></i>`;

                    // Intentar parsear dirección para mostrarla en tooltip
                    let dirFiscal = "Sin dirección fiscal";
                    try {
                        if(row.Datos_Fiscales && row.Datos_Fiscales !== "null") {
                            const fis = JSON.parse(row.Datos_Fiscales);
                            if(fis && fis.calle) dirFiscal = `${fis.calle} ${fis.num_ext}, ${fis.colonia}, CP ${fis.cp}`;
                        }
                    } catch(e) {}

                    // Como row es un objeto, lo stringify para pasarlo al editar
                    // Usamos replace para escapar comillas simples dentro del JSON stringificado
                    const rowString = JSON.stringify(row).replace(/'/g, "&#39;");

                    tbody.innerHTML += `
                        <tr>
                            <td class="pl-4"><div class="avatar-prov shadow-sm">${inicial}</div></td>
                            <td>
                                <div class="font-weight-bold text-dark">${row.razon_social}</div>
                                <small class="text-muted font-monospace"><i class="fas fa-id-card mr-1"></i>${row.rfc || 'Sin RFC'}</small>
                            </td>
                            <td><div class="text-dark"><i class="fas fa-user-tie text-muted mr-1"></i>${row.nombre_contacto || '--'}</div></td>
                            <td>
                                ${row.telefono ? `<div class="small"><i class="fas fa-phone text-muted mr-1"></i>${row.telefono}</div>` : ''}
                                ${row.email ? `<div class="small"><i class="fas fa-envelope text-muted mr-1"></i>${row.email}</div>` : ''}
                                <div class="small text-info mt-1" title="${dirFiscal}"><i class="fas fa-map-marker-alt mr-1"></i>${dirFiscal.substring(0,20)}...</div>
                            </td>
                            <td class="text-center"><span class="badge-credito ${badgeClass}">${badgeText}</span></td>
                            <td class="text-center h5 mb-0">${estadoIcon}</td>
                            <td class="text-right pr-4">
                                <button class="btn btn-sm btn-light border" onclick='editarProveedor(${rowString})'><i class="fas fa-edit text-primary"></i></button>
                                <button class="btn btn-sm btn-light border" onclick="eliminarProveedor(${row.IDPr}, '${escapeSQL(row.razon_social)}')"><i class="fas fa-trash text-danger"></i></button>
                            </td>
                        </tr>
                    `;
                });
                
                document.getElementById('kpi_total').innerText = total;
                document.getElementById('kpi_activos').innerText = activos;
                document.getElementById('kpi_credito').innerText = total > 0 ? Math.round(sumaCredito/total) + ' Días' : '0';
            } else {
                tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted py-5">No se encontraron proveedores.</td></tr>';
                document.getElementById('kpi_total').innerText = '0';
            }
        })
        .catch(err => console.error("Error listar:", err));
    }

    // --- 2. GUARDAR (INSERT / UPDATE) ---
    function guardarProveedor() {
        const id = document.getElementById('IDP').value;
        const razon = document.getElementById('razon_social').value.trim();
        
        if(!razon) { 
            Swal.fire('Atención', 'La Razón Social es obligatoria', 'warning'); 
            return; 
        }

        // 1. Recolectar Datos Fiscales en Objeto
        const datosFiscalesObj = {
            calle: document.getElementById('fis_calle').value,
            num_ext: document.getElementById('fis_num_ext').value,
            num_int: document.getElementById('fis_num_int').value,
            colonia: document.getElementById('fis_colonia').value,
            cp: document.getElementById('fis_cp').value,
            municipio: document.getElementById('fis_municipio').value,
            estado: document.getElementById('fis_estado').value,
            pais: document.getElementById('fis_pais').value,
            regimen: document.getElementById('fis_regimen').value,
            uso_cfdi: document.getElementById('fis_uso_cfdi').value
        };
        const datosFiscalesJSON = JSON.stringify(datosFiscalesObj);

        // 2. Variables para SQL
        const p = {
            razon: escapeSQL(razon),
            rfc: escapeSQL(document.getElementById('rfc').value),
            contacto: escapeSQL(document.getElementById('nombre_contacto').value),
            tel: escapeSQL(document.getElementById('telefono').value),
            email: escapeSQL(document.getElementById('email').value),
            dias: document.getElementById('dias_credito').value || 0,
            activo: document.getElementById('activo').value,
            datos: escapeSQL(document.getElementById('Datos').value),
            datos_fiscales: escapeSQL(datosFiscalesJSON) 
        };

        let sql = "";
        
        // NOTA IMPORTANTE: Usar DB_NAME.`TABLE_RAW` en todas las consultas
        if(id) {
            // UPDATE
            sql = `UPDATE ${DB_NAME}.\`${TABLE_RAW}\` SET 
                   razon_social='${p.razon}', 
                   rfc='${p.rfc}', 
                   nombre_contacto='${p.contacto}', 
                   telefono='${p.tel}', 
                   email='${p.email}', 
                   dias_credito='${p.dias}', 
                   activo='${p.activo}', 
                   Datos='${p.datos}', 
                   Datos_Fiscales='${p.datos_fiscales}'
                   WHERE IDPr = ${id}`;
        } else {
            // INSERT
            sql = `INSERT INTO ${DB_NAME}.\`${TABLE_RAW}\` 
                   (razon_social, rfc, nombre_contacto, telefono, email, dias_credito, activo, Datos, Datos_Fiscales) 
                   VALUES ('${p.razon}', '${p.rfc}', '${p.contacto}', '${p.tel}', '${p.email}', '${p.dias}', '${p.activo}', '${p.datos}', '${p.datos_fiscales}')`;
        }

        console.log("SQL Enviado:", sql); // Para depurar

        fetch('../librerias/AJAX/Execute.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `sql=${encodeURIComponent(sql)}&db=${DB_NAME}`
        })
        .then(r => r.json())
        .then(res => {
            if(res.status === 'error' || res.error) {
                Swal.fire('Error SQL', res.error || res.message, 'error');
            } else {
                Swal.fire({
                    icon: 'success', 
                    title: 'Guardado correctamente', 
                    toast: true, position: 'top-end', 
                    showConfirmButton: false, timer: 1500
                });
                $('#modalEdicion').modal('hide');
                listarProveedores();
            }
        })
        .catch(err => Swal.fire('Error de red', err.message, 'error'));
    }

    // --- 3. EDITAR (CARGAR DATOS AL MODAL) ---
    function editarProveedor(row) {
        document.getElementById('IDP').value = row.IDPr; // OJO: Tu base de datos dice IDPr
        document.getElementById('razon_social').value = row.razon_social;
        document.getElementById('rfc').value = row.rfc || '';
        document.getElementById('nombre_contacto').value = row.nombre_contacto || '';
        document.getElementById('telefono').value = row.telefono || '';
        document.getElementById('email').value = row.email || '';
        document.getElementById('dias_credito').value = row.dias_credito || 0;
        document.getElementById('activo').value = row.activo;
        document.getElementById('Datos').value = row.Datos || '';

        // Limpiar campos fiscales
        document.querySelectorAll('.fis-field').forEach(el => el.value = '');
        
        // Cargar JSON Fiscal
        try {
            if(row.Datos_Fiscales) {
                const fis = JSON.parse(row.Datos_Fiscales);
                document.getElementById('fis_calle').value = fis.calle || '';
                document.getElementById('fis_num_ext').value = fis.num_ext || '';
                document.getElementById('fis_num_int').value = fis.num_int || '';
                document.getElementById('fis_colonia').value = fis.colonia || '';
                document.getElementById('fis_cp').value = fis.cp || '';
                document.getElementById('fis_municipio').value = fis.municipio || '';
                document.getElementById('fis_estado').value = fis.estado || '';
                document.getElementById('fis_pais').value = fis.pais || 'México';
                document.getElementById('fis_regimen').value = fis.regimen || '';
                document.getElementById('fis_uso_cfdi').value = fis.uso_cfdi || 'G03';
            }
        } catch(e) { console.warn("JSON Fiscal inválido o vacío"); }
        
        $('#modalEdicion').modal('show');
    }

    // --- 4. ELIMINAR (DELETE) ---
    function eliminarProveedor(id, nombre) {
        Swal.fire({
            title: '¿Eliminar Proveedor?',
            text: `Se borrará permanentemente a: ${nombre}`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                // CORRECCIÓN CRÍTICA: Agregar base de datos y backticks
                const sql = `DELETE FROM ${DB_NAME}.\`${TABLE_RAW}\` WHERE IDPr = ${id}`;
                
                fetch('../librerias/AJAX/Execute.php', {
                    method: 'POST',
                    body: `sql=${encodeURIComponent(sql)}&db=${DB_NAME}`,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                })
                .then(r => r.json())
                .then(res => {
                    if(res.status === 'error') {
                        Swal.fire('Error', res.message, 'error');
                    } else {
                        listarProveedores();
                        Swal.fire('Eliminado', 'El proveedor ha sido borrado.', 'success');
                    }
                });
            }
        });
    }

    function abrirModal() {
        document.getElementById('formProv').reset();
        document.getElementById('IDP').value = '';
        document.getElementById('activo').value = 1;
        $('#modalEdicion').modal('show');
    }

    // --- 5. EXPORTAR EXCEL ---
    function exportarExcel() {
        let table = document.querySelector(".table-prov");
        let html = table.outerHTML.replace(/ /g, '%20');
        let a = document.createElement('a');
        a.href = 'data:application/vnd.ms-excel,' + html;
        a.download = 'Proveedores_' + new Date().toLocaleDateString() + '.xls';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
</script>