<?php

   namespace App\Http\Controllers;

   use App\Object;
   use App\User;
   use \Spatie\Activitylog\Models\Activity;
   use Illuminate\Http\Request;

   class ActivityLogController extends Controller
   {
      /**
       * Display a listing of the resource.
       *
       * @return \Illuminate\Http\Response
       */
      public function index()
      {
         $logs = Activity::orderBy('created_at', 'reverse')->paginate( 10 );

         return view( 'activitylog.index', compact( 'logs') );
      }

      /**
       * Search for a specific log
       *
       * @param  \Illuminate\Http\Request  $request
       * @return \Illuminate\Http\Response
       */
      public function search(Request $request) {
         $searchType = $request->searchType;
         if($searchType === "object" || $searchType === "string" || $searchType === "user") {
            // Proceed!
         } else {
            $searchType = "string";
         }
         switch ( $searchType ) {
            case "object":
               $object = Object::findShorthand( $request->search );
               if ( $object instanceof Object ) {
                  $logs = Activity::where( 'subject_type', 'App\Object' )->where( 'subject_id', $object->id )->orderBy('created_at', 'reverse')->paginate( 10 );
               } else {
                  $logs = collect();
               }
               break;
            case "user":
               $user = User::where( 'name', 'LIKE', "%" . $request->search . "%" )->orWhere( 'email', 'LIKE', "%" . $request->search . "%" )->first();
               if ( $user instanceof User ) {
                  $logs = Activity::where( 'causer_type', 'App\User' )->where( 'causer_id', $user->id )->orderBy('created_at', 'reverse')->paginate( 10 );
               } else {
                  $logs = collect();
               }
               break;
            case "string":
               $logs = Activity::where( 'description', 'LIKE', '%' . $request->search . '%' )->orderBy('created_at', 'reverse')->paginate( 10 );
               break;
         }
         return view( 'activitylog.index', compact( 'logs') );
      }
   }