<?php

namespace App\Http\Controllers;

use App\Http\Requests\BulkUpdateSeoDefaultRequest;
use App\Http\Requests\UpdateSeoDefaultRequest;
use App\Traits\ExtractOgImageID;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Response;
use Mtc\ContentManager\Facades\Media;
use Mtc\ContentManager\Http\Resources\MediaEntryResource;
use Mtc\MercuryDataModels\SeoDefault;

class SeoDefaultController extends Controller
{
    use ExtractOgImageID;

    public function __construct()
    {
        $this->middleware([
            'permission:edit-seo',
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return Collection
     */
    public function index(): Collection
    {
        return SeoDefault::query()
            ->with('ogImage.media')
            ->get()
            ->map(function ($default) {

                $default->supported_tags = __("seo.default_tags.$default->section");
                if ($default->ogImage) {
                    $default->media_uses = [ new MediaEntryResource($default->ogImage) ];
                    $default->ogImage = [ $default->ogImage->media_id ];
                }
                return $default;
            });
    }

    public function bulkUpdate(BulkUpdateSeoDefaultRequest $request): Collection
    {
        collect($request->input('defaults', []))
            ->each(function ($input) {
                $default = SeoDefault::query()->find($input['id']);
                $default->update($input);
                !empty($input['og_image'])
                    ? Media::setUsesForModel([ $this->getID($input['og_image']) ], $default, [], true)
                    : Media::setUsesForModel([], $default, [], true);
            });
        return $this->index();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateSeoDefaultRequest  $request
     * @param  \Mtc\MercuryDataModels\SeoDefault  $default
     * @return Response
     */
    public function update(UpdateSeoDefaultRequest $request, SeoDefault $default): Collection
    {
        $default->update($request->input());
        $request->filled('og_image')
            ? Media::setUsesForModel([ $this->getID($request->input('og_image'))], $default, [], true)
            : Media::setUsesForModel([], $default, [], true);
        return $this->index();
    }
}
