<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use App\CreditUser;
use App\Http\Requests\CreditUserRequest;
use Auth;

class CreditUserController extends Controller
{
	public function __construct()
    {
        $this->middleware('auth');
    }


    public function index(User $user)
    {
		if(Auth::user()->role->role_permission('view_credit')){
			if(Auth::user()->role->role_permission('view_credit')->level == 'all'){
				$credituser = CreditUser::where('user_id',$user->id)->with('credit')->with('reservation')->paginate(30);
				
			}
		return view('credituser.index', compact('credituser'));
		}else{
			abort(403);
		}
    }
	
	public function search(Request $request)
	{
		if(Auth::user()->role->role_permission('view_credit')){
			$credituser = Credit::where('name', 'LIKE', '%'. $request->get('term') .'%')->paginate(30);
           
			return view('credituser.index', compact('credit'));
		}else{
			abort(403);
		}
	}
    
    public function create()
    {
		if(Auth::user()->role->role_permission('create_credit')){
         
			return view('credituser.create');
		}else{
			abort(403);
		}
    }
	
    public function store(CreditUserRequest $request)
    {
			if(Auth::user()->role->role_permission('create_credit')){
				
				$credituser = Credit::create($request->all());
			
				return redirect('credits')->withSuccess($credit->name.' has been saved.');
			}else{
				abort(403);
			}
    }
	
    public function show(CreditUser $credituser)
    {
		if(Auth::user()->role->role_permission('view_credit')){
			return view('credituser.show', compact('credituser'));
		}else{
			abort(403);
		}
    }
	
    public function edit(CreditUser $credituser,User $user)
    {
		if(Auth::user()->role->role_permission('edit_credit')){
			//$credituser= $credituser->with('credit')->with('reservation')->first();
			return view('credituser.edit', compact('credituser','user'));
		}else{
			abort(403);
		}
    }
	
    public function update(CreditUserRequest $request, CreditUser $credituser,User $user)
    {
		
        if(Auth::user()->role->role_permission('edit_credit')){
            $credituser= $credituser->first();
			      $credituser->update($request->all());
           
            $credituser = CreditUser::where('user_id',$user->id)->with('credit')->with('reservation')->paginate(30);
		
            return view('credituser.index', compact('credituser'))->withSuccess(' has been updated.');
		}else{
			abort(403);
		}
    }
	
    public function destroy(CreditUser $credituser,User $user)
    {
		if(Auth::user()->role->role_permission('delete_credit')){
			$credituser= $credituser->first();
			$credituser->delete();
			$credituser = CreditUser::where('user_id',$user->id)->with('credit')->with('reservation')->paginate(30);
		
			return view('credituser.index', compact('credituser'))->withSuccess(' has been deleted.');
		}else{
			abort(403);
		}
    }
}
