<?php
include ('includes/header.php');
// Definir el nombre de la tabla
$table_name = "playlist";
// Obtener todos los DNS
$dnss = $db->select('dns', '*', '', '');
$dnsMap = [];
foreach($dnss as $dns) {
    $dnsMap[$dns['id']] = $dns['title'];
}
// Configuración de paginación
$items_per_page = 10;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($current_page < 1) $current_page = 1;
// Verificar conexión a la base de datos
if (!$db) {
    die("Error de conexión a la base de datos");
}
// Obtener total de registros
try {
    $total_items = $db->select($table_name, 'COUNT(*) as total', '', '')[0]['total'];
    $total_pages = ceil($total_items / $items_per_page);
    $offset = ($current_page - 1) * $items_per_page;
} catch (Exception $e) {
    die("Error al obtener datos: " . $e->getMessage());
}
// Función para formatear MAC
function formatMac($mac) {
    $mac = strtoupper(preg_replace('/[^0-9A-F]/', '', $mac));
    return implode(':', str_split($mac, 2));
}
// Función para cambiar protección
if (isset($_GET['toggle_protect'])) {
    $id = (int)$_GET['toggle_protect'];
    $current = $db->select($table_name, 'is_protected', 'id = :id', '', [':id' => $id])[0]['is_protected'];
    $new_value = $current ? 0 : 1;
    $db->update($table_name, ['is_protected' => $new_value], 'id = :id', [':id' => $id]);
    echo "<script>window.location.href='". basename($_SERVER["SCRIPT_NAME"])."?status=1'</script>";
    exit();
}
// Eliminar usuarios vencidos masivamente
if (isset($_POST['delete_expired'])) {
    $today = date('Y-m-d');
   $db->delete($table_name, 'expiracion < :today', [':today' => $today]);
     echo "<script>window.location.href='". basename($_SERVER["SCRIPT_NAME"])."?status=2'</script>";
    exit();
}
// Eliminar múltiples seleccionados
if (isset($_POST['delete_selected']) && isset($_POST['selected_ids'])) {
    $ids = $_POST['selected_ids'];
    $placeholders = [];
    $params = [];
    
    foreach ($ids as $index => $id) {
        $placeholders[] = ':id'.$index;
        $params[':id'.$index] = (int)$id;
    }

    if (!empty($placeholders)) {
        $db->delete($table_name, 'id IN ('.implode(',', $placeholders).')', $params);
        echo "<script>window.location.href='". basename($_SERVER["SCRIPT_NAME"])."?status=2'</script>";
        exit();
    }
}
// Procesar nuevo registro
if (isset($_POST['submit'])){
    unset($_POST['submit']);
    $_POST['is_protected'] = isset($_POST['is_protected']) ? 1 : 0;
    
    if (!empty($_POST['mac_address']) && !empty($_POST['username']) && !empty($_POST['password'])) {
        // Procesar cada MAC address
        $macs = is_array($_POST['mac_address']) ? $_POST['mac_address'] : [$_POST['mac_address']];
        $successCount = 0;
        
        foreach ($macs as $mac) {
            if (!empty(trim($mac))) {
                $data = $_POST;
                $data['mac_address'] = formatMac($mac);
                $db->insert($table_name, $data);
                $successCount++;
            }
        }
        if ($successCount > 0) {
            echo "<script>window.location.href='". basename($_SERVER["SCRIPT_NAME"])."?status=1&count=".$successCount."'</script>";
            exit();
        } else {
            $error = "Por favor ingrese al menos una dirección MAC válida";
        }
    } else {
        $error = "Por favor complete todos los campos requeridos";
    }
}
// Obtener datos para actualizar
@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);
// Procesar actualización
if(isset($_POST['submitU'])){
    unset($_POST['submitU']);
    $_POST['is_protected'] = isset($_POST['is_protected']) ? 1 : 0;
    $_POST['mac_address'] = formatMac(is_array($_POST['mac_address']) ? $_POST['mac_address'][0] : $_POST['mac_address']);

    if (!empty($_POST['mac_address']) && !empty($_POST['username']) && !empty($_POST['password'])) {
        $db->update($table_name, $_POST, 'id = :id',[':id' => $_GET['update']]);
       echo "<script>window.location.href='". basename($_SERVER["SCRIPT_NAME"])."?status=1'</script>";
        exit();
    } else {
        $error = "Por favor complete todos los campos requeridos";
    }
}
// Procesar eliminación
if(isset($_GET['delete'])){
    if(isset($_GET['confirm']) && $_GET['confirm'] == 1) {
        $db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
        echo "<script>window.location.href='". basename($_SERVER["SCRIPT_NAME"])."?status=2'</script>";
        exit();
    } else {
        // Mostrar modal de confirmación
        echo '
        <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header bg-danger text-white">
                        <h5 class="modal-title">Confirmar Eliminación</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        ¿Está seguro que desea eliminar este registro?
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                        <a href="?delete='.$_GET['delete'].'&confirm=1" class="btn btn-danger">Eliminar</a>
                    </div>
                </div>
            </div>
        </div>
        <script>
            $(document).ready(function(){
                $("#deleteModal").modal("show");
            });
        </script>';
    }
}
// Obtener datos con paginación
$res = $db->select($table_name, '*', '', 'LIMIT '.$items_per_page.' OFFSET '.$offset);

// Mostrar formulario de creación/edición
if (isset($_GET['create']) || isset($_GET['update'])) { 
    $is_update = isset($_GET['update']);
?>
<div class="col-md-8 mx-auto">
    <div class="card bg-dark text-white">
        <div class="card-header">
            <h2 class="text-center"><?= $is_update ? 'Editar' : 'Agregar' ?> Usuario</h2>
        </div>
        <div class="card-body">
            <?php if(isset($error)): ?>
                <div class="alert alert-danger"><?= $error ?></div>
            <?php endif; ?>
            
            <form method="post">
                <?php if($is_update): ?>
                    <input type="hidden" name="id" value="<?= $resU[0]['id'] ?>">
                <?php endif; ?>
                
                <div class="form-group">
                    <label>DNS</label>
                    <select class="form-control" name="dns_id" required>
                        <option value="">Seleccione uno</option>
                        <?php foreach($dnss as $dns): ?>
                            <option value="<?= $dns['id'] ?>" <?= ($is_update && $dns['id'] == $resU[0]['dns_id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($dns['title']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select> 
                </div>
                
                <div class="form-group">
                    <label>MAC Address</label>
                    <div id="macs-container">
    <div class="input-group mb-2 mac-input-group">
        <input class="form-control mac-input" name="mac_address[]" placeholder="" required
               value="<?= $is_update ? htmlspecialchars($resU[0]['mac_address']) : '' ?>">
        <div class="input-group-append">
            <button type="button" class="btn btn-success add-mac-btn">
                <i class="fas fa-plus"></i>
            </button>
                            </div>
                        </div>
                    </div>
                    <small class="form-text text-muted">Puede agregar hasta 5 direcciones MAC por cliente</small>
                </div>
                
                <div class="form-group">
                    <label>Usuario</label>
                    <input class="form-control" name="username" 
                           value="<?= $is_update ? htmlspecialchars($resU[0]['username']) : '' ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Contraseña</label>
                    <input class="form-control" name="password" 
                           value="<?= $is_update ? htmlspecialchars($resU[0]['password']) : '' ?>" required>
                </div>
                
                <div class="form-group">
                    <label>PIN Parental</label>
                    <input class="form-control" name="pin" 
                           value="<?= $is_update ? htmlspecialchars($resU[0]['pin']) : '0000' ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Nombre del Cliente</label>
                    <input class="form-control" name="cliente_nombre" 
                           value="<?= $is_update ? htmlspecialchars($resU[0]['cliente_nombre']) : '' ?>" required>
                </div>

                <div class="form-group">
                    <label>WhatsApp</label>
                    <input class="form-control" name="cliente_whatsapp" 
                           value="<?= $is_update ? htmlspecialchars($resU[0]['cliente_whatsapp']) : '' ?>" required>
                </div>

                <div class="form-group">
                    <label>Fecha de Expiración</label>
                    <input class="form-control" name="expiracion" type="date" 
                           value="<?= $is_update ? htmlspecialchars($resU[0]['expiracion']) : '' ?>" required>
                </div>

                <div class="form-group form-check">
                    <input type="checkbox" class="form-check-input" name="is_protected" id="is_protected" value="1" 
                           <?= ($is_update && $resU[0]['is_protected']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="is_protected">
                        <i class="fas fa-lock"></i> Proteger lista (evitar modificaciones en la app)
                    </label>
                </div>

                <div class="text-center">
                    <button type="submit" name="<?= $is_update ? 'submitU' : 'submit' ?>" class="btn btn-info">
                        <i class="fas fa-save"></i> <?= $is_update ? 'Actualizar' : 'Guardar' ?>
                    </button>
                    <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>" class="btn btn-secondary">Cancelar</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Formateador de MAC address
document.addEventListener('input', function(e) {
    if (e.target && e.target.matches('.mac-input')) {
        let value = e.target.value.toUpperCase().replace(/[^0-9A-F]/g, '');
        let formatted = '';
        
        for (let i = 0; i < value.length && i < 12; i += 2) {
            formatted += value.substr(i, 2);
            if (i < value.length - 2 && i < 10) {
                formatted += ':';
            }
        }
        
        e.target.value = formatted;
    }
});

// Agregar nuevo campo MAC
document.addEventListener('click', function(e) {
    if (e.target && e.target.closest('.add-mac-btn')) {
        const container = document.getElementById('macs-container');
        const macGroups = container.querySelectorAll('.mac-input-group');
        
        if (macGroups.length < 5) {
            const newGroup = document.createElement('div');
            newGroup.className = 'input-group mb-2 mac-input-group';
            newGroup.innerHTML = `
                <input class="form-control mac-input" name="mac_address[]" placeholder="" required>
                <div class="input-group-append">
                    <button type="button" class="btn btn-danger remove-mac-btn">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            `;
            container.appendChild(newGroup);
        } else {
            alert('Máximo 5 direcciones MAC por cliente');
        }
    }
    
    // Eliminar campo MAC
    if (e.target && e.target.closest('.remove-mac-btn')) {
        const macGroup = e.target.closest('.mac-input-group');
        if (document.querySelectorAll('.mac-input-group').length > 1) {
            macGroup.remove();
        } else {
            macGroup.querySelector('input').value = '';
        }
    }
});
</script>
<?php } else { ?>
<div class="col-md-12 mx-auto">
    <div class="card bg-dark text-white">
        <div class="card-header">
            <h2 class="text-center">Usuarios Actuales</h2>
        </div>
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-4">
                    <a href="?create" class="btn btn-info">
                        <i class="fas fa-plus"></i> Crear Usuario
                    </a>
                </div>
                <div class="col-md-4 text-center">
                    <form method="post" onsubmit="return confirm('¿Eliminar TODOS los usuarios vencidos no protegidos?');">
                        <button type="submit" name="delete_expired" class="btn btn-danger">
                            <i class="fas fa-trash"></i> Eliminar Vencidos
                        </button>
                    </form>
                </div>
                <div class="col-md-4 text-right">
                    <button id="deleteSelectedBtn" class="btn btn-danger" disabled>
                        <i class="fas fa-trash-alt"></i> Eliminar Seleccionados
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" placeholder="Buscar por MAC, usuario o nombre" id="search">
                    <div class="input-group-append">
                        <button class="btn btn-info" type="button" onclick="buscarUsuarios()">
                            <i class="fas fa-search"></i> Buscar
                        </button>
                        <button class="btn btn-secondary" type="button" onclick="limpiarBusqueda()">
                            <i class="fas fa-times"></i> Limpiar
                        </button>
                    </div>
                </div>

                <form id="massDeleteForm" method="post">
                    <table id="users" class="table table-striped table-sm">
                        <thead class="text-white">
                            <tr>
                                <th width="30">
                                    <input type="checkbox" id="selectAll">
                                </th>
                                <th>DNS</th>
                                <th>Cliente</th>
                                <th>MAC</th>
                                <th>Usuario</th>
                                <th>Expiración</th>
                                <th>Estado</th>
                                <th>Protección</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($res as $row): 
                                $today = date('Y-m-d');
                                $exp = $row['expiracion'];
                                $dias = floor((strtotime($exp) - strtotime($today)) / 86400);
                                
                                if ($dias > 3) {
                                    $estado = '<span class="badge badge-success">✅ Activo</span>';
                                } elseif ($dias >= 0) {
                                    $estado = '<span class="badge badge-warning">⏰ Por vencer ('.$dias.' días)</span>';
                                } else {
                                    $estado = '<span class="badge badge-danger">❌ Vencido</span>';
                                }
                            ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="selected_ids[]" value="<?= $row['id'] ?>" class="select-checkbox">
                                </td>
                                <td><?= htmlspecialchars($dnsMap[$row['dns_id']] ?? 'Desconocido') ?></td>
                                <td><?= htmlspecialchars($row['cliente_nombre']) ?></td>
                                <td><?= htmlspecialchars($row['mac_address']) ?></td>
                                <td><?= htmlspecialchars($row['username']) ?></td>
                                <td><?= date('d/m/Y', strtotime($row['expiracion'])) ?></td>
                                <td><?= $estado ?></td>
                                <td>
                                    <a href="?toggle_protect=<?= $row['id'] ?>" class="btn btn-sm <?= $row['is_protected'] ? 'btn-success' : 'btn-secondary' ?>">
                                        <i class="fas <?= $row['is_protected'] ? 'fa-lock' : 'fa-lock-open' ?>"></i>
                                        <?= $row['is_protected'] ? 'Protegida' : 'Libre' ?>
                                    </a>
                                </td>
                                <td>
                                    <a href="?update=<?= $row['id'] ?>" class="btn btn-warning btn-sm">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete=<?= $row['id'] ?>" class="btn btn-danger btn-sm">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                    
                                    <?php if ($dias <= 3 && $dias >= 0): ?>
                                        <a href="https://wa.me/<?= $row['cliente_whatsapp'] ?>?text=<?= urlencode(
                                            "¡Hola *{$row['cliente_nombre']}*! 👋\n\n" .
                                            "📢 *Recordatorio importante:*\n" .
                                            "Tu servicio está por vencer en *{$dias} día(s)*.\n" .
                                            "📅 *Fecha de vencimiento:* " . date('d/m/Y', strtotime($row['expiracion'])) . "\n\n" .
                                            "Por favor, realiza tu renovación para evitar interrupciones. ¡Gracias! 😊\n" .
                                            "¿Necesitas ayuda? Estamos aquí para asistirte. 📞"
                                        ) ?>" 
                                        target="_blank" class="btn btn-success btn-sm">
                                            <i class="fab fa-whatsapp"></i>
                                        </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <input type="hidden" name="delete_selected" value="1">
                </form>

                <!-- Modal de confirmación para eliminación múltiple -->
                <div class="modal fade" id="deleteSelectedModal" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header bg-danger text-white">
                                <h5 class="modal-title">Confirmar Eliminación</h5>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>
                            <div class="modal-body">
                                ¿Está seguro que desea eliminar los registros seleccionados?
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                                <button type="button" class="btn btn-danger" id="confirmDeleteSelected">Eliminar</button>
                            </div>
                        </div>
                    </div>
                </div>
<style>
/* Estilos para tablas con texto blanco */
.table {
    color: #fff !important; /* Texto blanco forzado */
}

.table td, 
.table th {
    border-color: #495057 !important; /* Bordes visibles */
}

/* Estilo para filas y hover */
.table tbody tr {
    background-color: rgba(0, 0, 0, 0.3) !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(0, 0, 0, 0.5) !important;
}

/* Estilos específicos para elementos internos */
.code-text {
    color: #fff !important;
    margin-right: 10px;
}

/* Botones dentro de la tabla */
.btn-outline-secondary {
    color: #fff !important;
    border-color: #6c757d !important;
}

.btn-outline-secondary:hover {
    background-color: #6c757d !important;
    color: #000 !important;
}
</style>
                <!-- Paginación -->
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <?php if ($current_page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $current_page - 1 ?>" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                        
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?= $i == $current_page ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $current_page + 1 ?>" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<script>
// Función para buscar usuarios
function buscarUsuarios() {
    var input, filter, table, tr, td, i, j, txtValue, found;
    input = document.getElementById("search");
    filter = input.value.toUpperCase();
    table = document.getElementById("users");
    tr = table.getElementsByTagName("tr");

    for (i = 1; i < tr.length; i++) {
        found = false;
        // Buscar en las columnas 2 (DNS), 3 (Cliente), 4 (MAC), 5 (Usuario)
        for (j = 2; j <= 5; j++) {
            td = tr[i].getElementsByTagName("td")[j];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                    break;
                }
            }
        }
        tr[i].style.display = found ? "" : "none";
    }
}

// Función para limpiar la búsqueda
function limpiarBusqueda() {
    document.getElementById("search").value = "";
    buscarUsuarios();
}

// Permitir búsqueda al presionar Enter
document.getElementById("search").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        buscarUsuarios();
    }
});

// Selección/deselección de todos los checkboxes
document.getElementById('selectAll').addEventListener('click', function(e) {
    var checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = e.target.checked;
    }
    updateDeleteButtonState();
});

// Actualizar estado del botón de eliminar seleccionados
function updateDeleteButtonState() {
    var checkboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
    document.getElementById('deleteSelectedBtn').disabled = checkboxes.length === 0;
}

// Evento para checkboxes individuales
document.addEventListener('change', function(e) {
    if (e.target && e.target.matches('tbody input[type="checkbox"]')) {
        updateDeleteButtonState();
        
        // Desmarcar "Seleccionar todos" si no todos están seleccionados
        var allCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]');
        var checkedCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
        document.getElementById('selectAll').checked = (allCheckboxes.length === checkedCheckboxes.length);
    }
});

// Manejar clic en el botón de eliminar seleccionados
document.getElementById('deleteSelectedBtn').addEventListener('click', function() {
    var checkboxes = document.querySelectorAll('tbody input[type="checkbox"]:checked');
    if (checkboxes.length > 0) {
        $('#deleteSelectedModal').modal('show');
    }
});

// Confirmar eliminación de seleccionados
document.getElementById('confirmDeleteSelected').addEventListener('click', function() {
    document.getElementById('massDeleteForm').submit();
});
</script>
<?php } ?>

<?php include ('includes/footer.php'); ?>