<?php

namespace App\Http\Controllers;

use App\Models\InventoryItem;
use App\Models\ScanActivity;
use App\Support\AdminRealtimeNotifier;
use Illuminate\Support\Carbon;

class ReplacementController extends Controller
{
    public function index()
    {
        $items = InventoryItem::with(['category', 'room'])
            ->where(function ($query) {
                $query->where('status_barang', 'replace')
                    ->orWhere('pengajuan_penggantian', true)
                    ->orWhere('status_barang', 'broken');
            })
            ->latest()
            ->get();

        return view('replacements.index', compact('items'));
    }

    public function request(InventoryItem $item)
    {
        $item->update([
            'status_barang' => 'replace',
            'pengajuan_penggantian' => true,
        ]);

        ScanActivity::create([
            'id_ruangan' => $item->id_ruangan,
            'id_barang' => $item->id,
            'nama_petugas' => 'Petugas Mobile',
            'aktivitas' => 'replacement_request',
            'deskripsi' => $item->nama_barang . ' diajukan untuk penggantian',
            'dipindai_pada' => Carbon::now(),
        ]);

        AdminRealtimeNotifier::replacementRequest($item);

        return back()->with('success', 'Pengajuan penggantian berhasil dibuat.');
    }

    public function complete(InventoryItem $item)
    {
        $item->update([
            'status_barang' => 'good',
            'pengajuan_penggantian' => false,
            'tahun_perolehan' => (int) date('Y'),
            'tanggal_jadwal_pemeliharaan' => Carbon::now()->addMonths(6)->toDateString(),
            'catatan' => trim(($item->catatan ? $item->catatan . "\n" : '') . 'Penggantian diproses pada ' . now()->format('d/m/Y H:i')),
        ]);

        ScanActivity::create([
            'id_ruangan' => $item->id_ruangan,
            'id_barang' => $item->id,
            'nama_petugas' => 'Admin',
            'aktivitas' => 'replacement_completed',
            'deskripsi' => $item->nama_barang . ' selesai proses penggantian',
            'dipindai_pada' => Carbon::now(),
        ]);

        return redirect()->route('replacements.index')->with('success', 'Penggantian barang selesai diproses.');
    }
}
