@extends('layouts.app')
@section('title', 'Health Check')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="mb-0 fw-bold">Device Health</h5>
    <div class="d-flex align-items-center gap-3">
        <div>
            <span class="badge bg-success" id="cnt-online">{{ $online }} Online</span>
            <span class="badge bg-danger ms-1" id="cnt-offline">{{ $offline }} Offline</span>
            <span class="badge bg-secondary ms-1" id="cnt-unknown">{{ collect($results)->where('device.last_status', null)->count() }} Unknown</span>
        </div>
        <button class="btn btn-primary btn-sm" id="pingAllBtn" onclick="pingAll()">
            <i class="bi bi-broadcast me-1"></i>Ping All
        </button>
    </div>
</div>

<div class="row g-3 mb-4" id="device-cards">
    @foreach($results as $r)
    @php $device = $r['device']; $statusClass = $device->last_status === 'online' ? 'success' : ($device->last_status === 'offline' ? 'danger' : 'secondary'); @endphp
    <div class="col-md-6 col-xl-4" id="wrap-{{ $device->id }}">
        <div class="card h-100">
            <div class="card-body">
                <div class="d-flex align-items-start justify-content-between mb-3">
                    <div>
                        <div class="fw-semibold">{{ $device->name }}</div>
                        <code style="font-size:.8rem;color:#7dd3fc">{{ $device->ip_address }}:{{ $device->port }}</code>
                        @if($device->location)
                        <div class="text-secondary" style="font-size:.75rem">{{ $device->location }}</div>
                        @endif
                    </div>
                    <span class="badge bg-{{ $statusClass }}" id="badge-{{ $device->id }}">
                        <i class="bi bi-circle-fill me-1" style="font-size:.5rem"></i>
                        <span id="status-text-{{ $device->id }}">{{ strtoupper($device->last_status ?? 'UNKNOWN') }}</span>
                    </span>
                </div>

                <div class="row g-2 text-center mb-2">
                    <div class="col-6">
                        <div style="background:#0d1117;border-radius:6px;padding:10px">
                            <div class="text-secondary" style="font-size:.7rem">Latency</div>
                            <div class="fw-bold mt-1" id="latency-{{ $device->id }}"
                                 style="color:{{ $device->last_status === 'online' ? '#4ade80' : '#64748b' }}">
                                —
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div style="background:#0d1117;border-radius:6px;padding:10px">
                            <div class="text-secondary" style="font-size:.7rem">Last Mode</div>
                            <div class="fw-bold mt-1">
                                @if($device->last_sent_mode)
                                    <span class="badge badge-{{ $device->last_sent_mode }}">{{ strtoupper($device->last_sent_mode) }}</span>
                                @else
                                    <span class="text-secondary">—</span>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>

                <div class="text-secondary mb-1" id="msg-{{ $device->id }}" style="font-size:.75rem">
                    <i class="bi bi-info-circle me-1"></i>{{ $r['message'] }}
                </div>
                @if($device->last_seen_at)
                <div class="text-secondary mb-2" style="font-size:.72rem" id="seen-{{ $device->id }}">
                    Last seen: {{ $device->last_seen_at->diffForHumans() }}
                </div>
                @endif

                <div class="d-flex gap-2 mt-2">
                    <button class="btn btn-outline-secondary btn-sm ping-btn" id="ping-btn-{{ $device->id }}"
                            data-id="{{ $device->id }}" onclick="pingDevice({{ $device->id }})">
                        <i class="bi bi-broadcast me-1"></i>Ping
                    </button>
                    <a href="{{ route('lis.send.index') }}" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-send me-1"></i>Send
                    </a>
                </div>
            </div>
        </div>
    </div>
    @endforeach
</div>

{{-- Summary table --}}
<div class="card">
    <div class="card-header fw-semibold"><i class="bi bi-table me-2"></i>Summary</div>
    <div class="card-body p-0">
        <table class="table mb-0">
            <thead>
                <tr><th>Device</th><th>IP</th><th>Status</th><th>Latency</th><th>Message</th><th>Last Seen</th><th>Last Sent</th></tr>
            </thead>
            <tbody id="summary-tbody">
            @foreach($results as $r)
            @php $d = $r['device']; @endphp
            <tr id="row-{{ $d->id }}">
                <td class="fw-semibold">{{ $d->name }}</td>
                <td><code style="color:#7dd3fc">{{ $d->ip_address }}</code></td>
                <td>
                    <span class="badge bg-{{ $d->last_status === 'online' ? 'success' : ($d->last_status === 'offline' ? 'danger' : 'secondary') }}"
                          id="row-badge-{{ $d->id }}">
                        {{ strtoupper($d->last_status ?? 'UNKNOWN') }}
                    </span>
                </td>
                <td id="row-latency-{{ $d->id }}">—</td>
                <td style="font-size:.8rem" id="row-msg-{{ $d->id }}">{{ $r['message'] }}</td>
                <td style="font-size:.8rem">{{ $d->last_seen_at?->diffForHumans() ?? '—' }}</td>
                <td>
                    @if($d->last_sent_mode)
                        <span class="badge badge-{{ $d->last_sent_mode }}">{{ strtoupper($d->last_sent_mode) }}</span>
                        <span class="text-secondary ms-1" style="font-size:.75rem">{{ $d->last_sent_at?->format('d/m H:i') }}</span>
                    @else
                        <span class="text-secondary">—</span>
                    @endif
                </td>
            </tr>
            @endforeach
            </tbody>
        </table>
    </div>
</div>
@endsection

@push('scripts')
<script>
const CSRF = document.querySelector('meta[name=csrf-token]').content;
const deviceIds = @json(collect($results)->pluck('device.id')->values());

async function pingDevice(id) {
    const btn = document.getElementById('ping-btn-' + id);
    const origHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Pinging…';

    try {
        const res  = await fetch(`/lis-portal/health/${id}/ping`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
        });
        const data = await res.json();
        applyResult(id, data);
    } catch(e) {
        updateBadge(id, false);
        document.getElementById('msg-' + id).textContent = 'Request failed: ' + e.message;
    }

    setTimeout(() => { btn.disabled = false; btn.innerHTML = origHtml; }, 3000);
}

async function pingAll() {
    const btn = document.getElementById('pingAllBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Pinging…';

    let online = 0, offline = 0;
    for (const id of deviceIds) {
        try {
            const res  = await fetch(`/lis-portal/health/${id}/ping`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
            });
            const data = await res.json();
            applyResult(id, data);
            data.online ? online++ : offline++;
        } catch(e) { offline++; }
    }

    document.getElementById('cnt-online').textContent  = online  + ' Online';
    document.getElementById('cnt-offline').textContent = offline + ' Offline';

    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-broadcast me-1"></i>Ping All';
}

function applyResult(id, data) {
    updateBadge(id, data.online);

    const latency = data.latency_ms !== null ? data.latency_ms + ' ms' : '—';
    const latEl   = document.getElementById('latency-' + id);
    if (latEl) {
        latEl.textContent = latency;
        latEl.style.color = data.online ? '#4ade80' : '#f87171';
    }

    const msgEl = document.getElementById('msg-' + id);
    if (msgEl) msgEl.textContent = data.message;

    // Update table row
    const rowBadge   = document.getElementById('row-badge-' + id);
    const rowLatency = document.getElementById('row-latency-' + id);
    const rowMsg     = document.getElementById('row-msg-' + id);

    if (rowBadge) {
        rowBadge.className = 'badge bg-' + (data.online ? 'success' : 'danger');
        rowBadge.textContent = data.online ? 'ONLINE' : 'OFFLINE';
    }
    if (rowLatency) rowLatency.textContent = latency;
    if (rowMsg)     rowMsg.textContent     = data.message;
}

function updateBadge(id, online) {
    const badge    = document.getElementById('badge-' + id);
    const textEl   = document.getElementById('status-text-' + id);
    if (badge)  badge.className = 'badge bg-' + (online ? 'success' : 'danger');
    if (textEl) textEl.textContent = online ? 'ONLINE' : 'OFFLINE';
}
</script>
@endpush
