<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\DeviceSchedule;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    public function index()
    {
        $devices = Device::with(['schedule', 'logs' => fn($q) => $q->latest()->limit(1)])->get();
        return view('devices.index', compact('devices'));
    }

    public function create()
    {
        return view('devices.form', ['device' => new Device()]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'       => 'required|string|max:100',
            'ip_address' => 'required|ip',
            'port'       => 'required|integer|min:1|max:65535',
            'width_px'   => 'required|integer|min:1',
            'height_px'  => 'required|integer|min:1',
            'location'   => 'nullable|string|max:200',
            'latitude'   => 'nullable|numeric|between:-90,90',
            'longitude'  => 'nullable|numeric|between:-180,180',
            'highway'    => 'nullable|string|max:100',
            'chainage'   => 'nullable|string|max:20',
            'notes'      => 'nullable|string',
            'is_active'  => 'boolean',
        ]);
        $data['is_active'] = $request->boolean('is_active', true);

        $device = Device::create($data);
        DeviceSchedule::create(['device_id' => $device->id]);

        return redirect()->route('lis.devices.index')->with('success', "Device \"{$device->name}\" added.");
    }

    public function edit(Device $device)
    {
        return view('devices.form', compact('device'));
    }

    public function update(Request $request, Device $device)
    {
        $data = $request->validate([
            'name'       => 'required|string|max:100',
            'ip_address' => 'required|ip',
            'port'       => 'required|integer|min:1|max:65535',
            'width_px'   => 'required|integer|min:1',
            'height_px'  => 'required|integer|min:1',
            'location'   => 'nullable|string|max:200',
            'latitude'   => 'nullable|numeric|between:-90,90',
            'longitude'  => 'nullable|numeric|between:-180,180',
            'highway'    => 'nullable|string|max:100',
            'chainage'   => 'nullable|string|max:20',
            'notes'      => 'nullable|string',
            'is_active'  => 'boolean',
        ]);
        $data['is_active'] = $request->boolean('is_active', true);

        $device->update($data);
        return redirect()->route('lis.devices.index')->with('success', "Device \"{$device->name}\" updated.");
    }

    public function destroy(Device $device)
    {
        $name = $device->name;
        $device->delete();
        return redirect()->route('lis.devices.index')->with('success', "Device \"$name\" deleted.");
    }
}
