<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Traits\FranchiseData;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Contracts\PageModel;
use Mtc\ContentManager\Facades\Page;

class PageListResource extends JsonResource
{
    use FranchiseData;

    /**
     * @var LengthAwarePaginator|Collection
     */
    public $resource;

    /**
     * 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(PageModel $page) => $this->map($page));

            $data = $this->resource->toArray();
            $data['filters'] = collect(config('pages.page_types', []))
                ->filter(fn($type) => Settings::get($type['config_key']))
                ->map(fn ($filter) => [
                    'name' => $filter['name'],
                    'id' => $filter['value'],
                    'value' => $filter['filter'],
                    'default_template' => (int)Settings::get($filter['template_config'])
                ])->values();
            if ($this->hasFranchises()) {
                $data['filters']->push($this->franchiseFilter());
            }
            $data['soft_deletes'] = true;
            return $data;
        }

        $this->resource = $this->resource->map(fn(PageModel $page) => $this->map($page));

        return parent::toArray($request);
    }

    /**
     * Map page entry
     *
     * @param PageModel $page
     * @return array
     */
    private function map(PageModel $page)
    {
        return [
            'id' => $page->id,
            'title' => $page->title,
            'active' => $page->status === 'published',
            'status' => $page->status,
            'description' => $page->template->name ?? '',
            'image' => [
                'src' => $page->primaryMediaUse?->getUrl('mini-thumb'),
                'alt' => $page->title,
            ],
            'link' => '/manage-content/content/edit/' . $page->id,
            'disallow_delete' => Page::canRemove($page->id) !== true,
            'deleted_at' => $page->deleted_at,
            'metaItems' => [
                $page->updated_at->diffForHumans(),
                $page->users
                    ->map(fn ($user) => [
                        'alt' => $user->name,
                        'src' => $user->profile_photo_url
                    ]),
            ],
        ];
    }
}
