<?php

namespace App\Http\Controllers\Mobile;

use App\Enums\InspectionCycle;
use App\Http\Controllers\Controller;
use App\Models\Equipment\Equipment;
use App\Models\Equipment\EquipmentInspection;
use App\Models\Equipment\EquipmentInspectionDetail;
use App\Models\Equipment\EquipmentInspectionTemplate;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MobileInspectionController extends Controller
{
    public function show(Request $request, int $id): View
    {
        $equipment = Equipment::with(['manager', 'subManager'])->findOrFail($id);

        $cycle = $request->input('cycle', InspectionCycle::DAILY);
        $today = now()->format('Y-m-d');
        $period = InspectionCycle::resolvePeriod($cycle, $today);

        $activeCycles = EquipmentInspectionTemplate::where('equipment_id', $equipment->id)
            ->where('is_active', true)
            ->distinct()
            ->pluck('inspection_cycle')
            ->toArray();

        $templates = EquipmentInspectionTemplate::where('equipment_id', $equipment->id)
            ->where('inspection_cycle', $cycle)
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $inspection = EquipmentInspection::where('equipment_id', $equipment->id)
            ->where('inspection_cycle', $cycle)
            ->where('year_month', $period)
            ->first();

        $details = collect();
        if ($inspection) {
            $details = EquipmentInspectionDetail::where('inspection_id', $inspection->id)
                ->where('check_date', $today)
                ->get()
                ->keyBy('template_item_id');
        }

        $canInspect = $equipment->canInspect();

        return view('mobile.inspection.show', compact(
            'equipment',
            'cycle',
            'today',
            'period',
            'activeCycles',
            'templates',
            'details',
            'canInspect',
        ));
    }
}
