<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend\Pouzivatelia;

use App\Http\Controllers\Controller;
use App\Http\Requests\PouzivatelUpdateRequest;
use App\Notifications\Push\MAAISEKUserSendPushNotification;
use App\Repositories\Eloquent\Criteria\OrderDescCriteria;
use App\Repositories\PouzivatelRepositoryContract;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

/**
 * Class PouzivateliaController
 */
final class PouzivateliaController extends Controller
{
    private PouzivatelRepositoryContract $pouzivatelRepository;

    /**
     * PouzivateliaController constructor.
     */
    public function __construct(PouzivatelRepositoryContract $pouzivatelRepository)
    {
        $this->pouzivatelRepository = $pouzivatelRepository;
    }

    /**
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function index(): View
    {
        $this->pouzivatelRepository->pushCriteria(OrderDescCriteria::class);
        $pouzivatelia = $this->pouzivatelRepository->paginate();

        return view('pages.backend.pouzivatelia.index')
            ->withPouzivatelia($pouzivatelia);
    }

    public function edit(int $pouzivatelId): View
    {
        $pouzivatel = $this->pouzivatelRepository->with('pracovisko')->find($pouzivatelId);

        return view('pages.backend.pouzivatelia.edit')
            ->withPouzivatel($pouzivatel);
    }

    public function update(PouzivatelUpdateRequest $request, int $pouzivatelId): RedirectResponse
    {
        $pouzivatel = $this->pouzivatelRepository->find($pouzivatelId);
        $this->pouzivatelRepository->update(
            collect($request->validated())->only('stav')->toArray(),
            $pouzivatel->id,
        );

        flash()->success(sprintf('Nastavenia účtu používateľa %s boli úspešbe upravené.', $pouzivatel->meno));

        return response()->redirectToRoute('portal.sprava.pouzivatelia.edit', $pouzivatel);
    }

    public function send(Request $request, int $pouzivatelId): RedirectResponse
    {
        $message = $request->get('message') ?? 'Testovacia notifikácia...';
        $pouzivatel = $this->pouzivatelRepository->find($pouzivatelId);

        $pouzivatel->notify(new MAAISEKUserSendPushNotification(Str::limit($message, 50)));

        flash()->success(
            sprintf('Notifikácia pre používateľa %s bola zaradená na odoslanie.', $pouzivatel->meno),
        )->overlay();

        return back();
    }
}
