<?php
// Configuração do banco de dados
$db = new SQLite3('./api/.db.db');
$table_name = "device_tests";

// Nome do arquivo atual
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Criar tabela se não existir
$db->exec("CREATE TABLE IF NOT EXISTS {$table_name}(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    device_id TEXT UNIQUE, 
    timestamp INTEGER
)");

// Processar operações
if (isset($_GET['delete'])) {
    // Excluir registro
    $stmt = $db->prepare("DELETE FROM {$table_name} WHERE id = :id");
    $stmt->bindValue(':id', $_GET['delete'], SQLITE3_INTEGER);
    $stmt->execute();
    header("Location: {$base_file}?status=deleted");
    exit;
}

if (isset($_POST['submit'])) {
    // Adicionar novo registro
    $stmt = $db->prepare("INSERT INTO {$table_name}(device_id, timestamp) VALUES(:device_id, :timestamp)");
    $stmt->bindValue(':device_id', $_POST['device_id'], SQLITE3_TEXT);
    $stmt->bindValue(':timestamp', time(), SQLITE3_INTEGER);
    $stmt->execute();
    header("Location: {$base_file}?status=added");
    exit;
}

// Buscar todos os registros
$res = $db->query("SELECT * FROM {$table_name} ORDER BY timestamp DESC");

include ('includes/studiolivheaderecode.php');
?>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirmar</h2>
            </div>
            <div class="modal-body">
                Tem certeza que deseja excluir este registro?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<div class="col-md-12 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-commenting"></i> Registros de Teste</h2>
                </center>
            </div>

            <div class="card-body">
                <div class="col-12">
                    <center>
                        <button type="button" class="btn btn-info" data-toggle="modal" data-target="#addModal">
                            Novo Registro
                        </button>
                    </center>
                </div>
                <br>
                
                <?php if (isset($_GET['status'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php
                    if ($_GET['status'] == 'deleted') echo "Registro excluído com sucesso!";
                    if ($_GET['status'] == 'added') echo "Registro adicionado com sucesso!";
                    ?>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <?php endif; ?>
                
                <div class="table-responsive">
                    <table class="table table-striped table-sm">
                        <thead style="color:white!important">
                            <tr>
                                <th>ID</th>
                                <th>Device ID</th>
                                <th>Data/Hora</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $res->fetchArray()): ?>
                            <tr>
                                <td><?= $row['id'] ?></td>
                                <td><?= $row['device_id'] ?></td>
                                <td><?= date('d/m/Y H:i:s', $row['timestamp']) ?></td>
                                <td>
                                    <a class="btn btn-danger btn-sm" href="#" 
                                       data-href="./<?= $base_file ?>?delete=<?= $row['id'] ?>" 
                                       data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fa fa-trash-o"></i> Excluir
                                    </a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal para adicionar registro -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addModalLabel">Adicionar Registro de Teste</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="device_id">Device ID</label>
                        <input type="text" class="form-control" id="device_id" name="device_id" required 
                               placeholder="Ex: 96b534e2024b14e0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" name="submit" class="btn btn-primary">Adicionar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Script para o modal de confirmação de exclusão
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
</script>

<?php include ('includes/studifooterolivecode.php'); ?>
</body>
</html>