<?php

namespace App\Services;

use App\Models\LeasingRecord;
use Illuminate\Database\Eloquent\Builder;

class RecordSearchService
{
    /**
     * Search for vehicles across all active leasing data.
     */
    public function search(array $filters): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query = LeasingRecord::with(['leasingProfile', 'branch'])
            ->where('record_status', 'active');

        if (!empty($filters['query'])) {
            $q = strtoupper(trim($filters['query']));
            $query->where(function (Builder $sub) use ($q) {
                $sub->where('nopol', 'like', "%{$q}%")
                    ->orWhere('rangka', 'like', "%{$q}%")
                    ->orWhere('mesin', 'like', "%{$q}%");
            });
        }

        if (!empty($filters['leasing_id'])) {
            $query->where('leasing_profile_id', $filters['leasing_id']);
        }

        if (!empty($filters['branch_id'])) {
            $query->where('branch_id', $filters['branch_id']);
        }

        return $query->latest('tgl_data')->paginate(15);
    }

    /**
     * Find a single record with related data, ensuring it's active.
     */
    public function findById(int $id): ?LeasingRecord
    {
        return LeasingRecord::with(['leasingProfile', 'branch'])
            ->where('record_status', 'active')
            ->findOrFail($id);
    }
}
