<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Question;
use App\Http\Requests\QuestionRequest;
use App\User;
use App\Answer;
use Auth;

class QuestionController extends Controller
{
	public function __construct()
    {
        $this->middleware('auth');
    }
	
    public function index()
    {
		if(Auth::user()->role->role_permission('view_questions')){
			if(Auth::user()->role->role_permission('view_questions')->level == 'all'){
				$questions = Question::paginate(30);
			}
			return view('questions.index', compact('questions'));
		}else{
			abort(403);
		}
    }

    public function create()
    {
		if(Auth::user()->role->role_permission('create_questions')){
			return view('questions.create');
		}else{
			abort(403);
		}
    }
	
    public function store(QuestionRequest $request)
    {
		if(Auth::user()->role->role_permission('create_questions')){
			$question = Question::create($request->all());
			return redirect('questions')->withSuccess('Question has been saved.');
		}else{
			abort(403);
		}
    }
	
    public function show(Question $question)
    {

		if(Auth::user()->role->role_permission('view_questions')){
			$question = Question::where('id', $question->id)->first();
			$questionId = $question->id;
			$answers = Answer::where('question_id', $questionId)->get();
			return view('answers.index', compact('answers','questionId'));
			//return view('questions.show', compact('question'));
		}else{
			abort(403);
		}
    }
	
    public function edit(Question $question)
    {
		if(Auth::user()->role->role_permission('edit_questions')){
			if(Auth::user()->role->role_permission('edit_questions')->level == 'team'){
				$question = Question::where('id', $question->id)->first();
			}elseif(Auth::user()->role->role_permission('edit_questions')->level == 'self'){
				$question = Question::where('id', $question->id)->first();
			}
		
			return $question ? view('questions.edit', compact('question')) : abort(403);
		}else{
			abort(403);
		}
    }
	
    public function update(QuestionRequest $request)
    {
        
		if(Auth::user()->role->role_permission('edit_questions')){
		  $question = Question::find($request->id);
			$question->update($request->all());
			return redirect('questions')->withSuccess('Question has been updated.');
		}else{
			abort(403);
		}
    }
	
    public function destroy(Question $question)
    {

		if(Auth::user()->role->role_permission('delete_questions')){
			$question->delete();
			return redirect('questions')->withSuccess('Question has been deleted.');
		}else{
			abort(403);
		}
    }
}
