<?php
// 1. SEGURIDAD Y CONTEXTO
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado");
}

// Variables de Configuración
$nombre_bd = "MS_Datos";
$prefijo = isset($IDUg) ? $IDU : ($_SESSION['IDU'] ?? '101'); 
$tb_clientes = $prefijo . "-Clientes"; 
?>

<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>
    /* --- ESTILOS VISUALES --- */
    body { background-color: #f0f2f5; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    
    /* Avatares */
    .avatar-circle {
        width: 40px; height: 40px;
        background-color: #3b82f6; color: white;
        border-radius: 50%; display: flex;
        align-items: center; justify-content: center;
        font-weight: bold; font-size: 1rem;
        box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
    }

    /* Tarjetas KPI */
    .kpi-card {
        border: none; border-radius: 12px; background: white;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05); transition: transform 0.2s;
        height: 100%;
    }
    .kpi-card:hover { transform: translateY(-3px); }
    .kpi-icon { width: 50px; height: 50px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; }

    /* Tabla */
    .table-clients thead th { background-color: #f8fafc; color: #64748b; font-size: 0.75rem; text-transform: uppercase; border-bottom: 2px solid #e2e8f0; }
    
    /* Estado */
    .status-pill { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; }
    .st-activo { background: #dcfce7; color: #166534; }
    .st-inactivo { background: #fee2e2; color: #991b1b; }
    .st-lead { background: #e0f2fe; color: #075985; }

    /* MODAL */
    .modal-content { border-radius: 12px; border: none; overflow: hidden; }
    .nav-tabs { border-bottom: 1px solid #dee2e6; padding: 0 1rem; background: #f8f9fa; }
    .nav-tabs .nav-link { border: none; color: #6c757d; font-weight: 600; padding: 1rem 1.5rem; border-radius: 0; }
    .nav-tabs .nav-link.active { color: #0d6efd; border-bottom: 3px solid #0d6efd; background: transparent; }
    .tab-content { background: #fff; min-height: 350px; }
    .modal-header { background: #1e293b; color: white; padding: 1rem 1.5rem; }
    .form-label { font-size: 0.85rem; font-weight: 700; color: #334155; margin-bottom: 5px; }
    .form-control { border-radius: 6px; border: 1px solid #ced4da; padding: 0.6rem; }
    .form-control:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
    
    /* Input disabled style */
    .form-control:disabled { background-color: #e9ecef; cursor: not-allowed; opacity: 1; }
</style>

<div class="container-fluid p-4">
    
    <div class="row mb-4">
        <div class="col-md-8">
            <h3 class="font-weight-bold text-dark mb-1"><i class="fas fa-users mr-2"></i>Gestión de Clientes</h3>
            <p class="text-muted mb-0">Administra perfiles, datos fiscales y accesos.</p>
        </div>
        <div class="col-md-4 text-right">
             <button class="btn btn-primary shadow-sm font-weight-bold" onclick="abrirModal()">
                <i class="fas fa-user-plus mr-2"></i> Nuevo Cliente
            </button>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center">
                <div class="kpi-icon bg-light text-primary mr-3"><i class="fas fa-users"></i></div>
                <div><h4 class="mb-0 font-weight-bold" id="kpi_total">0</h4><small class="text-muted">Total Clientes</small></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center">
                <div class="kpi-icon bg-light text-success mr-3"><i class="fas fa-user-check"></i></div>
                <div><h4 class="mb-0 font-weight-bold" id="kpi_activos">0</h4><small class="text-muted">Activos</small></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center">
                <div class="kpi-icon bg-light text-info mr-3"><i class="fas fa-wallet"></i></div>
                <div><h4 class="mb-0 font-weight-bold" id="kpi_valor">$0</h4><small class="text-muted">Valor Cartera</small></div>
            </div>
        </div>
         <div class="col-md-3">
            <div class="kpi-card p-3 d-flex align-items-center">
                <div class="kpi-icon bg-light text-warning mr-3"><i class="fas fa-bullhorn"></i></div>
                <div><h4 class="mb-0 font-weight-bold" id="kpi_leads">0</h4><small class="text-muted">Leads / Prospectos</small></div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-3">
        <div class="card-header bg-white py-3 border-0">
            <div class="input-group" style="max-width: 350px;">
                <span class="input-group-text bg-light border-0"><i class="fas fa-search text-muted"></i></span>
                <input type="text" id="buscador" class="form-control bg-light border-0" placeholder="Buscar por nombre, email o teléfono...">
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover table-clients align-middle mb-0">
                <thead>
                    <tr>
                        <th class="pl-4">Cliente</th>
                        <th>Contacto</th>
                        <th>Origen</th>
                        <th class="text-center">Valor</th>
                        <th class="text-center">Estado</th>
                        <th class="text-right pr-4">Acciones</th>
                    </tr>
                </thead>
                <tbody id="tbody_clientes"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCliente" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content shadow-lg">
            <div class="modal-header">
                <h5 class="modal-title font-weight-bold" id="modalTitulo">Nuevo Cliente</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            
            <form id="formCliente">
                <input type="hidden" id="IDC">
                <input type="hidden" id="IDU">
                
                <ul class="nav nav-tabs" id="myTab" role="tablist">
                    <li class="nav-item"><a class="nav-link active" id="tab-perfil" data-toggle="tab" href="#perfil" role="tab">Perfil</a></li>
                    <li class="nav-item"><a class="nav-link" id="tab-fiscal" data-toggle="tab" href="#fiscal" role="tab">Datos Fiscales</a></li>
                    <li class="nav-item"><a class="nav-link" id="tab-seguridad" data-toggle="tab" href="#seguridad" role="tab">Seguridad</a></li>
                </ul>

                <div class="tab-content" id="myTabContent">
                    
                    <div class="tab-pane fade show active" id="perfil" role="tabpanel">
                        <div class="p-3">
                            <div class="row">
                                <div class="col-md-8 mb-3">
                                    <label class="form-label">Nombre Completo <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control font-weight-bold" id="Nombre" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Fecha Nacimiento</label>
                                    <input type="date" class="form-control" id="FechaNacimiento">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Teléfono / WhatsApp <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control font-weight-bold" id="Telefono" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Email Principal <small class="text-muted">(Opcional)</small></label>
                                    <input type="email" class="form-control" id="Email">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Dirección Física</label>
                                    <textarea class="form-control" id="Direccion" rows="2"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="fiscal" role="tabpanel">
                        <div class="p-3">
                            <div class="row">
                                <div class="col-12 mb-3">
                                    <div class="alert alert-info border-info small p-2 m-0">
                                        <i class="fas fa-info-circle mr-1"></i> Estos datos se generan dinámicamente desde la configuración.
                                    </div>
                                </div>
                                
                                <div id="contenedor_fiscal" class="row w-100 m-0 p-0"></div>

                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="seguridad" role="tabpanel">
                        <div class="p-3">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label text-primary">Contraseña de Acceso</label>
                                    <div class="input-group">
                                        <input type="password" class="form-control border-primary" id="Pass" placeholder="Opcional">
                                        <div class="input-group-append">
                                            <button class="btn btn-outline-primary" type="button" onclick="togglePass()"><i class="fas fa-eye"></i></button>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Token (Auto)</label>
                                    <input type="text" class="form-control bg-light" id="Token" readonly>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Fuente Adquisición</label>
                                    <select class="form-control" id="FuenteAdquisicion">
                                        <option value="Directo">Directo</option>
                                        <option value="Facebook">Facebook Ads</option>
                                        <option value="Google">Google Ads</option>
                                        <option value="Referido">Referido</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Estado</label>
                                    <select class="form-control font-weight-bold" id="EstadoCliente">
                                        <option value="Activo" class="text-success">Activo</option>
                                        <option value="Inactivo" class="text-danger">Inactivo</option>
                                        <option value="Lead" class="text-primary">Lead / Prospecto</option>
                                    </select>
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label">Notas Internas</label>
                                    <textarea class="form-control" id="NotasInternas" rows="2"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-primary px-4 font-weight-bold shadow-sm" onclick="guardarCliente()">
                        <i class="fas fa-save mr-2"></i> Guardar Cliente
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const DB = "<?php echo $nombre_bd; ?>";
    const TB = "<?php echo $tb_clientes; ?>";
    const safe = (str) => str ? String(str).replace(/'/g, "\\'") : '';

    // ==========================================
    // ⚙️ CONFIGURACIÓN DE CAMPOS FISCALES (JSON)
    // ==========================================
    const FISCAL_FIELDS = [
        { id: "rfc", label: "RFC / ID Tributario", type: "text", col: "6", placeholder: "XAXX010101000" },
        { id: "razon", label: "Razón Social", type: "text", col: "6", placeholder: "Nombre Fiscal" },
        { id: "regimen", label: "Régimen Fiscal", type: "text", col: "4", placeholder: "601 - General" },
        { id: "cp", label: "Código Postal Fiscal", type: "number", col: "4", placeholder: "00000" },
        { id: "uso", label: "Uso de CFDI", type: "select", col: "4", options: [
            {val: "G03", text: "G03 - Gastos en general"},
            {val: "P01", text: "P01 - Por definir"},
            {val: "S01", text: "S01 - Sin efectos fiscales"},
            {val: "I01", text: "I01 - Construcciones"}
        ]}
    ];

    document.addEventListener('DOMContentLoaded', () => {
        console.log("Sistema Iniciado.");
        renderizarFiscal(); 
        listarClientes();
        
        document.getElementById('buscador').addEventListener('keyup', function(e) {
            const term = e.target.value.toLowerCase();
            document.querySelectorAll('#tbody_clientes tr').forEach(row => {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(term) ? '' : 'none';
            });
        });
    });

    // --- RENDERIZADOR FISCAL ---
    function renderizarFiscal() {
        const contenedor = document.getElementById('contenedor_fiscal');
        contenedor.innerHTML = ''; 

        FISCAL_FIELDS.forEach(campo => {
            let inputHtml = '';
            if (campo.type === 'select') {
                let optionsHtml = '';
                campo.options.forEach(opt => { optionsHtml += `<option value="${opt.val}">${opt.text}</option>`; });
                inputHtml = `<select class="form-control" id="dyn_${campo.id}">${optionsHtml}</select>`;
            } else {
                inputHtml = `<input type="${campo.type}" class="form-control" id="dyn_${campo.id}" placeholder="${campo.placeholder || ''}">`;
            }
            const div = document.createElement('div');
            div.className = `col-md-${campo.col} mb-3`;
            div.innerHTML = `<label class="form-label">${campo.label}</label>${inputHtml}`;
            contenedor.appendChild(div);
        });
    }

    // --- UUID MANUAL ---
    function generarUUID() {
       return '<?php echo $IDU ?? "0"; ?>';
    }

    // --- LISTAR ---
    function listarClientes() {
        const sql = `SELECT * FROM \`${TB}\` ORDER BY IDC DESC LIMIT 200`;
        const tbody = document.getElementById('tbody_clientes');
        
        fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=${DB}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
        .then(r => r.json())
        .then(res => {
            tbody.innerHTML = '';
            let total = 0, activos = 0, leads = 0, valor = 0;

            if(res.data && res.data.length > 0) {
                res.data.forEach(c => {
                    total++;
                    if(c.EstadoCliente === 'Activo') activos++;
                    if(c.EstadoCliente === 'Lead') leads++;
                    valor += parseFloat(c.ValorCliente || 0);

                    const iniciales = c.Nombre ? c.Nombre.substring(0,2).toUpperCase() : "NN";
                    const colorAvatar = obtenerColorAvatar(c.Nombre || "X");
                    
                    let badgeClass = 'st-inactivo';
                    if(c.EstadoCliente === 'Activo') badgeClass = 'st-activo';
                    if(c.EstadoCliente === 'Lead') badgeClass = 'st-lead';
                    
                    const emailTxt = c.Email ? c.Email : '<span class="text-muted font-italic">Sin Email</span>';
                    const telTxt = c.Telefono ? c.Telefono : '--';

                    tbody.innerHTML += `
                        <tr>
                            <td class="pl-4">
                                <div class="d-flex align-items-center">
                                    <div class="avatar-circle mr-3 text-white" style="background-color: ${colorAvatar}">${iniciales}</div>
                                    <div>
                                        <div class="font-weight-bold text-dark">${c.Nombre}</div>
                                        <small class="text-muted" style="font-size:0.75rem">Reg: ${c.Timestamp ? c.Timestamp.substring(0,10) : '--'}</small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="small font-weight-bold"><i class="fas fa-phone text-success mr-1"></i> ${telTxt}</div>
                                <div class="small mt-1"><i class="fas fa-envelope text-muted mr-1"></i> ${emailTxt}</div>
                            </td>
                            <td><span class="badge badge-light border text-muted">${c.FuenteAdquisicion || 'Directo'}</span></td>
                            <td class="text-center font-weight-bold text-dark">$${parseFloat(c.ValorCliente || 0).toLocaleString()}</td>
                            <td class="text-center"><span class="status-pill ${badgeClass}">${c.EstadoCliente}</span></td>
                            <td class="text-right pr-4">
                                <button class="btn btn-sm btn-outline-dark rounded-circle mr-1" onclick='editarCliente(${JSON.stringify(c)})'><i class="fas fa-pen"></i></button>
                                <button class="btn btn-sm btn-outline-danger rounded-circle" onclick="eliminarCliente(${c.IDC})"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                    `;
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center py-5 text-muted">No hay clientes registrados.</td></tr>';
            }
            
            document.getElementById('kpi_total').innerText = total;
            document.getElementById('kpi_activos').innerText = activos;
            document.getElementById('kpi_leads').innerText = leads;
            document.getElementById('kpi_valor').innerText = '$' + valor.toLocaleString();
        });
    }

    // --- GUARDAR (MEJORADO CON ERROR DETECTION) ---
    async function guardarCliente() {
        console.log("--- Guardando ---");
        
        const idc = document.getElementById('IDC').value;
        const passRaw = document.getElementById('Pass').value;
        let passFinal = "";

        if(!document.getElementById('Nombre').value.trim() || !document.getElementById('Telefono').value.trim()) {
            Swal.fire('Faltan Datos', 'El Nombre y el Teléfono son obligatorios.', 'warning');
            return;
        }

        // 1. Password
        if (passRaw.length > 0) {
            try {
                const response = await fetch('../librerias/AJAX/pass.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ passwordCliente: passRaw }) });
                const result = await response.json();
                if (result.hash_guardado) passFinal = result.hash_guardado;
                else { Swal.fire('Error', 'No se pudo encriptar la contraseña.', 'error'); return; }
            } catch (error) { console.error(error); Swal.fire('Error', 'Fallo conexión pass.php', 'error'); return; }
        }

        // 2. Datos Dinámicos
        let fiscalData = {};
        FISCAL_FIELDS.forEach(campo => {
            const input = document.getElementById('dyn_' + campo.id);
            if(input) fiscalData[campo.id] = input.value;
        });

        // 3. Preparar Objeto
        // IMPORTANTE: Para IDU usamos PHP si es nuevo, para token usamos JS
        const tempToken = generarToken(8); 
        const tempIDU = 'CLI-' + Date.now(); 

        const data = {
            idu: document.getElementById('IDU').value || tempIDU, 
            token: document.getElementById('Token').value || tempToken,
            nombre: document.getElementById('Nombre').value.trim(),
            email: document.getElementById('Email').value.trim(),
            pass: passFinal,
            tel: document.getElementById('Telefono').value.trim(),
            dir: document.getElementById('Direccion').value,
            nac: document.getElementById('FechaNacimiento').value,
            fuente: document.getElementById('FuenteAdquisicion').value,
            estado: document.getElementById('EstadoCliente').value,
            notas: document.getElementById('NotasInternas').value,
            fiscal_json: JSON.stringify(fiscalData)
        };

        // 4. SQL
        let sql = "";
        if(idc) {
            let passSql = (passFinal.length > 0) ? `, Pass='${safe(passFinal)}'` : ""; 
            sql = `UPDATE \`${TB}\` SET Nombre='${safe(data.nombre)}', Email='${safe(data.email)}', Telefono='${safe(data.tel)}', Direccion='${safe(data.dir)}', FechaNacimiento='${data.nac}', FuenteAdquisicion='${safe(data.fuente)}', EstadoCliente='${safe(data.estado)}', NotasInternas='${safe(data.notas)}', Datos_Fiscales='${safe(data.fiscal_json)}' ${passSql} WHERE IDC=${idc}`;
        } else {
            sql = `INSERT INTO \`${TB}\` (IDU, Token, Nombre, Email, Pass, Telefono, Direccion, FechaNacimiento, FuenteAdquisicion, EstadoCliente, NotasInternas, Datos_Fiscales) VALUES ('${data.idu}', '${data.token}', '${safe(data.nombre)}', '${safe(data.email)}', '${safe(data.pass)}', '${safe(data.tel)}', '${safe(data.dir)}', '${data.nac}', '${safe(data.fuente)}', '${safe(data.estado)}', '${safe(data.notas)}', '${safe(data.fiscal_json)}')`;
        }

        // 5. EJECUTAR Y PROCESAR ERRORES (LOGICA CORREGIDA)
        fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=${DB}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
        .then(r => r.json()) 
        .then(res => {
            console.log("Respuesta BD:", res);

            // DETECCIÓN INTELIGENTE DE ERRORES (Soporta ambos formatos)
            let errorMsg = res.status === 'error' ? res.message : null;
            if (!errorMsg && res.error) errorMsg = res.error;

            if (errorMsg) {
                // ANÁLISIS DE ERROR ESPECÍFICO
                let msg = errorMsg;
                if(msg.includes("Duplicate entry")) {
                    if(msg.includes("Telefono")) msg = "El **Teléfono** ingresado ya existe en otro cliente.";
                    else if(msg.includes("Email")) msg = "El **Email** ingresado ya existe en otro cliente.";
                    else if(msg.includes("Token")) msg = "Error interno de Token duplicado, intente de nuevo.";
                    else msg = "Dato duplicado en la base de datos.";
                }
                Swal.fire({ icon: 'error', title: 'Error al Guardar', html: msg });
            } else {
                Swal.fire({icon: 'success', title: 'Guardado Correctamente', toast: true, position: 'top-end', showConfirmButton: false, timer: 1500});
                $('#modalCliente').modal('hide');
                listarClientes();
            }
        })
        .catch(err => {
            console.error("Error Crítico JS/PHP:", err);
            Swal.fire('Error del Servidor', 'Revisa la consola (F12). Posiblemente Execute.php devolvió HTML de error.', 'error');
        });
    }

    // --- HELPER FUNCIONES ---
    function abrirModal() {
        document.getElementById('formCliente').reset();
        document.getElementById('IDC').value = '';
        document.getElementById('IDU').value = ''; 
        document.getElementById('Token').value = generarToken(8);
        document.getElementById('modalTitulo').innerText = "Nuevo Cliente";
        
        // Bloquear fecha Nacimiento
        const hoy = new Date();
        const fechaHoy = hoy.getFullYear() + '-' + String(hoy.getMonth() + 1).padStart(2, '0') + '-' + String(hoy.getDate()).padStart(2, '0');
        const inputNac = document.getElementById('FechaNacimiento');
        inputNac.value = fechaHoy;  
        inputNac.disabled = true;   

        FISCAL_FIELDS.forEach(c => { if(document.getElementById('dyn_' + c.id)) document.getElementById('dyn_' + c.id).value = ''; });

        $('.nav-tabs a[href="#perfil"]').tab('show');
        $('#modalCliente').modal('show');
    }

    function editarCliente(c) {
        document.getElementById('IDC').value = c.IDC;
        document.getElementById('IDU').value = c.IDU;
        document.getElementById('Token').value = c.Token;
        document.getElementById('Nombre').value = c.Nombre;
        document.getElementById('Email').value = c.Email;
        document.getElementById('Pass').value = ''; 
        document.getElementById('Telefono').value = c.Telefono;
        document.getElementById('Direccion').value = c.Direccion;
        document.getElementById('FechaNacimiento').value = c.FechaNacimiento;
        document.getElementById('FuenteAdquisicion').value = c.FuenteAdquisicion;
        document.getElementById('EstadoCliente').value = c.EstadoCliente;
        document.getElementById('NotasInternas').value = c.NotasInternas;
        
        // Desbloquear fecha
        document.getElementById('FechaNacimiento').disabled = false;

        try {
            const f = JSON.parse(c.Datos_Fiscales || '{}');
            FISCAL_FIELDS.forEach(campo => {
                if(document.getElementById('dyn_' + campo.id)) {
                    document.getElementById('dyn_' + campo.id).value = f[campo.id] || '';
                }
            });
        } catch(e) { }

        document.getElementById('modalTitulo').innerText = "Editar: " + c.Nombre;
        $('.nav-tabs a[href="#perfil"]').tab('show');
        $('#modalCliente').modal('show');
    }

    function eliminarCliente(id) {
        Swal.fire({ title: '¿Eliminar?', text: "No se puede deshacer.", icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33' }).then((result) => {
            if (result.isConfirmed) {
                const sql = `DELETE FROM \`${TB}\` WHERE IDC=${id}`;
                fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=${DB}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(() => listarClientes());
            }
        });
    }

    function generarToken(length) {
        let result = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        for (let i = 0; i < length; i++) result += characters.charAt(Math.floor(Math.random() * characters.length));
        return result;
    }
    function togglePass() { const x = document.getElementById("Pass"); x.type = x.type === "password" ? "text" : "password"; }
    function obtenerColorAvatar(str) {
        const colores = ['#ef4444', '#f97316', '#f59e0b', '#84cc16', '#10b981', '#06b6d4', '#3b82f6', '#6366f1', '#8b5cf6', '#d946ef', '#f43f5e'];
        let hash = 0;
        for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
        return colores[Math.abs(hash) % colores.length];
    }
</script>