@extends('layouts.app')
@section('title', 'Dashboard')

@section('content')
{{-- Stats row --}}
<div class="row g-3 mb-4">
    <div class="col-sm-6 col-xl-3">
        <div class="stat-card" style="background:#1e3a5f">
            <div class="label text-info">Total Devices</div>
            <div class="value text-info mt-1">{{ $totalDevices }}</div>
            <div class="mt-2" style="font-size:.8rem;color:#7dd3fc">
                <i class="bi bi-circle-fill text-success me-1" style="font-size:.5rem"></i>{{ $onlineCount }} online
                <i class="bi bi-circle-fill text-danger ms-2 me-1" style="font-size:.5rem"></i>{{ $offlineCount }} offline
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="stat-card" style="background:#14532d">
            <div class="label text-success">Successful Today</div>
            <div class="value text-success mt-1">{{ $successToday }}</div>
            <div class="mt-2" style="font-size:.8rem;color:#86efac">sends completed</div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="stat-card" style="background:#7f1d1d">
            <div class="label text-danger">Failed Today</div>
            <div class="value text-danger mt-1">{{ $failedToday }}</div>
            <div class="mt-2" style="font-size:.8rem;color:#fca5a5">errors logged</div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="stat-card" style="background:#1a1a2e">
            <div class="label" style="color:#a78bfa">Quick Actions</div>
            <div class="mt-2 d-flex gap-2 flex-wrap">
                <button class="btn btn-success btn-sm quick-all" data-mode="buka">
                    <i class="bi bi-circle-fill me-1"></i>BUKA All
                </button>
                <button class="btn btn-danger btn-sm quick-all" data-mode="tutup">
                    <i class="bi bi-circle-fill me-1"></i>TUTUP All
                </button>
            </div>
            <div id="quick-result" class="mt-2" style="font-size:.75rem"></div>
        </div>
    </div>
</div>

<div class="row g-3">
    {{-- Device status grid --}}
    <div class="col-xl-5">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span class="fw-semibold"><i class="bi bi-hdd-network me-2"></i>Devices</span>
                <a href="{{ route('lis.devices.create') }}" class="btn btn-primary btn-sm">
                    <i class="bi bi-plus"></i> Add
                </a>
            </div>
            <div class="card-body p-0">
                @forelse($devices as $device)
                <div class="d-flex align-items-center px-4 py-3 border-bottom border-secondary border-opacity-25">
                    <div class="me-3">
                        <i class="bi bi-circle-fill {{ $device->last_status === 'online' ? 'text-success' : ($device->last_status === 'offline' ? 'text-danger' : 'text-secondary') }}"
                           style="font-size:.55rem"></i>
                    </div>
                    <div class="flex-grow-1">
                        <div class="fw-semibold" style="font-size:.9rem">{{ $device->name }}</div>
                        <div class="text-secondary" style="font-size:.75rem">{{ $device->ip_address }}:{{ $device->port }}</div>
                    </div>
                    <div class="text-end">
                        @if($device->last_sent_mode)
                            <span class="badge badge-{{ $device->last_sent_mode }}">{{ strtoupper($device->last_sent_mode) }}</span>
                        @else
                            <span class="badge bg-secondary">—</span>
                        @endif
                        <div class="text-secondary mt-1" style="font-size:.7rem">
                            {{ $device->last_sent_at?->diffForHumans() ?? 'Never sent' }}
                        </div>
                    </div>
                </div>
                @empty
                <div class="text-center text-secondary py-5">
                    <i class="bi bi-hdd-network display-6 d-block mb-2 opacity-25"></i>
                    No devices configured.
                    <a href="{{ route('lis.devices.create') }}" class="d-block mt-2">Add your first device →</a>
                </div>
                @endforelse
            </div>
        </div>
    </div>

    {{-- Recent activity --}}
    <div class="col-xl-7">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span class="fw-semibold"><i class="bi bi-clock-history me-2"></i>Recent Activity</span>
                <a href="{{ route('lis.log.index') }}" class="btn btn-sm btn-outline-secondary">View All</a>
            </div>
            <div class="card-body p-0">
                @forelse($recentLogs as $log)
                <div class="d-flex align-items-center px-4 py-2 border-bottom border-secondary border-opacity-25">
                    <div class="me-3">
                        <i class="bi bi-{{ $log->success ? 'check-circle-fill text-success' : 'x-circle-fill text-danger' }}" style="font-size:1.1rem"></i>
                    </div>
                    <div class="flex-grow-1">
                        <div style="font-size:.875rem">
                            <span class="fw-semibold">{{ $log->device?->name ?? '—' }}</span>
                            <span class="badge ms-2 badge-{{ $log->mode }}">{{ strtoupper($log->mode) }}</span>
                            <span class="badge bg-secondary ms-1" style="font-size:.65rem">{{ $log->triggered_by }}</span>
                        </div>
                        @if(!$log->success)
                            <div class="text-danger" style="font-size:.75rem">{{ Str::limit($log->message, 80) }}</div>
                        @endif
                    </div>
                    <div class="text-end text-secondary" style="font-size:.75rem; white-space:nowrap">
                        {{ $log->duration_ms }} ms<br>
                        {{ $log->created_at->diffForHumans() }}
                    </div>
                </div>
                @empty
                <div class="text-center text-secondary py-5">
                    <i class="bi bi-journal-text display-6 d-block mb-2 opacity-25"></i>
                    No activity yet.
                </div>
                @endforelse
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.querySelectorAll('.quick-all').forEach(btn => {
    btn.addEventListener('click', async () => {
        const mode = btn.dataset.mode;
        const label = mode.toUpperCase();
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Sending…';
        const res  = document.getElementById('quick-result');
        res.innerHTML = '';
        try {
            const r = await fetch('{{ route("lis.send.send") }}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                body: JSON.stringify({ mode, device_id: 'all' })
            });
            const data = await r.json();
            if (data.results) {
                res.innerHTML = data.results.map(d =>
                    `<span class="${d.success ? 'text-success' : 'text-danger'}">${d.success ? '✓' : '✗'} ${d.device}</span>`
                ).join(' · ');
            }
        } catch(e) { res.innerHTML = `<span class="text-danger">${e.message}</span>`; }
        btn.disabled = false;
        btn.innerHTML = `<i class="bi bi-circle-fill me-1"></i>${label} All`;
    });
});
</script>
@endpush
