<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Device;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DevicesController extends Controller
{
    public function index(Request $request): View
    {
        $devices = Device::with('user:id,name,email')
            ->when($request->q, fn($q) => $q->where(fn($sub) =>
                $sub->where('device_id', 'like', "%{$request->q}%")
                    ->orWhere('model', 'like', "%{$request->q}%")
                    ->orWhereHas('user', fn($u) => $u->where('email', 'like', "%{$request->q}%"))
            ))
            ->when($request->platform, fn($q) => $q->where('platform', $request->platform))
            ->orderByDesc('last_sync_at')
            ->paginate(25)
            ->withQueryString();

        return view('admin.devices.index', compact('devices'));
    }

    public function revoke(Device $device): RedirectResponse
    {
        $device->update(['is_revoked' => true]);
        $user = $device->user;
        if ($user) {
            $user->tokens()->where('name', 'device:' . $device->device_id)->delete();
        }
        return back()->with('success', 'Device revoked.');
    }
}
