<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

use App\Download;
use App\Http\Requests\DownloadRequest;
use App\User;
use Auth;

class DownloadController extends Controller
{
	public function __construct()
    {
        $this->middleware('auth');
    }
	
    public function index()
    {
		if(Auth::user()->role->role_permission('view_downloads')){
			if(Auth::user()->role->role_permission('view_downloads')->level == 'all'){
				$downloads = Download::paginate(30);
			}
			return view('downloads.index', compact('downloads'));
		}else{
			abort(403);
		}
    }
	
	public function search(Request $request)
	{
		if(Auth::user()->role->role_permission('view_downloads')){
			$downloads = Download::paginate(30);
			return view('downloads.index', compact('downloads'));
		}else{
			abort(403);
		}
	}
    
    public function create()
    {
		if(Auth::user()->role->role_permission('create_downloads')){
			return view('downloads.create');
		}else{
			abort(403);
		}
    }
	
    public function store(DownloadRequest $request)
    {
		if(Auth::user()->role->role_permission('create_downloads')){
			$download = Download::create($request->all());
			return redirect('downloads')->withSuccess('Download has been saved.');
		}else{
			abort(403);
		}
    }
	
    public function show(Download $download)
    {
		if(Auth::user()->role->role_permission('view_downloads')){
			if(Auth::user()->role->role_permission('view_downloads')->level == 'team'){
				$download = Download::where('id', $download->id)->first();
			}elseif(Auth::user()->role->role_permission('view_downloads')->level == 'self'){
				$download = Download::where('id', $download->id)->first();
			}
			return $download ? response()->download(public_path($download->document)) : abort(403);
		}else{
			abort(403);
		}
    }
	
    public function edit(Download $download)
    {
		if(Auth::user()->role->role_permission('edit_downloads')){
			if(Auth::user()->role->role_permission('edit_downloads')->level == 'team'){
				$download = Download::where('id', $download->id)->first();
			}elseif(Auth::user()->role->role_permission('edit_documents')->level == 'self'){
				$download = Download::where('id', $download->id)->first();
			}
			return $download ? view('download.edit', compact('download')) : abort(403);
		}else{
			abort(403);
		}
    }
	
    public function update(DownloadRequest $request, Download $download)
    {
		if(Auth::user()->role->role_permission('edit_downloads')){
			$download->update($request->all());
			return redirect('downloads')->withSuccess('Download has been updated.');
		}else{
			abort(403);
		}
    }
	
    public function destroy(Download $download)
    {
		if(Auth::user()->role->role_permission('delete_downloads')){
			$download->delete();
			return redirect('downloads')->withSuccess('Download has been deleted.');
		}else{
			abort(403);
		}
    }
}
