<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

use App\Link;
use App\Http\Requests\LinkRequest;
use App\User;
use Auth;

class LinkController extends Controller
{
	public function __construct()
    {
        $this->middleware('auth');
    }
	
    public function index()
    {
		if(Auth::user()->role->role_permission('view_links')){
			if(Auth::user()->role->role_permission('view_links')->level == 'all'){
				$links = Link::paginate(30);
			}
			return view('links.index', compact('links'));
		}else{
			abort(403);
		}
    }
	
	public function search(Request $request)
	{
		if(Auth::user()->role->role_permission('view_links')){
			$links = Download::paginate(30);
			return view('links.index', compact('links'));
		}else{
			abort(403);
		}
	}
    
    public function create()
    {
		if(Auth::user()->role->role_permission('create_links')){
			return view('links.create');
		}else{
			abort(403);
		}
    }
	
    public function store(LinkRequest $request)
    {
		if(Auth::user()->role->role_permission('create_links')){
			$link = Link::create($request->all());
			return redirect('links')->withSuccess('Link has been saved.');
		}else{
			abort(403);
		}
    }
	
    public function show(Link $link)
    {
		if(Auth::user()->role->role_permission('view_links')){
			$link = Link::where('id', $link->id)->first();
			return view('links.show', compact('link'));
		}else{
			abort(403);
		}
    }
	
    public function edit(Link $link)
    {
		if(Auth::user()->role->role_permission('edit_links')){
			if(Auth::user()->role->role_permission('edit_links')->level == 'team'){
				$link = Link::where('id', $link->id)->first();
			}elseif(Auth::user()->role->role_permission('edit_links')->level == 'self'){
				$link = Link::where('id', $link->id)->first();
			}
			return $link ? view('links.edit', compact('link')) : abort(403);
		}else{
			abort(403);
		}
    }
	
    public function update(LinkRequest $request, Link $link)
    {
		if(Auth::user()->role->role_permission('edit_links')){
			$link->update($request->all());
			return redirect('links')->withSuccess('Link has been updated.');
		}else{
			abort(403);
		}
    }
	
    public function destroy(Link $link)
    {
		if(Auth::user()->role->role_permission('delete_links')){
			$link->delete();
			return redirect('links')->withSuccess('Link has been deleted.');
		}else{
			abort(403);
		}
    }
}
