<?php

namespace App\Http\Resources;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Mtc\ContentManager\Contracts\Menu;
use Mtc\ContentManager\Http\Resources\MenuList as ParentMenuList;
use Mtc\MercuryDataModels\Franchise;

class MenuList extends ParentMenuList
{
    /**
     * 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) {
            $resource = $this->resource
                ->through(fn(Menu $menu) => $this->map($menu))
                ->toArray();
            $resource['default_columns'] = [
                'status',
                'updated',
            ];
            $resource['filters'] = Franchise::query()
                ->whereHas('menus')
                ->select('name', 'slug as value')
                ->get();
            return $resource;
        }
        $this->resource = $this->resource->map(fn(Menu $menu) => $this->map($menu));
        return parent::toArray($request);
    }

    /**
     * Map Menu entry
     *
     * @param Menu $menu
     * @return array
     */
    private function map(Menu $menu)
    {
        return [
            'id' => $menu->id,
            'title' => $menu->title,
            'description' => $menu->description,
            'disallow_delete' => $menu->meta['disallow_delete'] ?? false,
            'metaItems' => [
                'status' => $menu->is_enabled ? __('labels.active') : __('labels.inactive'),
                'updated' => $menu->updated_at->diffForHumans(),
            ],
        ];
    }
}
