<?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__ . '/database.db';
$db = new PDO('sqlite:' . $dbFile);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// The POST request handling for 'add', 'edit', 'delete', 'toggle_status'
// is intentionally removed as the goal is a display-only page.
// If you still need these functionalities but not the IP/Uptime/Toggle on display,
// you would keep this POST block and modify the display part below.
// For a *truly* display-only page, removing the POST handling is appropriate.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // You can choose to throw an error, redirect, or simply do nothing
    // if POST requests are not expected on this "display-only" page.
    http_response_code(405); // Method Not Allowed
    echo json_encode(['status' => 'error', 'message' => '❌ Esta página é somente para visualização.']);
    exit;
}

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

$page_title = "📱 Visualização de Conexões"; // Changed title to reflect display-only nature

$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"></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>

';

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();
    });

    // Removed all JavaScript functions related to adding, editing, deleting,
    // and toggling status, as they are not needed for a display-only page.
    // This includes: openAddModal, editConnection, saveConnection, deleteConnection, toggleStatus
});
</script>