<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Services\PingService;

class HealthController extends Controller
{
    public function index()
    {
        $devices = Device::all();
        $results = [];

        foreach ($devices as $device) {
            $r = PingService::ping($device);
            $device->update([
                'last_status'  => $r['online'] ? 'online' : 'offline',
                'last_seen_at' => $r['online'] ? now() : $device->last_seen_at,
            ]);
            $results[] = ['device' => $device, ...$r];
        }

        $online  = collect($results)->where('online', true)->count();
        $offline = collect($results)->where('online', false)->count();

        return view('health.index', compact('results', 'online', 'offline'));
    }

    /** AJAX single-device ping */
    public function ping(Device $device)
    {
        $r = PingService::ping($device);
        $device->update([
            'last_status'  => $r['online'] ? 'online' : 'offline',
            'last_seen_at' => $r['online'] ? now() : $device->last_seen_at,
        ]);
        return response()->json($r);
    }
}
