<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class CategoryController extends Controller
{

    public function index(Request $request, $id = '')
    {
        if ($id > 0) {
            $arr = Category::where(['id' => $id])->get();

            $result['category'] = $arr['0']->category;
            $result['category_slug'] = $arr['0']->category_slug;
            $result['id']=$arr['0']->id;
        } else {
            $result['category'] = '';
            $result['category_slug'] = '';
            $result['id']=0;
        }
        $Categores = Category::all();
        return view('admin/category', compact('Categores'),$result);
    }

    public function create(Request $request)
    {
        $validatedData = $request->validate([
            "category" => 'required',
            "category_slug" => 'required|unique:categories,category_slug,'.$request->input('id'),

        ]);
        if($request->input('id')>0){
            $Categores=Category::find($request->input('id'));
            $msg="Category updated";
        }else{
            $Categores = new Category;
            $msg="Category inserted";
        }
        $Categores->category = $request->input('category');
        $Categores->category_slug = $request->input('category_slug');
        $Categores->status = 1;
        $Categores->save();
        Session::flash('message', $msg);
        return redirect('category');
    }


    public function status(Request $request,$status,$id){
        $model=Category::find($id);
        $model->status=$status;
        $model->save();
        Session::flash('message','Category status updated');
        return redirect('category');
    }

    public function show(Category $category)
    {
    }

    public function edit(Category $category)
    {
    }

    public function update(Request $request, Category $category)
    {
    }

    public function delete(Request $request, $id)
    {
        $model = Category::find($id);
        $model->delete();
        Session::flash('message', 'Category deleted');
        return redirect('category');
    }
}
