<?php 
include ('includes/header.php');
$db = new SQLite3("a/.logs.db");
$res = $db->query("SELECT * FROM logs ORDER by id DESC");

if(isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $db->exec("DELETE FROM logs WHERE id = '$id'");
}

// Adição da exclusão em massa
if(isset($_GET['delete_selected'])) {
    $ids_to_delete = isset($_GET['delete_check']) ? $_GET['delete_check'] : [];
    foreach ($ids_to_delete as $id) {
        $db->exec("DELETE FROM logs WHERE id = '$id'");
    }
    // Redirecionamento após a exclusão usando JavaScript
    echo '<script>window.location.replace("snoop.php");</script>';
    exit();
}

?>
<div class="card border-left-primary card mb-4">
    <center>
        <h1 class="colorboard"></i> LOGS</h1>
    </center>
    <br>
    <div class="table-responsive" style="padding: 10px;">
        <form method="get">
            <div class="form-group">
                <button type="submit" class="btn btn-danger" name="delete_selected">Excluir Selecionados</button>
            </div>
            <table class="table table-striped table-sm">
                <thead style="color:white!important">
                    <tr>
                        <th><input type="checkbox" id="selecionarTodos"></th>
                        <th>ID</th>
                        <th>Data</th>
                        <th>IP Address</th>
                        <th>Deletar</th>
                    </tr>
                </thead>
                <?php while ($row = $res->fetchArray()) {?>
                <tbody>
                    <tr>
                        <td><input type="checkbox" class="checkbox" name="delete_check[]" value="<?php echo $row['id']; ?>"></td>
                        <td><?=$row['id'] ?></td>
                        <td><?=$row['date'] ?></td>
                        <td><?=$row['ipaddress'] ?></td>
                        <td>
                            <a class="" href="snoop.php?delete=<?php echo $row['id']; ?>"><i style="color: red; cursor: pointer; display: flex; justify-content: center; padding: 7px;" class="fa fa-trash"></i></a>
                        </td>
                    </tr>
                </tbody>
                <?php }?>
            </table>
        </form>
    </div>
</div>

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

<script>
    document.getElementById('selecionarTodos').addEventListener('change', function() {
        var checkboxes = document.getElementsByClassName('checkbox');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].checked = this.checked;
        }
    });
</script>

</body>
</html>
