<?php

namespace App\Http\Resources;

use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Str;
use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\Crm\Models\EnquiryType;

class EnquiryList extends \Mtc\Crm\Http\Resources\EnquiryList
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn(EnquiryModel $enquiry) => $this->mapEntry($enquiry));
        } else {
            $this->resource = $this->resource
                ->map(fn(EnquiryModel $enquiry) => $this->mapEntry($enquiry));
        }
        $resource = $this->resource->toArray();
        $resource['filters'] = [
            [
                'name' => 'Partially submitted',
                'value' => 'partiallySubmitted',
            ],
            [
                'name' => 'Archived',
                'value' => 'archived',
            ],
            [
                'name' => 'Has Failed Actions',
                'value' => 'hasFailedActions',
            ],
            [
                'type' => 'list',
                'name' => 'Enquiry Type',
                'values' => EnquiryType::query()
                    ->select('name', 'id')
                    ->whereHas('enquiries')
                    ->get()
                    ->map(fn(EnquiryType $enquiryType) => [
                        'id' => $enquiryType->id,
                        'value' => 'enquiry-type-' . $enquiryType->id,
                        'name' => $enquiryType->name,
                    ]),
            ]
        ];

        return $resource;
    }

    private function mapEntry(EnquiryModel $enquiry)
    {
        return [
            'id' => $enquiry->id,
            'title' => $enquiry->title,
            'description' => __('labels.submitted_at', [
                'datetime' => Carbon::parse($enquiry->ingested_at)?->format('d/m/Y H:i'),
            ]),
            'metaItems' => [
                $enquiry->form?->name,
                $enquiry->actions
                    ->map(function ($action) {
                        if ($action->processed_at) {
                            return Str::title(str_replace('-', ' ', $action->action_name)) . ' - OK';
                        }
                        if ($action->failed_at) {
                            return Str::title(str_replace('-', ' ', $action->action_name)) . ' - Failed';
                        }
                        return Str::title(str_replace('-', ' ', $action->action_name)) . ' - Pending';
                    })->implode('<br/>'),
            ]
        ];
    }
}
