<?php

   namespace App\Http\Controllers;


   use DB;
   use Gate;
   use Request;
   use App\Role;
   use App\Resource;
   use App\Http\Requests;
   use App\Http\Requests\ResourceRequest;
   use Illuminate\Http\Request as HttpRequest;
   use Intervention\Image\ImageManagerStatic as Image;

   class ResourcesController extends Controller
   {
      /**
       * Display a listing of the resource.
       *
       * @return \Illuminate\Http\Response
       */
      public function index()
      {
         if (Gate::denies('viewer')) {
            abort(403, 'You cannot view resources.');
         }
         if ($search = Request::get('q')) {
            $searchArray = preg_split('!\s+!', $search);

            //            DB::listen(function($sql, $bindings, $time) { dd($sql, $bindings, $time); });
            $resources = Resource::with( 'roles' )
                                 ->where( function ( $query ) use ( $searchArray ) {
                                    foreach ( $searchArray as $search ) {
                                       $query->where( function ( $subQuery ) use ( $search ) {
                                          $subQuery->orWhere( 'name', 'LIKE', "%$search%" )
                                                   ->orWhere( 'email', 'LIKE', "%$search%" )
                                                   ->orWhere( 'phone', 'LIKE', "%$search%" )
                                                   ->orWhere( 'company', 'LIKE', "%$search%" )
                                                   ->orWhere( 'notes', 'LIKE', "%$search%" )
                                                   ->orWhere( 'skills', 'LIKE', "%$search%" )
                                                   ->orWhere( 'city', 'LIKE', "%$search%" )
                                                   ->orWhere( 'state', 'LIKE', "%$search%" )
                                                   ->orWhere( 'project_name', 'LIKE', "%$search%" )
                                                   ->orWhereHas( 'roles', function ( $rolesQuery ) use ( $search ) {
                                                      $rolesQuery->where( 'role_name', 'LIKE', "%$search%" );
                                                   } );
                                       } );
                                    }
                                 } )->get();

            $idArray = [];

            foreach($resources as $key => $item) {
               $idArray[] = $item->id;
            }

            if(!$idArray) {
               $stuff = "No search results for $search.";
               $resources = Resource::get()->sortBy('name');
               return view( 'resources.index', compact( 'resources', 'stuff' ));
            }

            array_unique($idArray);

            $resources = Resource::whereIn('id', $idArray)
                                 ->get()
                                 ->sortBy('name');

            return view( 'resources.index', compact( 'resources' ));

         } else {
            $resources = Resource::get()->sortBy('name');
            return view( 'resources.index', compact( 'resources' ));
         }
      }

      /**
       * Show the form for creating a new resource.
       *
       * @return \Illuminate\Http\Response
       */
      public function create()
      {
         if (Gate::denies('regular')) {
            abort(403, 'You cannot create resources.');
         }
         $roles = Role::lists('role_name', 'id')->toArray();
         return view('resources.create', compact('roles'));
      }


      public function store(ResourceRequest $request)
      {
         if (Gate::denies('regular')) {
            abort(403, 'You cannot store resources.');
         }
         $resource = Resource::create($request->all());

         $resource->roles()->attach( $request->input('role_list') );

         return redirect('resources/' . $resource->id);
      }

      public function show(Resource $resource)
      {
         if (Gate::denies('viewer')) {
            abort(403, 'You cannot view resources.');
         }

         return view('resources.show', compact('resource'));
      }

      public function edit(Resource $resource)
      {
         if (Gate::denies('regular')) {
            abort(403, 'You cannot edit resources.');
         }
         $roles = Role::lists('role_name', 'id')->toArray();

         return view('resources.edit', compact('resource', 'roles'));
      }


      public function update(Resource $resource, ResourceRequest $request)
      {
         if (Gate::denies('regular')) {
            abort(403, 'You cannot update resources.');
         }
         $resource->update($request->all());
         $roleList = $request->input('role_list') ? : [];
         $resource->roles()->sync( $roleList );
         return redirect('resources/' . $resource->id);
      }

      public function upload( $id, HttpRequest $request ) {
         if (Gate::denies('regular')) {
            abort(403, 'You cannot update resources.');
         }
         $this->validate($request, [
            'imageUpload' => 'required|mimes:jpg,jpeg,png,bmp'
         ]);

         $file = $request->file('imageUpload');
         $image = Image::make($file)->orientate();

         // make the original picture, save it
         $name = time() . $file->getClientOriginalName();

         $image->fit(500)
               ->save(public_path() . "/img/$name", 80)
               ->fit(200)
               ->save(public_path() . "/img/thumb-$name", 70);

         $resource = Resource::find($id);

         $resource->update(['profilepic' => "$name"]);
      }

      public function destroy(Resource $resource)
      {
         if (Gate::denies('admin')) {
            abort(403, 'You cannot delete resources.');
         }
         $resource->delete();
         return redirect('resources');
      }

   }