<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\News;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class NewsController extends Controller
{
    public function addNews(): View
    {
        return view('admin.add-news', [
        ]);
    }

    public function storeNews(Request $request): RedirectResponse
    {

//        dd($request);

        $news = new News();

        $request->validate([
            'title' => 'required',
            'caption' => 'required',
            'description' => 'required',
            'path' => 'required',
            'order' => 'required',
        ]);

        // Determine the values of active and featured based on the checkbox status
        $active = $request->has('active') ? 1 : 0;


        $news->title = $request->title;
        $news->caption = $request->caption;
        $news->description = $request->description;
        $news->active = $active;
        $news->image = $request->path;
        $news->order = $request->order;
        $news->slug = strtolower(str_replace(' ', '-', $request->title));

        $news->save();

        return redirect()->route('list-news')->with('success', 'News created successfully');

    }


    public function listNews(): View
    {
        $news = News::all();

        return view('admin.list-news', [
            'news' => $news,
        ]);
    }


    public function editNews($id): View
    {
        $news = News::findOrFail($id);


        return view('admin.edit-news', [
            'news' => $news,
        ]);
    }


    public function updateNews(Request $request): RedirectResponse
    {

//        dd($request);

        $request->validate([
            'title' => 'required',
            'caption' => 'required',
            'description' => 'required',
            'path' => 'required',
            'order' => 'required',
        ]);

        $id = $request->id;

        // Determine the values of active and featured based on the checkbox status
        $active = $request->has('active') ? 1 : 0;

        News::findOrFail($id)->update([
            'title' => $request->title,
            'caption' => $request->caption,
            'description' => $request->description,
            'active' => $active,
            'image' => $request->path,
            'order' => $request->order,
            'slug' => strtolower(str_replace(' ', '-', $request->title)),
        ]);

        return redirect()->route('list-news')->with('success', 'News updated successfully');

    }

    public function deleteNews($id): RedirectResponse
    {
        News::findOrFail($id)->delete();
        return redirect()->route('list-news')->with('success', 'News deleted successfully');

    }

}
