<?php

namespace App;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\Crm\Models\Scopes\OnlySubmitted;

class EnquiryRepository extends \Mtc\Crm\EnquiryRepository
{
    public function showList(Request $request): LengthAwarePaginator
    {
        return $this->enquiry->newQuery()
            ->with([
                'form',
                'type',
                'status',
            ])
            ->when(
                $request->filled('customer_id'),
                fn($query) => $query->where('customer_id', $request->input('customer_id'))
            )
            ->archived($request->input('archive', 0))
            ->setSortBy($request->input('sort_by', 'id_desc'))
            ->setFilters($request->input('filters', []))
            ->paginate()
            ->appends($request->input());
    }

    /**
     * find and return enquiry
     * @param int $id
     * @return EnquiryModel|Model
     */
    public function find(int $id): EnquiryModel
    {
        return $this->enquiry = $this->enquiry
            ->newQuery()
            ->withoutGlobalScope(OnlySubmitted::class)
            ->whereNotNull('status_id')
            ->findOrFail($id);
    }
}
