<?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 PageTreeResource 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['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,
            'children' => $page->children->map(fn(PageModel $child) => $this->map($child)),
            'expanded' => false,
            'menu_open' => false,
            'description' => collect([
                $page->deleted_at ? 'Archived' : null,
                $page->slug,
                $page->template?->name
            ])
                ->filter()
                ->implode(' | '),
            'link' => '/manage-content/content/edit/' . $page->id,
            'disallow_delete' => Page::canRemove($page->id, $page) !== true,
            'deleted_at' => $page->deleted_at,
            'metaItems' => [
                $page->updated_at->diffForHumans(),
            ],
            'featured' => (bool) $page->featured,
        ];
    }
}
