<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Models\Category;
use Illuminate\Support\Facades\Auth;

class CategoryController extends Controller
{

    const CATEGORIES_BLADE = 'src/categories';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $categories = Category::all();
        return view(CategoryController::CATEGORIES_BLADE, 
        ['categories' => $categories, 'selectedCategory' => null]);
    }

    public function save(Request $request){

        $data = $request->validate([
            'category_name' => 'required|max:255'
        ]);

        $data['created_by'] = Auth::user()->user_id;
        $data['description'] = $request->description;
    
        $selected = $request->selected_category;
    
        if($selected){
            $category = tap(Category::where('category_id', $selected)->update($data));
        }else {
            $category = tap(new Category($data))->save();
        }

        return redirect('/categories');
    }

    public function search(Request $request){

        $categories = Category::where('category_name', 'like', 
        '%' .$request->keyword. '%')->get();
        return json_encode($categories);
    }

    public function edit($id) {
        $categoryId = $id;
        $selectedCategory = Category::find($categoryId);
        $categories = Category::all();
        
        return view(CategoryController::CATEGORIES_BLADE, 
        ['categories' => $categories, 'selectedCategory' => $selectedCategory]);
    }

    public function del(Request $request) {

        $categoryId = $request->deletecategory;
        $category = Category::find($categoryId);
        $category->delete();
        
        return redirect('/categories');
    }
}