<?php

namespace App\Http\Controllers;

use App\Models\InventoryItem;
use App\Models\Room;
use App\Models\ScanActivity;
use App\Support\AdminRealtimeNotifier;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class ScanController extends Controller
{
    public function room(Request $request, string $qrCode)
    {
        $room = Room::where('kode_qr', $qrCode)->firstOrFail();
        $officer = $request->input('officer', 'Petugas Mobile');

        ScanActivity::create([
            'id_ruangan' => $room->id,
            'nama_petugas' => $officer,
            'aktivitas' => 'room_scan',
            'deskripsi' => $room->nama_ruangan . ' dipindai melalui QR ruangan',
            'dipindai_pada' => Carbon::now(),
        ]);

        AdminRealtimeNotifier::scanRoomByOfficer($room, $officer);

        return redirect()->route('dashboard')->with('success', 'Scan QR ruangan ' . $room->nama_ruangan . ' berhasil dicatat.');
    }

    public function item(Request $request, string $assetCode)
    {
        $item = InventoryItem::with(['category', 'room'])
            ->where('kode_aset', $assetCode)
            ->firstOrFail();
        $officer = $request->input('officer', 'Petugas Mobile');

        ScanActivity::create([
            'id_ruangan' => $item->id_ruangan,
            'id_barang' => $item->id,
            'nama_petugas' => $officer,
            'aktivitas' => 'scan',
            'deskripsi' => $item->nama_barang . ' dipindai melalui QR barang',
            'dipindai_pada' => Carbon::now(),
        ]);

        AdminRealtimeNotifier::itemScan($item, $officer);

        return view('scan.item', compact('item'));
    }
}