<?php

namespace App\Http\Controllers\Admin\Blog;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use App\Tag;
use App\PostPivotTag;
use Session;
use DB;
use Toastr;


class TagController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function index()
    {
        $tags = Tag::latest()->get();
        return view('admin.blog.tags.index', compact('tags'));
    }




    public function create()
    {
        return view('admin.blog.tags.create');
    }




    public function store(Request $request)
    {
         $this->validate($request,[
            'name'=>'unique:tags',
        ]);

        $tag= new Tag();
        $tag->name=$request->name;
        $tag->slug=Str::slug($request->name);
        $tag->save();
        
        
        Toastr::success('message', 'tag created successfully.'); 
        return redirect('/admin/tag');
    }

 


    public function edit($id)
    {
        $tag = Tag::find($id);
        return view('admin.blog.tags.edit', compact('tag'));

    }


    public function update(Request $request, $id)
    {
         $this->validate($request,[
            'name'=>[Rule::unique("tags")->ignore($id)],
        ]);

        $tag= Tag::find($id);
        $tag->name=$request->name;
        $tag->slug=Str::slug($request->name);
        $tag->save();
        
        Toastr::success('message', 'Tag Updated successfully.'); 
        return redirect('/admin/tag');
    }

   
    public function destroy($id)
    {
        $tag= Tag::find($id);

        PostPivotTag::where('tag_id',$id)->delete();

        $tag->delete();
        
        
        

        Toastr::success('message', 'Tag deleted successfully.');
        return redirect('admin/tag');
    }
}
