<?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
     * @param bool $withTrashed Include soft-deleted records
     * @return EnquiryModel|Model
     */
    public function find(int $id, bool $withTrashed = true): EnquiryModel
    {
        return $this->enquiry = $this->enquiry
            ->newQuery()
            ->when($withTrashed, fn($query) => $query->withTrashed())
            ->withoutGlobalScope(OnlySubmitted::class)
            ->whereNotNull('status_id')
            ->findOrFail($id);
    }

    /**
     * Mark enquiries as spam - updates status to Spam and soft-deletes
     *
     * @param array|int $ids
     * @return int Number of enquiries marked as spam
     */
    public function markAsSpam(array|int $ids): int
    {
        $ids = (array) $ids;

        // Find or create Spam status
        $statusModel = config('crm.status_model');
        $spamStatus = $statusModel::query()->firstOrCreate(
            ['name' => 'Spam'],
            ['is_initial' => false, 'is_final' => true]
        );

        // Update status to Spam and soft-delete
        return $this->enquiry->newQuery()
            ->whereIn('id', $ids)
            ->update([
                'status_id' => $spamStatus->id,
                'deleted_at' => now(),
            ]);
    }
}
