<?php

namespace App\Crm;

use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\Crm\Models\FormQuestion;

trait EnquiryDataToProviderData
{
    private function convertEnquiryToParams(EnquiryModel $enquiry, string $provider): array
    {
        $answers = collect($enquiry->details ?? [])->map(fn($answer) => $answer['answer'] ?? null);
        return FormQuestion::query()
            ->whereIn('id', $answers->keys())
            ->get()
            ->keyBy('id')
            ->map(fn($question) => $question->data[$provider] ?? null)
            ->filter()
            ->groupBy(fn($field) => $field, true)
            ->map(fn($group) => $group->count() == 1
                ? $answers[$group->keys()->first()] ?? null
                : $group->map(fn($key, $item) => $answers[$item] ?? null)->filter()->implode(', '))
            ->toArray();
    }
}
