<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
// use Illuminate\Http\Request as HttpRequest;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Feeds\Enums\StatusEnum;
use App\Http\Requests\ImageFormRequest;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redirect;
use App\Domain\Tags\Action\CreateTagAction;
use App\Domain\Feeds\Action\CreateFeedAction;
use App\Domain\Feeds\Queries\FeedQueryBuilder;
use App\Domain\Images\Action\CreateImageAction;
use App\Domain\Images\Action\UpdateImageAction;
use App\Domain\Feeds\Service\FeedMediaTransform;
use App\Domain\Images\DataTransferObjects\ImageData;

class ImagesController extends Controller
{

    public function __construct()
    {
        $this->middleware('subs.paid')->except('show');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $filter = Request::get('filter');

        $feeds = (new FeedQueryBuilder())
            ->addType('image')
            ->enableAdvertising()
            ->search(Request::only('search'))
            ->filter($filter)
            ->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        $route = route('images.index');
        return Inertia::render('Image/Index', [
            'nextCursor' => $nextCursor,
            'searchFilters' => Request::all('search'),
            'feeds' => $feeds,
            'local_route' => $route,
            'active_filter' => $filter ?? 'new'
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return Inertia::render('Image/Create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\ImageFormRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ImageFormRequest $request)
    {
        $action = new CreateFeedAction(
            new CreateImageAction(),
            new CreateTagAction(),
        );

        $imageData = ImageData::fromRequest($request);
        $action($imageData);
        $msg = 'Изображение успешно загружено и находится на модерации!';
        return Redirect::route('profile.user', auth()->user()->username)->with('success', $msg);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($slug)
    {
        $feed = new FeedQueryBuilder();
        $feed = $feed->selectBy('slug', $slug)->disablePaginate()->transformGet()->first();
        if(!$feed){
            abort(404);
        }
        return Inertia::render('Image/Show', [
            'user' => $feed['user'],
            'feed' =>  $feed,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  string  $slug
     * @return \Illuminate\Http\Response
     */
    public function edit($slug)
    {
        $feed = Feed::where('slug', $slug)->firstOrFail();
        if (!$feed->user()->is(auth()->user())) {
            abort(404);
        }
        $tags = $feed->tags()->pluck('name')->toArray();

        $mediaTransformCommon = (new FeedMediaTransform($feed))->default()->spot();
        $mediaTransformPaid = (new FeedMediaTransform($feed))->paid()->spot();

        return Inertia::render('Image/Edit', [
            'feed' => $feed,
            'tags' => $tags,
            'mediasCount' => count($mediaTransformCommon['medias']),
            'mediasCommon' => $mediaTransformCommon['medias'],
            'mediasPaid' => $mediaTransformPaid['medias'],
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ImageFormRequest $request, Feed $feed)
    {
        $oldStatus = $feed->status;
        if (!$feed->user()->is(auth()->user())) {
            abort(404);
        }

        $action = new CreateFeedAction(
            new UpdateImageAction($feed),
            new CreateTagAction(),
        );

        $imageData = ImageData::fromRequest($request);
        $action($imageData);

        $newStatus = $feed->status;

        $message = 'Изображение успешно обновлено!';
        if($oldStatus === StatusEnum::APPROVED() && $newStatus === StatusEnum::EDITABLE()){
            $message = 'Изображение успешно обновлено и находится на модерации!';
        }
        return Redirect::back()->with('success', $message);

    }
}
