<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreMaintenanceLogRequest;
use App\Models\Item;
use App\Services\PublicMaintenanceLookup;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

class PublicMaintenanceController extends Controller
{
    public function show(string $token, PublicMaintenanceLookup $lookup): View
    {
        $target = $lookup->findByToken($token);
        abort_unless($target, 404);

        return view('public-maintenance.show', [
            'target' => $target,
            'token' => $token,
        ]);
    }

    public function store(StoreMaintenanceLogRequest $request, string $token, PublicMaintenanceLookup $lookup): RedirectResponse
    {
        $target = $lookup->findByToken($token);
        abort_unless($target, 404);

        $photoPath = $request->file('photo')?->store('maintenance-photos', 'public');

        $target->maintenanceLogs()->create([
            'user_id' => $request->user()?->id,
            'submitter_name' => $request->validated('submitter_name'),
            'performed_at' => $request->validated('performed_at'),
            'condition' => $request->validated('condition'),
            'notes' => $request->validated('notes'),
            'location_note' => $request->validated('location_note'),
            'photo_path' => $photoPath,
            'source' => 'public_qr',
        ]);

        if ($target instanceof Item) {
            $target->update([
                'last_checked_at' => $request->validated('performed_at'),
                'notes' => trim(($target->notes ? $target->notes.PHP_EOL : '').($request->validated('notes') ?? '')),
            ]);
        } else {
            $target->update([
                'last_checked_at' => $request->validated('performed_at'),
                'current_condition' => $request->validated('condition'),
                'notes' => trim(($target->notes ? $target->notes.PHP_EOL : '').($request->validated('notes') ?? '')),
            ]);
        }

        return redirect()->route('maintenance.public.show', $token)->with('status', 'Laporan maintenance berhasil dikirim.');
    }
}
