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

$db_usuarios = "MS_Usuario";
$IDUg_SISTEMA = $_SESSION['IDUg'] ?? 1; 
?>

<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; }
    .card-metric { border: none; border-radius: 12px; background: white; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
    .table-ui thead th { font-size: 0.75rem; text-transform: uppercase; color: #6c757d; background: #f8f9fa; border-bottom: 2px solid #e9ecef; padding: 15px; }
    .avatar-user { 
        width: 45px; height: 45px; background: linear-gradient(135deg, #404E67 0%, #6e8efb 100%);
        color: white; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; font-weight: bold;
    }
    .status-pill { padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: bold; color: white; }
    .bg-active { background-color: #2ed8b6; }
    .bg-inactive { background-color: #ff5370; }
</style>

<div class="container-fluid p-3">
    <div class="row mb-4">
        <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 font-weight-bold">USUARIOS</small><h3 class="mb-0 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-users 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 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-user-check 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 font-weight-bold">ADMINS</small><h3 class="mb-0 text-info font-weight-bold" id="kpi_admins">0</h3></div>
                    <div class="icon-shape bg-light text-info rounded-circle p-3"><i class="fas fa-user-shield 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 d-flex justify-content-between align-items-center">
            <h5 class="mb-0 font-weight-bold text-dark"><i class="fas fa-id-badge mr-2 text-primary"></i>Gestión de Usuarios</h5>
            <div>
                <button class="btn btn-success mr-2" onclick="exportarExcel()"><i class="fas fa-file-excel mr-1"></i> Excel</button>
                <button class="btn btn-dark" onclick="abrirModal()"><i class="fas fa-plus-circle mr-1"></i> Nuevo</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover align-middle table-ui mb-0" id="tabla_principal">
                <thead>
                    <tr>
                        <th class="text-center">IDU</th>
                        <th>Nombre / Usuario</th>
                        <th>Contacto</th>
                        <th>Rol</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" id="modalUsuario" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title font-weight-bold">Datos de Usuario</h5>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body p-4 bg-light">
                <form id="formUser">
                    <input type="hidden" id="IDU">
                    <div class="row">
                        <div class="col-md-8 form-group">
                            <label class="font-weight-bold">Nombre Completo *</label>
                            <input type="text" class="form-control" id="Nombre" required>
                        </div>
                        <div class="col-md-4 form-group">
                            <label>Teléfono</label>
                            <input type="text" class="form-control" id="Telefono_1">
                        </div>
                        <div class="col-md-12 form-group">
                            <label>Email Corporativo</label>
                            <input type="email" class="form-control" id="EMail">
                        </div>
                        <div class="col-md-12"><hr><small class="text-primary font-weight-bold">SEGURIDAD Y ROL</small></div>
                        <div class="col-md-6 form-group">
                            <label>Nombre de Usuario (@)</label>
                            <input type="text" class="form-control" id="User_Acceso" required>
                        </div>
                        <div class="col-md-6 form-group">
                            <label>Contraseña</label>
                            <input type="password" class="form-control" id="Password" placeholder="Solo para nuevos o cambios">
                        </div>
                        <div class="col-md-6 form-group">
                            <label>Rol</label>
                            <select class="form-control" id="Rol">
                                <option value="Ventas">Ventas</option>
                                <option value="Admin">Admin</option>
                            </select>
                        </div>
                        <div class="col-md-6 form-group">
                            <label>Estado</label>
                            <select class="form-control" id="Estado">
                                <option value="Activo">Activo</option>
                                <option value="Inactivo">Inactivo</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-primary btn-block font-weight-bold py-2" onclick="guardarUsuario()">GUARDAR CAMBIOS</button>
            </div>
        </div>
    </div>
</div>

<script>
const DB_NAME = "<?php echo $db_usuarios; ?>";
const IDUg_SISTEMA = "<?php echo $IDUg_SISTEMA; ?>";

document.addEventListener('DOMContentLoaded', () => { window.listarUsuarios(); });

window.listarUsuarios = function() {
    const tbody = document.getElementById('tabla_body');
    const sql = `SELECT u.IDU, u.Nombre, u.EMail, u.Telefono_1, d.User, d.Rol, d.Estado FROM Usuarios u INNER JOIN Usuarios_Datos d ON u.IDU = d.IDU AND IDUg=<?php echo $IDUg_SISTEMA; ?> ORDER BY u.IDU DESC`;
	console.log(sql)
    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 => {
        let d = res.data || (Array.isArray(res) ? res : []);
        tbody.innerHTML = '';
        let tot = 0, act = 0, adm = 0;
        d.forEach(row => {
            tot++; if(row.Estado === 'Activo') act++; if(row.Rol === 'Admin') adm++;
            tbody.innerHTML += `<tr><td class="text-center">${row.IDU}</td><td><b>${row.Nombre}</b><br><small>@${row.User}</small></td><td><small>${row.EMail}<br>${row.Telefono_1}</small></td><td>${row.Rol}</td><td class="text-center"><span class="status-pill ${row.Estado == 'Activo' ? 'bg-active' : 'bg-inactive'}">${row.Estado}</span></td><td class="text-right pr-4"><button class="btn btn-sm btn-light border" onclick='editarUsuario(${JSON.stringify(row)})'><i class="fas fa-edit"></i></button></td></tr>`;
        });
        document.getElementById('kpi_total').innerText = tot;
        document.getElementById('kpi_activos').innerText = act;
        document.getElementById('kpi_admins').innerText = adm;
    });
};

// --- GUARDAR CON CIFRADO ---
window.guardarUsuario = async function() {
    const id = document.getElementById('IDU').value;
    const passInput = document.getElementById('Password').value;
    const nombre = document.getElementById('Nombre').value.trim();
    const user = document.getElementById('User_Acceso').value.trim();

    if(!nombre || !user) return Swal.fire('Error', 'Datos incompletos', 'error');

    // 1. Decidir si cifrar
    let hashFinal = "";
    let passAProcesar = passInput;
    if(!id && !passInput) passAProcesar = "12345"; // Default para nuevos

    try {
        if (passAProcesar) {
            // PETICIÓN A PASS.PHP (JSON REAL)
            const respCifrado = await fetch('../librerias/AJAX/Pass.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ passwordCliente: passAProcesar })
            }).then(r => r.json());

            if (respCifrado.hash_guardado) {
                hashFinal = respCifrado.hash_guardado;
            } else {
                throw new Error("No se recibió hash del servidor");
            }
        }

        const safe = (s) => s ? s.replace(/'/g, "\\'") : '';
        const token = Math.random().toString(36).substring(2, 12);

        if(id) {
            // UPDATE
            let sql1 = `UPDATE Usuarios SET Nombre='${safe(nombre)}', EMail='${safe(document.getElementById('EMail').value)}', Telefono_1='${safe(document.getElementById('Telefono_1').value)}' WHERE IDU=${id}`;
            let updPass = hashFinal ? `, Password='${safe(hashFinal)}'` : '';
            let sql2 = `UPDATE Usuarios_Datos SET User='${safe(user)}', Rol='${safe(document.getElementById('Rol').value)}', Estado='${safe(document.getElementById('Estado').value)}' ${updPass} WHERE IDU=${id}`;
            
            await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql1)}&db=${DB_NAME}` });
            await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql2)}&db=${DB_NAME}` });
        } else {
            // INSERT
            let sql1 = `INSERT INTO Usuarios (Nombre, EMail, Telefono_1) VALUES ('${safe(nombre)}', '${safe(document.getElementById('EMail').value)}', '${safe(document.getElementById('Telefono_1').value)}')`;
            await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql1)}&db=${DB_NAME}` });
            
            let sql2 = `INSERT INTO Usuarios_Datos (IDU, IDUg, Rol, User, Password, Estado, Token) VALUES (LAST_INSERT_ID(), ${IDUg_SISTEMA}, '${document.getElementById('Rol').value}', '${safe(user)}', '${safe(hashFinal)}', 'Activo', '${token}')`;
            await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql2)}&db=${DB_NAME}` });
        }

        Swal.fire('Éxito', 'Usuario guardado y cifrado', 'success');
        $('#modalUsuario').modal('hide');
        window.listarUsuarios();
    } catch (e) {
        Swal.fire('Error', 'Fallo en cifrado o base de datos', 'error');
    }
};

window.abrirModal = () => { document.getElementById('formUser').reset(); document.getElementById('IDU').value = ''; $('#modalUsuario').modal('show'); };
window.editarUsuario = (row) => {
    document.getElementById('IDU').value = row.IDU;
    document.getElementById('Nombre').value = row.Nombre;
    document.getElementById('EMail').value = row.EMail;
    document.getElementById('Telefono_1').value = row.Telefono_1;
    document.getElementById('User_Acceso').value = row.User;
    document.getElementById('Rol').value = row.Rol;
    document.getElementById('Estado').value = row.Estado;
    document.getElementById('Password').value = "";
    $('#modalUsuario').modal('show');
};
</script>