<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\QuestionCategory;
use Illuminate\Validation\Rule;
use DB;
use Validator;
class QuestionCategoryController extends Controller
{
    public function add()
    {  
    	$this->data['category'] = $category = new QuestionCategory;
        return view('questioncategory.add', $this->data);
    }
    public function edit($id) {
		$this->data['category'] = $category = QuestionCategory::where('id', $id)->first();
		// dd($this->data['company']);
		return view('questioncategory.add', $this->data);
	}
    public function list()
    {  
       	$categories= QuestionCategory::toBase()->get();
        return view('questioncategory.list',compact('categories'));
        
    }
    public function save(Request $request) {
		//dd($request->all());
		DB::beginTransaction();
		try {
			$validator = Validator::make($request->all(), [
				"question_category" => [
					Rule::unique('question_categories')->ignore($request->id),
					'required:true',
				],
				"status" => [
					'required:true',
				],
			]);

			if ($validator->fails()) {
				return response()->json(['success' => false, 'errors' => $validator->errors()->all()]);
			} else {

				if (empty($request->id)) {
					$category = new QuestionCategory;

				} else {
					$category = QuestionCategory::where('id', $request->id)->first();
					$category->updated_at = date('Y-m-d H:i:s');
				}
				$category->question_category = $request->question_category;
				$category->status = $request->status;
				$category->save();
				DB::commit();
				if (empty($request->id)) {
					$request->session()->flash('success', 'Category added successfully!');
					return redirect('/question-category/list')->with('success', 'Category added successfully!');
				} else {
					$request->session()->flash('success', 'Category updated successfully!');
					return redirect('/question-category/list')->with('success', 'Category updated successfully!');
				}
				return response()->json(['success' => true]);
			}

		} catch (Exception $e) {
			DB::rollBack();
			return response()->json(['success' => false, 'errors' => ['Exception Error' => $e->getMessage()]]);
		}

	}
	public function delete($id)
    {
      	DB::delete('delete from questions_categories where id = ?',[$id]);
      	return redirect('/question-category/list')->with('success', 'Category deleted successfully!');
    }
}
