<?php

namespace App\Http\Controllers;

use App\Models\NewsRoom;
use Illuminate\Http\Request;

class NewsroomController extends Controller
{
    public function index()
    {
        $newsrooms = NewsRoom::orderBy('id','desc')->where('delete_status','0')->paginate(10);
        return view('backend.newsroom.index', compact('newsrooms') );
    }

    public function create()
    {
        return view('backend.newsroom.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
        ]);

        $newsroom=$request->all();

        if($request->file('image')){
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('backend/images/newsroom'), $imageName);
            $newsroom['image']=$imageName;
        }


        $newsroom['slug']=\Str::slug($request->title).'-'.rand();
        NewsRoom::create($newsroom);


        return redirect()->route('newsroom.index')
        ->with('success','Newsroom created successfully.');
    }

    public function edit(NewsRoom $newsroom)
    {
        return view('backend.newsroom.edit',compact('newsroom'));
    }

    public function update(Request $request,  $id)
    {
        $newsroom = NewsRoom::find($id);
        $input=$request->all();

        if($request->file('image')){
            $imageName = time().'.'.$request->image->extension();
            $request->image->move(public_path('backend/images/newsroom'), $imageName);
            $input['image']=$imageName;
        }

        $newsroom->update($input);


        return redirect()->route('newsroom.index')->with('success','NewsRoom updated successfully.');
    }

    public function destroy($id)
    {
        $newsroom= NewsRoom::where('id', $id)->update(array('delete_status' => 1));

        return redirect()->route('newsroom.index')
                        ->with('success','NewsRoom deleted successfully');
    }

    public function changeStatus(Request $request)

    {
        $newsroom = NewsRoom::find($request->id);
        $newsroom->status = $request->status;
        $newsroom->save();

        return response()->json(['success'=>'Status change successfully.']);
    }

}
