<?php

namespace App\Http\Controllers;

use App\Models\Device;

class MapController extends Controller
{
    public function index()
    {
        $devices = Device::all();
        $mapped  = Device::whereNotNull('latitude')->whereNotNull('longitude')->get();

        // Centre map on centroid of mapped devices, or default to Seafield area
        if ($mapped->isNotEmpty()) {
            $centreLat = $mapped->avg('latitude');
            $centreLng = $mapped->avg('longitude');
        } else {
            $centreLat = 3.0483;
            $centreLng = 101.5820;
        }

        return view('map.index', compact('devices', 'mapped', 'centreLat', 'centreLng'));
    }

    /** AJAX — return device list as JSON for live map refresh */
    public function devices()
    {
        $devices = Device::all()->map(fn($d) => [
            'id'             => $d->id,
            'name'           => $d->name,
            'ip_address'     => $d->ip_address,
            'port'           => $d->port,
            'location'       => $d->location,
            'chainage'       => $d->chainage,
            'highway'        => $d->highway,
            'latitude'       => $d->latitude,
            'longitude'      => $d->longitude,
            'last_status'    => $d->last_status,
            'last_sent_mode' => $d->last_sent_mode,
            'last_sent_at'   => $d->last_sent_at?->toISOString(),
            'is_active'      => $d->is_active,
        ]);

        return response()->json($devices);
    }
}
