<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Dealership;

class DealershipListResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn(Dealership $dealership) => $this->mapOffer($dealership));
        } else {
            $this->resource = $this->resource
                ->map(fn(Dealership $dealership) => $this->mapOffer($dealership));
        }
        $resource = $this->resource->toArray();
        $resource['default_columns'] = [
            'vehicle_count',
            'address',
            'contact_no',
        ];

        $resource['view_columns'] = [
            [
                'id' => 'vehicle_count',
                'name' => 'Vehicle count',
                'icon' => 'cars',
            ],
            [
                'id' => 'address',
                'name' => 'Address',
                'icon' => 'location-dot',
            ],
            [
                'id' => 'contact_no',
                'name' => 'Phone number',
                'icon' => 'phone',
            ],
        ];
        return $resource;
    }

    /**
     * Convert vehicle to the json format used in lists
     *
     * @param Dealership $dealership
     * @return array
     */
    protected function mapOffer(Dealership $dealership)
    {
        return [
            'image' => [
                'src' => $dealership->getPreviewImage('mini-thumb'),
                'alt' => $dealership->name,
            ],
            'active' => $dealership->active,
            'title' => $dealership->name,
            'metaItems' => [
                'vehicle_count' => $dealership->vehicle_count,
                'address' => collect([
                    $dealership->address1,
                    $dealership->address2,
                    $dealership->city,
                    $dealership->postcode,
                ])->filter()->implode(', '),
                'contact_no' => $dealership->contact_no,
            ],
            'id' => $dealership->id,
        ];
    }
}
