<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreFacilityObjectRequest;
use App\Models\FacilityObject;
use App\Models\Location;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class FacilityObjectController extends Controller
{
    public function index(Request $request): View
    {
        $facilities = FacilityObject::query()
            ->with('location')
            ->when($request->string('search')->value(), fn ($query, $search) => $query->where('name', 'like', "%{$search}%"))
            ->when($request->integer('location_id'), fn ($query, $locationId) => $query->where('location_id', $locationId))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('facilities.index', [
            'facilities' => $facilities,
            'locations' => Location::query()->orderBy('name')->get(),
        ]);
    }

    public function create(): View
    {
        return view('facilities.form', [
            'facility' => new FacilityObject(['current_condition' => 'good', 'is_active' => true]),
            'locations' => Location::query()->orderBy('name')->get(),
            'action' => route('facilities.store'),
            'method' => 'POST',
        ]);
    }

    public function store(StoreFacilityObjectRequest $request): RedirectResponse
    {
        $facility = new FacilityObject();
        $this->persist($facility, $request->validated());

        return redirect()->route('facilities.index')->with('status', 'Objek fasilitas berhasil ditambahkan.');
    }

    public function edit(FacilityObject $facility): View
    {
        return view('facilities.form', [
            'facility' => $facility,
            'locations' => Location::query()->orderBy('name')->get(),
            'action' => route('facilities.update', $facility),
            'method' => 'PUT',
        ]);
    }

    public function update(StoreFacilityObjectRequest $request, FacilityObject $facility): RedirectResponse
    {
        $this->persist($facility, $request->validated());

        return redirect()->route('facilities.index')->with('status', 'Objek fasilitas berhasil diperbarui.');
    }

    public function show(FacilityObject $facility): View
    {
        return view('facilities.show', [
            'facility' => $facility->load('location'),
            'logs' => $facility->maintenanceLogs()->with('submitter')->latest('performed_at')->get(),
        ]);
    }

    public function destroy(FacilityObject $facility): RedirectResponse
    {
        $facility->delete();

        return redirect()->route('facilities.index')->with('status', 'Objek fasilitas berhasil dihapus.');
    }

    protected function persist(FacilityObject $facility, array $validated): void
    {
        $facility->fill([
            'location_id' => $validated['location_id'],
            'name' => $validated['name'],
            'slug' => Str::slug($validated['name']),
            'current_condition' => $validated['current_condition'],
            'notes' => $validated['notes'] ?? null,
            'last_checked_at' => $validated['last_checked_at'] ?? null,
            'is_active' => (bool) ($validated['is_active'] ?? true),
            'qr_token' => $facility->qr_token ?: (string) Str::uuid(),
        ]);
        $facility->save();
    }
}
