<?php 
include ('includes/header.php');

// Tabela de rastreamento
$table_name = 'mac_tracking';
$page = 'mac_tracking.php';

// Criar tabela se não existir
$createTableSQL = "CREATE TABLE IF NOT EXISTS mac_tracking (
    id INTEGER PRIMARY KEY,
    mac_address TEXT NOT NULL UNIQUE,
    device_name TEXT,
    app_version TEXT,
    last_access TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    access_count INTEGER DEFAULT 1,
    first_access TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    ip_address TEXT,
    status TEXT DEFAULT 'active'
)";

try {
    $db->db->exec($createTableSQL);
} catch (Exception $e) {
    // Tabela já existe
}

// Buscar todos os registros
$res = $db->select($table_name, '*', '', 'last_access DESC');

// Deletar registro
if(isset($_GET['delete'])){
    $db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
    echo "<script>window.location.href='".$page."?status=deleted'</script>";
}

// Limpar histórico de acesso
if(isset($_POST['clear_history'])){
    $db->db->exec("DELETE FROM mac_tracking");
    echo "<script>window.location.href='".$page."?status=cleared'</script>";
}

// Exportar dados
if(isset($_GET['export'])){
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="mac_tracking_' . date('Y-m-d_H-i-s') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM
    
    fputcsv($output, ['ID', 'Endereço MAC', 'Nome do Dispositivo', 'Versão do App', 'Último Acesso', 'Total de Acessos', 'Primeiro Acesso', 'IP', 'Status']);
    
    foreach ($res as $row) {
        fputcsv($output, [
            $row['id'],
            $row['mac_address'],
            $row['device_name'],
            $row['app_version'],
            $row['last_access'],
            $row['access_count'],
            $row['first_access'],
            $row['ip_address'],
            $row['status']
        ]);
    }
    fclose($output);
    exit;
}

?>

<!-- Status Messages -->
<?php if(isset($_GET['status'])): ?>
    <div class="container-fluid pt-4 px-4">
        <div class="row g-4">
            <div class="col-12">
                <?php if($_GET['status'] == 'deleted'): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Sucesso!</strong> Dispositivo Mac removido do rastreamento.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php elseif($_GET['status'] == 'cleared'): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Sucesso!</strong> Histórico de acesso limpo com sucesso.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Tracking Table Start -->
<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <div class="col-12">
            <div class="bg-secondary rounded h-100 p-4">
                <h2 class="mb-4">📱 Rastreamento de Clientes Mac</h2>
                <h6 class="mb-4 text-info">🔍 Monitore todos os Macs que acessaram a API do gerenciador</h6>
                
                <div class="text-end mb-3">
                    <a href="<?php echo $page; ?>?export" class="btn btn-info m-2">
                        <i class="fa fa-download"></i> Exportar CSV
                    </a>
                    <form method="post" style="display:inline;">
                        <button type="submit" name="clear_history" class="btn btn-warning m-2" onclick="return confirm('Tem certeza que deseja limpar todo o histórico?')">
                            <i class="fa fa-trash"></i> Limpar Histórico
                        </button>
                    </form>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>#</th>
                                <th>Endereço MAC</th>
                                <th>Nome do Dispositivo</th>
                                <th>Versão App</th>
                                <th>Último Acesso</th>
                                <th>Total Acessos</th>
                                <th>Primeiro Acesso</th>
                                <th>IP</th>
                                <th>Status</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if(empty($res)): 
                            ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted">Nenhum dispositivo Mac registrado ainda</td>
                                </tr>
                            <?php 
                            else:
                                foreach ($res as $row): 
                            ?>
                                <tr>
                                    <td><?=$row['id']; ?></td>
                                    <td><code><?=$row['mac_address']; ?></code></td>
                                    <td><?=$row['device_name'] ?? 'N/A'; ?></td>
                                    <td><?=$row['app_version'] ?? 'N/A'; ?></td>
                                    <td><?=date('d/m/Y H:i:s', strtotime($row['last_access'])); ?></td>
                                    <td><span class="badge bg-primary"><?=$row['access_count']; ?></span></td>
                                    <td><?=date('d/m/Y H:i:s', strtotime($row['first_access'])); ?></td>
                                    <td><?=$row['ip_address']; ?></td>
                                    <td>
                                        <?php if($row['status'] == 'active'): ?>
                                            <span class="badge bg-success">Ativo</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Inativo</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a class="btn btn-square btn-sm btn-danger" href="<?php echo $page; ?>?delete=<?php echo $row['id']; ?>" 
                                           onclick="return confirm('Tem certeza que deseja remover este dispositivo?')">
                                            <i class="fa fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php 
                                endforeach;
                            endif;
                            ?>
                        </tbody>
                    </table>
                </div>

                <!-- Statistics -->
                <div class="row mt-4">
                    <div class="col-md-3">
                        <div class="bg-dark rounded p-3">
                            <h6 class="text-muted mb-2">Total de Dispositivos</h6>
                            <h3 class="text-primary"><?=count($res); ?></h3>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="bg-dark rounded p-3">
                            <h6 class="text-muted mb-2">Total de Acessos</h6>
                            <h3 class="text-success">
                                <?php 
                                $total_accesses = array_sum(array_column($res, 'access_count'));
                                echo $total_accesses;
                                ?>
                            </h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Tracking Table End -->

<!-- Footer Start -->
<?php include ('includes/footer.php');?>
<!-- Footer End -->
</body>
</html>
