<?php

namespace App\Http\Controllers;

use App\Models\Reading;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ServiceHistoryController extends Controller
{
    public function index(Request $request): View
    {
        $q = trim((string) $request->query('q', ''));

        $readings = Reading::query()
            ->with(['printer.client', 'technician'])
            ->when($q !== '', function ($query) use ($q) {
                $query->where(function ($sub) use ($q) {
                    $sub->whereHas('printer', fn ($p) => $p->where('serial_number', 'like', "%{$q}%")
                        ->orWhere('model', 'like', "%{$q}%")
                        ->orWhere('manufacturer', 'like', "%{$q}%"))
                    ->orWhereHas('printer.client', fn ($c) => $c->where('name', 'like', "%{$q}%"))
                    ->orWhereHas('technician', fn ($t) => $t->where('name', 'like', "%{$q}%"));
                });
            })
            ->orderByDesc('reading_date')
            ->orderByDesc('id')
            ->limit(500)
            ->get();

        if ($request->boolean('partial')) {
            return view('services._rows', compact('readings'));
        }

        return view('services.index', compact('readings', 'q'));
    }
}
