<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Category;
use App\Item;
use Session;
use Illuminate\Validation\Rule;
use DB;
class CategoryController extends Controller
{
      

      public function __construct()
{
           
}

function index()
{
      $categoryList = Category::with('children')
    ->orderBy('id', 'DESC')
    ->get();
      return view('procurement/categories.index' ,compact('categoryList') );
}


function create()
{
    $categories = Category::orderBy('category_name')->get();
      return view('procurement/categories.addCategory' , compact('categories'));
}



function store(Request $request)
{

$validator = Validator::make($request->all(), [
                    'name' => 'required|unique:categories,category_name',
                    'category_type' => 'required',
        ]);


       if ($validator->fails()) {
            return redirect('/categories/add-category')
                            ->withErrors($validator)
                            ->withInput();
        }


         $createCategory = Category::create([
                    'category_name' => $request->name,
                    'parent_id' => $request->category_type,
                    'description' => $request->description
                    
          ]);
        
        return redirect()->route('category.list')->with('success' , 'Category Added Successfully!');
}

function destroy($id)
{
 
    if(is_numeric($id))
    {
        DB::beginTransaction();

   try {
        
        Category::where('id',$id)->delete();
        DB::commit();
   
      } 
        catch (\Exception $e) 
      {
       DB::rollback();
    
      }
    
    }
 
  return redirect()->route('category.list')->with('success' , 'Category Removed Successfully!');
}

function edit($id)
{
 
    if(is_numeric($id))
    {
        $findCategory = Category::where('id', $id)->first();
        $categories = Category::where('id' , '!=', $id)->orderBy('category_name')->get();
        return view('procurement/categories.editCategory' ,compact('findCategory' , 'categories') );
    }

    }

function update(Request $request)
{

$id = $request->input('id');
if(is_numeric($id))
{
  $validator = Validator::make($request->all(), [
                    'name' => 'required|unique:categories,category_name,'.$id,
                    'category_type' => 'required',

        ]);


       if ($validator->fails()) {
            return redirect('/categories/edit-category/'.$id)
                            ->withErrors($validator)
                            ->withInput();
        }

    Category::where('id', '=', $id)->update(array( 'category_name' => $request->name,  'parent_id' => $request->category_type, 'description' => $request->description));
}

  return redirect()->route('category.list')->with('success' , 'Category Updated Successfully!');
}

}
