<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$dbFile = __DIR__ . '/api/database.db';
$db = new PDO('sqlite:' . $dbFile);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Adicionando tratamento para limpar o banco de dados se for uma requisição POST com ação 'clear'
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'clear') {
    try {
        $db->exec("DELETE FROM user_connections");
        echo json_encode(['status' => 'success', 'message' => '✅ Todas as conexões foram removidas com sucesso!']);
        exit;
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => '❌ Erro ao limpar o banco de dados: ' . $e->getMessage()]);
        exit;
    }
}

$connections = $db->query("SELECT * FROM user_connections ORDER BY last_connection DESC")->fetchAll(PDO::FETCH_ASSOC);

$page_title = "📱 Visualização de Conexões";

$page_content = '
<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_connections" class="form-control form-control-solid w-250px ps-12" placeholder="🔍 Pesquisar Dispositivos" />
            </div>
        </div>
        <div class="card-toolbar">
            <button id="clear_all" class="btn btn-sm btn-light-danger" data-bs-toggle="modal" data-bs-target="#confirmClearModal">
                <i class="ki-outline ki-trash fs-2 me-2"></i> Limpar Tudo
            </button>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="connections_table">
            <thead>
                <tr class="text-start text-gray-500 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-100px">🆔 ID</th>
                    <th class="min-w-150px">📱 Dispositivo</th>
                    <th class="min-w-100px">🔌 Status</th>
                    <th class="min-w-100px">🖥️ Modelo</th>
                    <th class="min-w-100px">🕒 Última Conexão</th>
                    <th class="min-w-100px">📅 Primeira Visita</th>
                </tr>
            </thead>
            <tbody id="connections_table_body" class="fw-semibold text-gray-600">
';

foreach ($connections as $conn) {
    $statusClass = $conn['is_online'] ? 'badge-light-success' : 'badge-light-warning';
    $statusText = $conn['is_online'] ? '✅ Online' : '⏸️ Offline';
    $lastConnection = date('d/m/Y H:i', strtotime($conn['last_connection']));
    $firstSeen = date('d/m/Y', strtotime($conn['first_seen']));
    
    $page_content .= "<tr data-id='{$conn['id']}'>
        <td>{$conn['id']}</td>
        <td>{$conn['device_id']}</td>
        <td>
            <span class='badge {$statusClass}'>{$statusText}</span>
        </td>
        <td>{$conn['device_model']}</td>
        <td>{$lastConnection}</td>
        <td>{$firstSeen}</td>
        </tr>";
}

$page_content .= '
            </tbody>
        </table>
    </div>
</div>

<!-- Modal de Confirmação -->
<div class="modal fade" id="confirmClearModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="fw-bold">Confirmar Limpeza</h2>
                <div class="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal" aria-label="Close">
                    <i class="ki-outline ki-cross fs-1"></i>
                </div>
            </div>
            <div class="modal-body">
                <p>Tem certeza que deseja limpar TODOS os registros de conexões?</p>
                <p class="text-danger">⚠️ Esta ação não pode ser desfeita!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" id="confirmClearBtn" class="btn btn-danger">Limpar Tudo</button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let connectionsTable = $('#connections_table').DataTable({
        searching: true,
        paging: true,
        ordering: true,
        info: true,
        responsive: true,
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/pt-BR.json'
        }
    });

    document.getElementById("search_connections").addEventListener("input", function() {
        connectionsTable.search(this.value).draw();
    });

    // Limpar banco de dados
    document.getElementById("confirmClearBtn").addEventListener("click", function() {
        fetch(window.location.href, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=clear'
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                toastr.success(data.message);
                setTimeout(() => window.location.reload(), 1500);
            } else {
                toastr.error(data.message);
            }
            $('#confirmClearModal').modal('hide');
        })
        .catch(error => {
            toastr.error('Erro na requisição');
            console.error('Error:', error);
            $('#confirmClearModal').modal('hide');
        });
    });
});
</script>