<?php

namespace App\Http\Controllers;

use App\Link;
use App\Category;
use App\AdminSet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CategoryController extends Controller
{/*
    public function __construct()
    {
        $this->middleware('auth');
    }*/

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::all();
        return view('admin.create_category', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $category = new Category;
        $category->name = $request->name;
        $category->save();

        return redirect()->route('category.index', compact('category'))->withMessage('A category created successfully!');
    }

    /**
     * Display the category posts.
     * Pagination is used on category model.
     * 
     * categories used in AppServiceProvider
     *
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        $categories = Category::all();
        $links = $category->links()->latest()->paginate(10);
        //$admin = AdminSet::first();
        return view('links.category', compact('links', 'categories', 'category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        $this->validate($request, [
            'name' => 'required|min:3'
        ]);

        //update
        $category->update($request->all());

        //redirect
        return redirect()->route('category.index', $category->id)->withMessage('Category name has updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        //$category->links()->delete();
        //$category->delete();
        //Link::whereCategoryId($id)->update(['category_id' => null]);
//
        //Session::flash('success', 'The category was successfully deleted.');
        //return redirect()->back();

        Link::where('category_id', $category->id)->update(['category_id' => null]);

        $category->delete();

        return redirect()->back()->withMessage('The category is deleted successfully!');
    }
}
