/**
  * Show the form for editing the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function edit($id)
 {
     $update = Update::find($id);
     if (Auth::check()) {
         $update = Update::withTrashed()->find($id);
     }
     return view('about.events.edit', compact('update'));
 }
 function create()
 {
     if (Session::has('user')) {
         $aLike = ['liked' => false, 'unliked' => false];
         $iLikeFromType = Input::get('like_from_type');
         $iToUserID = Input::get('to_user_id');
         $iUserID = Session::get('user')['id'];
         $iLikeFromID = Input::get('like_from_id');
         switch ($iLikeFromType) {
             case Like::LIKE_TYPE_USER:
                 $iFromWhereID = "user_id";
                 break;
             case Like::LIKE_TYPE_CHARACTER:
                 $iFromWhereID = "character_id";
                 break;
             case Like::LIKE_TYPE_FAMILY:
                 $iFromWhereID = "family_id";
                 break;
             case Like::LIKE_TYPE_SPECY:
                 $iFromWhereID = "specy_id";
                 break;
             case Like::LIKE_TYPE_PHOTO:
                 $iFromWhereID = "photo_id";
                 break;
             case Like::LIKE_TYPE_POST:
                 $iFromWhereID = "post_id";
                 break;
             case Like::LIKE_TYPE_MATE:
                 $iFromWhereID = "mate_id";
                 break;
             case Like::LIKE_TYPE_COMMENT:
                 $iFromWhereID = "comment_id";
         }
         //If no result on hasLiked, create like
         $oResultHasLike = self::hasLiked($iFromWhereID, $iToUserID, $iUserID, $iLikeFromType, $iLikeFromID);
         if (!$oResultHasLike) {
             $oResult = Like::create(['from_user_id' => $iUserID, 'to_user_id' => $iToUserID, 'like_type' => $iLikeFromType, $iFromWhereID => $iLikeFromID]);
             Update::create(['user_id' => $iUserID, 'update_type' => Update::UPDATE_TYPE_LIKE, 'like_id' => $oResult['id'], 'status' => Update::UPDATE_STATUS_ACTIVE]);
             if ($oResult) {
                 $aLike['liked'] = true;
                 return response()->json(['status' => true, 'message' => "Successfully liked", 'like' => json_encode($aLike)]);
             } else {
                 return response()->json(['status' => false, 'message' => "Something went wrong. Please try again later"]);
             }
         } else {
             $bResult = Like::where('id', $oResultHasLike['id'])->update(['status' => Like::LIKE_STATUS_DISLIKED_BY_USER]);
             Update::where('like_id', $oResultHasLike['id'])->update(['status' => Update::UPDATE_STATUS_DEACTIVATED_BY_USER]);
             if ($bResult) {
                 $aLike['unliked'] = true;
                 return response()->json(['status' => true, 'message' => "Successfully disliked", 'like' => json_encode($aLike)]);
             } else {
                 return response()->json(['status' => false, 'message' => "Something went wrong. Please try again later"]);
             }
         }
     }
 }
 public function remove()
 {
     $oMate = Mate::where('from_user_id', Input::get('from_user_id'))->where('status', Mate::MATE_STATUS_ACCEPTED_BY_USER)->orWhere('status', Mate::MATE_STATUS_ACCEPTED_BY_ADMIN)->first();
     $oMate->update(['status' => Mate::MATE_STATUS_REMOVED_BY_USER]);
     Update::where('mate_id', $oMate->id)->update(['status' => Update::UPDATE_STATUS_DEACTIVATED_BY_USER]);
     if ($oMate) {
         $aMate = $oMate->toArray();
         return response()->json(['status' => true, 'message' => "Successfully removed mate ", 'mate' => json_encode($aMate)]);
     } else {
         return response()->json(['status' => false, 'message' => "Something went wrong. Please try again"]);
     }
 }
 public function updateST(Request $request)
 {
     //  check that a file has been selected
     //
     if (!$request->hasFile('csv_update')) {
         $message = 'Please select a CSV file to update with.';
         Session::flash('flash_type', 'alert-danger');
         return Redirect::back()->with('flash_message', $message);
     }
     $csv_file = $request->file('csv_update');
     $filename = $csv_file->getClientOriginalName();
     $fileinfo = pathinfo($filename);
     // check the file has a .csv extention
     //
     if (strtoupper($fileinfo['extension']) !== 'CSV') {
         $message = 'You did not select a csv file.';
         Session::flash('flash_type', 'alert-danger');
         return Redirect::back()->with('flash_message', $message);
     }
     //  determine if the type is FH or ST
     //
     $valid = 0;
     if (strpos($fileinfo['filename'], 'ST') !== false) {
         $type = "ST";
         $valid = 1;
     }
     if (strpos($fileinfo['filename'], 'FH') !== false) {
         $type = "FH";
         $valid = 0;
     }
     // if not FH or ST the return error
     //
     if ($valid !== 1) {
         $message = 'This is not a valid ST update file.';
         Session::flash('flash_type', 'alert-danger');
         return Redirect::back()->with('flash_message', $message);
     }
     // get the databse name from the CSV file
     //
     $startpos = strrpos($fileinfo['filename'], '_') + 1;
     $endpos = strrpos($fileinfo['filename'], ' ');
     $len = $endpos - $startpos;
     $name = substr($fileinfo['filename'], $startpos, $len);
     $normal_name = $name . ' ' . $type;
     $name = str_replace(' ', '_', $name) . '_' . $type . '_' . 'farmbook2';
     $database = $name;
     // check if the database exists
     //
     $schema = 'information_schema';
     $otf = new \App\Database\OTF(['database' => $schema]);
     $db = DB::connection($schema);
     $data = $db->table('schemata')->select('schema_name')->where('schema_name', 'like', '%farmb%')->orderBy('schema_name')->lists("schema_name", "schema_name");
     $found = array_search($database, $data);
     //  the database does not exist
     //
     if ($found == false) {
         $message = 'The database does not exist - ' . $database;
         Session::flash('flash_type', 'alert-danger');
         return Redirect::back()->with('flash_message', $message);
     }
     // create update instance
     //
     $csv_updater = new CsvFileUpdater();
     // Import our csv file
     //
     if (!$csv_updater->update($csv_file, $database)) {
         $message = 'Error importing the file during update.';
         Session::flash('flash_type', 'alert-danger');
         return Redirect::back()->with('flash_message', $message);
     }
     // connect to the database
     //
     $dbname = $database;
     $otf = new \App\Database\OTF(['database' => $dbname]);
     $db = DB::connection($dbname);
     // totals
     $del = 0;
     $add = 0;
     $tot = 0;
     $lastupdate = "none";
     // time
     $now = \Carbon\Carbon::now('Africa/Johannesburg')->toDateTimeString();
     // setup log file - same name as csv with .log ext
     $destination_directory = storage_path('updates/tmp');
     $original_file_name = $csv_file->getClientOriginalName();
     $logfilename = $destination_directory . '/' . $original_file_name;
     $logfilename = str_replace('.csv', '.log', $logfilename);
     // File::put($logfilename, '');
     // setup log file - same name as csv with .log ext
     $destination_directory = storage_path('updates/tmp');
     $original_file_name = $csv_file->getClientOriginalName();
     $this->logfilename = $destination_directory . '/' . $original_file_name;
     $this->logfilename = str_replace('.csv', '.log', $logfilename);
     File::put($this->logfilename, '');
     //dd($logfilename);
     // check latest regDate in properties and delete old updates
     $propDate = Property::on($database)->orderBy('dtmRegDate', 'desc')->first();
     Update::on($database)->where('dtmRegDate', '<=', $propDate['dtmRegDate'])->delete();
     $echo = "last dtmRegDate in properties = " . $propDate['dtmRegDate'];
     File::append($this->logfilename, $echo . "\r\n");
     // get all update records
     //
     $updates = Update::on($database)->orderBy(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"))->orderBy('strKey')->orderBy('strTitleDeed')->get();
     // convert to array
     //
     $updatesA = $updates->toArray();
     $echo = 'updates to process = ' . $updates->count();
     File::append($this->logfilename, $echo . "\r\n");
     // process update records
     //
     for ($x = 0; $x <= sizeof($updatesA) - 1; $x++) {
         // check if there is an exact match on strKey
         //  $exact = Property::on($database)->where('strKey', $updatesA[$x]['strKey'])->where(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"), '<', Date($updatesA[$x]['dtmRegDate']))->get();
         $units = $this->noOfUnits($updatesA[$x]['strComplexNo']);
         $arr_units = $this->arrOfUnits($updatesA[$x]['strComplexNo']);
         $echo = '...........................................................................................................................................';
         File::append($this->logfilename, $echo . "\r\n");
         $echo = $updatesA[$x]['strKey'] . " - " . $updatesA[$x]['dtmRegDate'];
         File::append($this->logfilename, $echo . "\r\n");
         $echo = $units . ' units  -> ' . implode(" ", $arr_units);
         File::append($this->logfilename, $echo . "\r\n");
         $echo = '...........................................................................................................................................';
         File::append($this->logfilename, $echo . "\r\n");
         // fetch all property records for the complex where the reg date is older than the update
         $properties = Property::on($database)->orderBy('strKey')->where('strComplexName', $updatesA[$x]['strComplexName'])->where(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"), '<=', Date($updatesA[$x]['dtmRegDate']))->get();
         // check if there is an exact match on strKey with an earlier date
         $exact = Property::on($database)->where('strKey', $updatesA[$x]['strKey'])->where(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"), '<=', Date($updatesA[$x]['dtmRegDate']))->get();
         // if the strKey exists
         if ($exact->count() > 0) {
             $echo = ' - ' . $exact->count() . ' matching strKey in properties';
             File::append($this->logfilename, $echo . "\r\n");
             // check the updates are newer
             $anyupdates = Property::on($database)->where('strKey', $updatesA[$x]['strKey'])->where(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"), '<=', Date($updatesA[$x]['dtmRegDate']))->get();
             // if record already exists dont add it
             $dualowner = Property::on($database)->where('strKey', $updatesA[$x]['strKey'])->where('strIdentity', '=', $updatesA[$x]['strIdentity'])->where('strTitleDeed', '=', $updatesA[$x]['strTitleDeed'])->where(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"), '=', Date($updatesA[$x]['dtmRegDate']))->get();
             // echo 'anyupdates - ' . $anyupdates->count() . ' dualowner - ' . $dualowner->count() . '<br>';
             // check it is a new update and that it is not already in the database
             if ($anyupdates->count() > 0 && $dualowner->count() == 0) {
                 $echo = ' - ' . $anyupdates->count() . $updatesA[$x]['strKey'] . '  update ------------ exact key';
                 File::append($this->logfilename, $echo . "\r\n");
                 // if single unit
                 if ($units == 1) {
                     // dd($arr_units[0], $arr_units);
                     $this->newUnit($updatesA[$x], $arr_units[0], $database);
                 } else {
                     File::append($this->logfilename, $echo . "\r\n");
                     $this->newMultiUnit($updatesA[$x], $arr_units, $database);
                 }
             } else {
                 //echo ' - <b>' . $anyupdates->count() . $updatesA[$x]['strKey'] . '</b>-----------  NO updates' . "<br>";
                 $echo = ' No updates';
                 File::append($this->logfilename, $echo . "\r\n");
             }
             // strKey not found - search by units as may be in another key
         } else {
             $echo = 'No match for strKey in properties - search by unit';
             File::append($this->logfilename, $echo . "\r\n");
             $isFound = 0;
             for ($u = 0; $u < $units; $u++) {
                 $echo = " - Unit  " . ($u + 1) . " - " . $arr_units[$u];
                 File::append($this->logfilename, $echo . "\r\n");
                 $echo = " ---------------";
                 File::append($this->logfilename, $echo . "\r\n");
                 $isFound = $this->findUnit($updatesA[$x]['strComplexName'], $arr_units[$u], $properties, $updatesA[$x]['dtmRegDate'], $updatesA[$x]['strSellers'], $updatesA[$x]['strIdentity'], $database, $updatesA[$x]);
                 // properties could have been updated so fetch again
                 // fetch all property records for the complex where the reg date is older than the update
                 $properties = Property::on($database)->orderBy('strKey')->where('strComplexName', $updatesA[$x]['strComplexName'])->where(DB::raw("STR_TO_DATE(dtmRegDate, '%Y-%m-%d')"), '<=', Date($updatesA[$x]['dtmRegDate']))->get();
             }
             // below is done in findunit so not needed here
             if (!$isFound) {
                 // echo " -- add this record as it is not found anywhere so must be a newcomer <br>";
             }
         }
     }
     // dd end for debug so I can read log
     //dd("update completed - delete this dd()");
     $echo = '';
     File::append($this->logfilename, $echo . "\r\n");
     $echo = '...........................................................................';
     File::append($this->logfilename, $echo . "\r\n");
     $echo = 'update compleded successfully';
     File::append($this->logfilename, $echo . "\r\n");
     $message = 'Update completed.';
     Session::flash('flash_type', 'alert-success');
     return Redirect::back()->with('flash_message', $message);
 }
 public function update($id, Request $request)
 {
     $validator = Validator::make($request->all(), ['title' => 'required | min:3', 'headline' => 'sometimes|min:3', 'body' => 'sometimes | min:3', 'attachments' => 'required', 'published' => 'required|date', 'expires' => 'sometimes|after:' . $request->published]);
     if ($validator->passes()) {
         $post = Update::withTrashed()->find($id);
         $post->title = $request->title;
         $post->content = $request->body;
         $post->published_on = $request->published;
         $post->headline = $request->headline;
         if (isset($request->expires)) {
             $post->expires_on = $request->expires;
         }
         $post->category_id = $request->category;
         if ($post->save()) {
             if ($request->delete) {
                 foreach ($request->delete as $deletion) {
                     $attachment = Attachment::find($deletion);
                     $attachment->delete();
                 }
             }
             $request->featured = $request->featured == '' ? null : $request->featured;
             $post->featured = $request->featured;
             $post->save();
             if ($request->destroy) {
                 $post->delete();
             } else {
                 if (!is_null($post->deleted_at)) {
                     $post->restore();
                 }
             }
             $files = $request->file('attachments');
             if (count($files)) {
                 if (!is_dir($this->upload_dir . $post->id)) {
                     mkdir($this->upload_dir . $post->id);
                 }
                 $success = true;
                 foreach ($files as $file) {
                     if (!is_null($file) && $file->isValid()) {
                         if ($file->move($this->upload_dir . $post->id, $file->getClientOriginalName())) {
                             $attachment = new Attachment();
                             $attachment->filename = $file->getClientOriginalName();
                             $attachment->size = $file->getClientSize();
                             $attachment->update_id = $post->id;
                             $attachment->type = pathinfo($this->upload_dir . $post->id . '/' . $file->getClientOriginalName(), PATHINFO_EXTENSION);
                             $attachment->save();
                         } else {
                             $success = false;
                         }
                     }
                 }
                 if ($success) {
                     return redirect('about/galleries/' . $post->id . '/edit');
                 }
             }
             return redirect('about/galleries');
         } else {
             return 'Error';
         }
     } else {
         return redirect('about/galleries/' . $post->id . '/edit')->withInput();
     }
 }
 public function boot()
 {
     view()->composer('partials._nav', function ($view) {
         $view->with('latest', \App\Update::latest()->first());
     });
 }
 public function get_updates_from_user($user)
 {
     $id = $user->id;
     $suggested_updates = Update::latest('created_at')->Where('user_id', $user->id)->get();
     return $suggested_updates;
 }
 function create(Request $request)
 {
     if (Session::has('user')) {
         //Check the type of comment type to determine what id is to be inserted [photo_id, character_id, family_id, specy_id, post_id, mate_id]
         $iFromType = Input::get('comment-from-type');
         $iFromWhereID = null;
         $iCommentPhotoID = 0;
         $aComment = [];
         switch ($iFromType) {
             case Comment::COMMENT_FROM_TYPE_USER:
                 $iFromWhereID = "user_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_CHARACTER:
                 $iFromWhereID = "character_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_FAMILY:
                 $iFromWhereID = "family_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_SPECY:
                 $iFromWhereID = "specy_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_PHOTO:
                 $iFromWhereID = "photo_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_POST:
                 $iFromWhereID = "post_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_MATE:
                 $iFromWhereID = "mate_id";
                 break;
         }
         $oComment = Comment::create(['from_user_id' => Session::get('user')['id'], 'to_user_id' => Input::get('comment-to-user-id'), 'comment_text' => Input::get('comment-text'), 'status' => Comment::COMMENT_STATUS_DEFAULT, 'comment_type' => $request->file('comment-photo') != null ? Comment::COMMENT_TYPE_PHOTO : Comment::COMMENT_TYPE_TEXT, 'comment_from_type' => Input::get('comment-from-type'), $iFromWhereID => Input::get('comment-from-id'), 'comment_photo_id' => $iCommentPhotoID]);
         //Check if there's a file
         if ($request->file('comment-photo') != null) {
             $sInputImageName = str_replace(' ', '_', Input::get('comment-to-user-id') . '_' . $request->file('comment-photo')->getClientOriginalName());
             $sImageName = rand(1, 1000000) . '_' . Session::get('user')['id'] . '_' . $sInputImageName;
             $request->file('comment-photo')->move(base_path() . '/public/' . Photo::PHOTO_LINK_COMMENT, $sImageName);
             $oPhoto = Photo::create(['user_id' => Session::get('user')['id'], 'photo_type' => Photo::PHOTO_TYPE_COMMENT, 'photo_link' => Photo::PHOTO_LINK_COMMENT . $sImageName, 'status' => Photo::PHOTO_STATUS_DEFAULT]);
             $iCommentPhotoID = $oPhoto->toArray()['id'];
             if ($oPhoto) {
                 Comment::where('id', $oComment->toArray()['id'])->update(['comment_photo_id' => $iCommentPhotoID]);
             }
         }
         if ($oComment) {
             $aComment = Comment::where('id', $oComment->toArray()['id'])->first()->toArray();
             $aNotification = Notification::create(['from_user_id' => Session::get('user')['id'], 'to_user_id' => Input::get('comment-to-user-id'), 'notification_type' => Notification::NOTIFICATION_TYPE_COMMENT, 'status' => Notification::NOTIFICATION_STATUS_ACTIVE, 'comment_id' => $aComment['id']]);
             Update::create(['user_id' => Session::get('user')['id'], 'update_type' => Update::UPDATE_TYPE_COMMENT, 'comment_id' => $aComment['id'], 'status' => Update::UPDATE_STATUS_ACTIVE]);
             //FOR DISPLAY
             $aComment['from_user'] = User::where('id', Session::get('user')['id'])->first()->toArray();
             $aComment['photo_comment'] = $aComment['comment_photo_id'] > 0 ? Photo::where('id', $aComment['comment_photo_id'])->first()->toArray() : [];
         }
         $view = view('users.comments.partials.partial-comment-owner')->with('aComment', $aComment);
         if ($aComment) {
             return response()->json(['status' => true, 'message' => "Successfully submitted comment", 'view' => (string) $view]);
         } else {
             return response()->json(['status' => false, 'message' => "Something went wrong. Please try again"]);
         }
     }
 }
 public function update_status_activate(Request $request)
 {
     $result = Character::where('id', Input::get('character_id'))->update(['status' => Character::CHARACTER_STATUS_ENABLED_BY_USER]);
     $aCharacter = Character::where('id', Input::get('character_id'))->first()->toArray();
     Update::where('character_id', $aCharacter['id'])->update(['status' => Update::UPDATE_STATUS_ACTIVATED_BY_USER]);
     $view = view('users.characters.partials.partials-active-list-show-characters')->with('aCharacter', $aCharacter);
     if ($result) {
         return response()->json(['view' => (string) $view, 'status' => true, 'message' => "Successfully activated character"]);
     } else {
         echo json_encode(array('status' => false, 'message' => "Something went wrong. Please try again later"));
     }
     die;
 }
 /**
  * Update the specified resource in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function update($id, Request $request)
 {
     $post = Update::withTrashed()->find($id);
     $post->title = $request->title;
     $post->content = $request->body;
     $post->published_on = $request->published;
     $post->headline = $request->headline;
     if (isset($request->expires)) {
         $post->expires_on = $request->expires;
     }
     $post->category_id = $request->category;
     if ($post->save()) {
         if ($request->delete) {
             foreach ($request->delete as $deletion) {
                 $attachment = Attachment::find($deletion);
                 $attachment->delete();
             }
         }
         $request->featured = $request->featured == '' ? null : $request->featured;
         $post->featured = $request->featured;
         $post->save();
         if ($request->destroy) {
             $post->delete();
         } else {
             if (!is_null($post->deleted_at)) {
                 $post->restore();
             }
         }
         $files = $request->file('attachments');
         if (count($files)) {
             if (!is_dir($this->upload_dir . $post->id)) {
                 mkdir($this->upload_dir . $post->id);
             }
             $success = true;
             foreach ($files as $file) {
                 if (!is_null($file) && $file->isValid()) {
                     if ($file->move($this->upload_dir . $post->id, $file->getClientOriginalName())) {
                         $attachment = new Attachment();
                         $attachment->filename = $file->getClientOriginalName();
                         $attachment->size = $file->getClientSize();
                         $attachment->update_id = $post->id;
                         $attachment->type = pathinfo($this->upload_dir . $post->id . '/' . $file->getClientOriginalName(), PATHINFO_EXTENSION);
                         $attachment->save();
                     } else {
                         $success = false;
                     }
                 }
             }
             if ($success) {
                 return redirect('academylife/sports-news/' . $post->id . '/edit');
             }
         }
         return redirect('academylife/sports-news');
     } else {
         return 'Error';
     }
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy(Update $update)
 {
     $update->delete();
     return redirect()->route('update.index');
 }