<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\SaveLoginScreenNewsRequest;
use App\Models\LoginScreenNews;
use App\Services\LoginScreenNewsService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Str;
use Illuminate\View\View;

class LoginScreenNewsController extends Controller
{
    public function index(LoginScreenNewsService $news): View
    {
        return view('admin.login-screen-news.index', [
            'newsItems' => $news->listForAdmin(),
            'newsStats' => $news->stats(),
            'feedPreview' => $news->renderFeed(),
            'feedUrl' => Str::replaceFirst('https://', 'http://', route('launcher.login-news.show')),
        ]);
    }

    public function store(SaveLoginScreenNewsRequest $request, LoginScreenNewsService $news): RedirectResponse
    {
        $news->create($request->validated(), $request->user());

        return back()->with('status', 'Новость для логин-экрана добавлена.');
    }

    public function update(
        LoginScreenNews $newsItem,
        SaveLoginScreenNewsRequest $request,
        LoginScreenNewsService $news,
    ): RedirectResponse {
        $news->update($newsItem, $request->validated(), $request->user());

        return back()->with('status', 'Новость для логин-экрана обновлена.');
    }

    public function destroy(LoginScreenNews $newsItem, LoginScreenNewsService $news): RedirectResponse
    {
        $news->delete($newsItem);

        return back()->with('status', 'Новость для логин-экрана удалена.');
    }
}
