<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\CategoryModel;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
     public function category()
    {
        $records   =  CategoryModel::orderBy('id', 'ASC')->get();
        return view('backend.category.list', compact('records'));
    }

    public function addCategory($id = '')
    {
        $record = '';
        if ($id > 0) {
            $record = CategoryModel::WHere('id', $id)->first();
        }
        return view('backend.category.add_edit', compact('record'));
    }

    public function storeUpdateCategory(Request $request)
    {
        $input     = $request->all();
        $id        = isset($input['id']) ? $input['id'] : 0;

        $dataArr = [];
        foreach ($input as $key => $val) {
            if ($key != '_token' && $key != 'id' )
                $dataArr[$key] = $val;
        }       
        if ($id == 0 || $id == '') {
            $request->validate([
                'category_name'          =>  "required|unique:category,category_name",                
              
            ]);
           $insert = CategoryModel::create($dataArr);
           if($insert['id'] > 0)
           {
               return redirect()->route('category')->with('success', 'Category Saved Successfully');
           }else{
               return redirect()->route('category')->with('error', 'Something went wrong!');
           }
           
        } else {
            $request->validate([                
                'category_name'     =>  "required",
            ]);
            $update = CategoryModel::Where('id',$id)->update($dataArr);
            return redirect()->route('category')->with('success', 'Category Updated Successfully');;
        }        
    }
}
