<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Paste;
use Auth;
use App\Log;
use App\User;
use App\PasteRedirect;
use Redirect;
use \Input;
use \Hash;
use RoleId;
use Session;
use Cookie;
use DB;
use Carbon\Carbon;
use ViKon\Diff\Diff;

class AdminApiController extends Controller{

	private function jsonError($msg = null){
		$r = (is_null($msg) ? ['status' => 'err'] : ['status' => 'err', 'msg' => $msg]);
		return response()->json($r);
	}

	public function change_owner(Request $request){
		if($request->isMethod('post')){
			$myUser = newGetUser();
			if(is_null($myUser) || !$myUser->isManager(true)){
				return response()->json(['status' => 'err']);
			}

			if(empty(Input::get('id'))){
				return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
			}

			$id = Input::get('id');
			$username = Input::get('username');
			$uid = 0;
			$paste = Paste::find($id);
			if(is_null($paste)){
				return response()->json(['status' => 'err', 'msg' => 'Paste does not exist.']);
			}

			if(!empty($username)){
				$newOwner = User::where('username', $username)->first();


				if(is_null($newOwner)){
					return response()->json(['status' => 'err', 'msg' => 'User does not exist.']);
				}

				$uid = $newOwner->id;
				$newOwner->pastes = $newOwner->pastes + 1;
				$newOwner->save();
			}
			if($paste->created_by != 0){
				$oldOwner = User::find($paste->created_by);
				if(!is_null($oldOwner)){
					$oldOwner->pastes = $oldOwner->pastes - 1;
					$oldOwner->save();
				}
			}
			DB::table('pastes')->where('id', $id)->update(['created_by' => $uid]);

			return response()->json(['status' => 'done', 'msg' => 'done']);
		}else{
			return response()->json(['status' => 'err', 'msg' => 'The request method '.$request->method().' is not accepted.']);
		}
	}

	public function change_views(Request $request){
		if($request->isMethod('post')){
			$myUser = newGetUser();
			if(is_null($myUser) || !$myUser->isManager(true)){
				return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
			}

			if(empty(Input::get('id'))){
				return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
			}

			$id = Input::get('id');
			$views = Input::get('views');

			if(DB::table('pastes')->where('id', $id)->count() < 1){
				return response()->json(['status' => 'err', 'msg' => 'That dox does not exist.']);
			}

			if(!is_numeric($views)){
				return response()->json(['status' => 'err', 'msg' => 'Invalid view count.']);
			}else{
				if($views < -1000000 || $views > 1000000){
					return response()->json(['status' => 'err', 'msg' => 'Invalid view count.']);
				}
			}

			DB::table('pastes')->where('id', $id)->update(['views' => $views]);

			return response()->json(['status' => 'done', 'msg' => 'done']);
		}else{
			return response()->json(['status' => 'err', 'msg' => 'The request method '.$request->method().' is not accepted.']);
		}
	}
    public function switch_maintenance(){
        $myUser = newGetUser();
        if($myUser == null){
            return response()->json(['status' => 'err', 'msg' => 'Not logged in.']);
		// I have been given permission to do this by Operator
		// This condition checks if the user is neither a manager+ nor a developer
		// I have tested this with all roles. Only Admin, Manager and Developer role can enable this
        }else if(!$myUser->isManager(true) && !$myUser->isDeveloper()){
            return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
        }

        $mtn = DB::table('site_settings')->where('setting', 'maintenance')->get();
        if($mtn == null){
            return response()->json(['status' => 'err', 'msg' => 'Row not found.']);
        }
        $mtn = $mtn[0]->intval;
        if($mtn == 1){
            $mtn = 0;
        }else{
            $mtn = 1;
        }
		DB::table('site_settings')->where('setting', 'maintenance')->update(['intval' => $mtn]);
		
		if($myUser->role > RoleId::COUNCIL){
			Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Turned maintenance ' . ($mtn == 1 ? 'on'  : 'off')]);
		}
        return response()->json(['status' => 'done', 'msg' => 'Maintenance toggled.', 'enabled' => $mtn]);
    }
	
	// Switching Paste Detection
	public function switch_paste_detection(){
        $myUser = newGetUser();
        if($myUser == null){
            return response()->json(['status' => 'err', 'msg' => 'Not logged in.']);
        }else if(!$myUser->isManager(true) && !$myUser->isDeveloper()){
            return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
        }

        $mtn = DB::table('site_settings')->where('setting', 'pastedetect')->get();
        if($mtn == null){
            return response()->json(['status' => 'err', 'msg' => 'Row not found.']);
        }
        $mtn = $mtn[0]->intval;
        if($mtn == 1){
            $mtn = 0;
        }else{
            $mtn = 1;
        }
		DB::table('site_settings')->where('setting', 'pastedetect')->update(['intval' => $mtn]);
		
		if($myUser->role > RoleId::COUNCIL){
			Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Turned Paste Detection ' . ($mtn == 1 ? 'on'  : 'off')]);
		}
        return response()->json(['status' => 'done', 'msg' => 'Paste Detection toggled.', 'enabled' => $mtn]);
    }

	// Switching Anon Posting
	public function switch_no_anon(){
		$myUser = newGetUser();
		if($myUser == null){
			return response()->json(['status' => 'err', 'msg' => 'Not logged in.']);
		}else if(!$myUser->isManager(true) && !$myUser->isDeveloper()){
			return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
		}

		$mtn = DB::table('site_settings')->where('setting', 'noanon')->get();
		if($mtn == null){
			return response()->json(['status' => 'err', 'msg' => 'Row not found.']);
		}
		$mtn = $mtn[0]->intval;
		if($mtn == 1){
			$mtn = 0;
		}else{
			$mtn = 1;
		}
		DB::table('site_settings')->where('setting', 'noanon')->update(['intval' => $mtn]);
		
		if($myUser->role > RoleId::COUNCIL){
			Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Turned Anon Posting ' . ($mtn == 1 ? 'on'  : 'off')]);
		}
		return response()->json(['status' => 'done', 'msg' => 'Anon Posting ', 'disabled' => $mtn]);
	}
	
	// Switching Register Toggle
	public function switch_register_toggle(){
		$myUser = newGetUser();
		if($myUser == null){
			return response()->json(['status' => 'err', 'msg' => 'Not logged in.']);
		}else if(!$myUser->isManager(true) && !$myUser->isDeveloper()){
			return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
		}

		$mtn = DB::table('site_settings')->where('setting', 'regdisable')->get();
		if($mtn == null){
			return response()->json(['status' => 'err', 'msg' => 'Row not found.']);
		}
		$mtn = $mtn[0]->intval;
		if($mtn == 1){
			$mtn = 0;
		}else{
			$mtn = 1;
		}
		DB::table('site_settings')->where('setting', 'regdisable')->update(['intval' => $mtn]);
		
		if($myUser->role > RoleId::COUNCIL){
			Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Turned User Registration ' . ($mtn == 1 ? 'on'  : 'off')]);
		}
		return response()->json(['status' => 'done', 'msg' => 'Anon Posting ', 'disabled' => $mtn]);
	}

	public function announcements(Request $request){
		if($request->isMethod('post')){
			$myUser = newGetUser();
			if(is_null($myUser) || !$myUser->isManager(true)){
				return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
			}

			if(empty(Input::get('ann'))){
				return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
			}

			$ann = Input::get('ann');
			$text = Input::get('text');
			if(empty($text)){
				$text = null;
			}
			$link = (empty(Input::get('link')) ? null : Input::get('link'));
			$color = Input::get('color');

			if($ann != 1 && $ann != 2 && $ann != 3 && $ann != 4){
				return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
			}

			if($link != null && substr($link, 0, 4) != "http"){
				$link = null;
			}

			if(strlen($color) != 6 && ctype_xdigit($color)){
				return response()->json(['status' => 'err', 'msg' => 'Invalid color.']);
			}

			if($myUser->role > RoleId::COUNCIL){
				Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Edited announcement ' . $ann]);
			}

			DB::table('site_announcements')->where('name', 'announcement'.$ann)->update(['text' => $text, 'link' => $link, 'colour' => $color]);

			return response()->json(['status' => 'done', 'msg' => 'done']);
		}else{
			return response()->json(['status' => 'err', 'msg' => 'The request method '.$request->method().' is not accepted.']);
		}
	}

	public function count() {
		$myUser = newGetUser();

		if ($myUser == null || !$myUser->isDeveloper(true)) {
			abort(403);
            return null;
		}

        $editReviewCount =
            DB::table('edit_review')
                ->where('handled', 0)
                ->count();

        $flagsCount =
            DB::table('flags')
                ->where('status', 0)
                ->count();

		if ($myUser->isAdmin(true)) {
            $pastesCount =
                DB::table('pastes')
                    ->where(['hidden' => 0, 'blacklist' => 1])
                    ->count();

			return response()->json([
                'count' => $editReviewCount + $pastesCount + $flagsCount,
            ]);
		} else {
            return response()->json([
                'count' => $editReviewCount + $flagsCount,
            ]);
        }
	}

	public function hide_comment(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}

		$myUser = newGetUser();
		if($myUser == null || !$myUser->isDeveloper(true)){ // dev +
			return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
		}
		$id = Input::get('id');
			
		if (!is_numeric($id)) {
			return response()->json(['status' => 'err', 'msg' => 'Invalid comment ID.']);
		}

		$comment = DB::table('comments')->where('id', $id)->limit(1)->get();

		if($comment->count() < 1){
			return response()->json(['status' => 'err', 'msg' => 'Invalid comment ID.']);
		}
		$comment = $comment[0];

		DB::table('comments')->where('id', $id)->update(['hidden' => !$comment->hidden]);

		if($comment->created_by != 0){
			$comment->hidden == 1 ? DB::table('users')->where('id', $comment->created_by)->increment('comments') : DB::table('users')->where('id', $comment->created_by)->decrement('comments');
		}
		$comment->hidden == 1 ? DB::table('pastes')->where('id', $comment->doxId)->increment('comments') : DB::table('pastes')->where('id', $comment->doxId)->decrement('comments');

		return response()->json(['status' => 'done', 'msg' => 'done', 'hidden' => !$comment->hidden]);
		
	}

	public function edits(Request $request){
		$myUser = newGetUser();
		if($request->isMethod('post')){
			if (is_null($myUser)) {
				return response()->json(['status' => 'err']);
			} else if(!$myUser->isDeveloper(true)) {
				return response()->json(['status' => 'err']);
			}
			$doxId = Input::get('doxid');

			$dox = DB::table('pastes')->where('id', $doxId)->get();

			if($dox->count() < 1){
				return response()->json(['status' => 'err', 'msg' => 'That paste was not found.']);
			}

			$dox = $dox[0];

			$edit = DB::table('edit_review')->where(['doxId' => $dox->id, 'handled' => '0'])->get();
			
			if($edit->count() < 1){
				return response()->json(['status' => 'err', 'msg' => 'This dox is not pending review or has already been handled by another admin.']);
			}
			$edit = $edit[0];

			if(Input::get('action') == "accept"){

				DB::table('edit_review')->where('doxId', $doxId)->update(['handled' => 1, 'datehandled' => floor(microtime(true) * 1000), 'handledby' => $myUser->id, 'action' => 1]);

				if(!$dox->hidden){
					DB::table('notifications')->insert(['uid' => $dox->created_by, 'pasteId' => $dox->id, 'type' => 1, 'text' => 'Edit request accepted for <a href="/upload/' . $dox->link . '">' . $dox->title . '</a>.', 'date' => floor(microtime(true) * 1000)]);
				}

				DB::table('pastes')->where('id', $doxId)->update(['content' => $edit->newpost, 'last_edited' => floor(microtime(true) * 1000)]);
				
				if($myUser->role > RoleId::COUNCIL){
					Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Accepted edit for paste: <a href="/upload/' . $dox->link . '">' . htmlspecialchars($dox->title) . '</a>']);
				}

				return response()->json(['status' => 'done', 'msg' => 'Accepted edit request.']);

			}else if(Input::get('action') == "deny"){

				DB::table('edit_review')->where('doxId', $doxId)->update(['handled' => 1, 'datehandled' => floor(microtime(true) * 1000), 'handledby' => $myUser->id, 'action' => 0]);

				if(!$dox->hidden){
					DB::table('notifications')->insert(['uid' => $dox->created_by, 'pasteId' => $dox->id, 'type' => 0, 'text' => 'Edit request denied for <a href="/upload/' . $dox->link . '">' . $dox->title . '</a>.', 'date' => floor(microtime(true) * 1000)]);
				}

				if($myUser->role > RoleId::COUNCIL){
					Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Denied edit for paste: <a href="/upload/' . $dox->link . '">' . htmlspecialchars($dox->title) . '</a>']);
				}

				return response()->json(['status' => 'done', 'msg' => 'Denied edit request.']);
			}
			return response()->json(['status' => 'err', 'msg' => 'Invalid request.']);
		}

		return response()->json(['status' => 'err', 'msg' => 'The request method '.$request->method().' is not accepted.']);
	}

	public function blacklist(Request $request) {
		if (!$request->isMethod('post')) {
            return response()->json(['status' => 'err', 'msg' => 'The request method ' . $request->method() . ' is not accepted.']);
        }

        $myUser = newGetUser();
        if(is_null($myUser)){
            return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
        }else if(!$myUser->isAdmin(true)){
            return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
        }

        if(empty(Input::get('type'))){
            return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
        }

        $type = Input::get('type');

        if($type == 'add'){
            $word = Input::get('word');
            if(empty($word)){
                return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
            }
            if(DB::table('word_blacklist')->where('word', $word)->count() > 0){
                return response()->json(['status' => 'err', 'msg' => 'That word is already blacklisted.']);
            }
            if(strlen($word) > 255){
                return response()->json(['status' => 'err', 'msg' => 'Word is too long.']);
            }

            DB::table('word_blacklist')->insert(['word' => $word, 'date' => floor(microtime(true) * 1000)]);
        }else{
            $id = Input::get('id');
            if(empty($id)){
                return response()->json(['status' => 'err', 'msg' => 'Invalid params.']);
            }
            $bl = DB::table('word_blacklist')->where('id', $id)->first();
            if(is_null($bl)){
                return $this->jsonError();
            }
            if(!is_null($bl->blid)){ // dont allow if it is a proper blaclist
                return $this->jsonError();
            }
            DB::table('word_blacklist')->where('id', $id)->delete();
            return response()->json(['status' => 'done', 'msg' => 'success']);
        }


        return response()->json(['status' => 'done', 'msg' => 'done']);
	}

	public function addNewRank(Request $request){
		if (!$request->isMethod('post')) {
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}

		$myUser = newGetUser();
		if (is_null($myUser) || !$myUser->isAdmin(true)) {
			return response()->json(['status' => 'err']);
		}

		$rankName =  Input::get('rankName');
		$rankText =  Input::get('rankText');
		$rankColor = Input::get('rankColor');

		if(empty($rankName) || !ctype_alnum($rankName) || strlen($rankName) > 20){
			return response()->json(['status' => 'err', 'msg' => 'Invalid rank name.']);
		}
		if(empty($rankText) || !ctype_alnum($rankText) || strlen($rankText) > 20){
			return response()->json(['status' => 'err', 'msg' => 'Invalid rank text.']);
		}
		if(empty($rankColor) || !ctype_xdigit($rankColor) || strlen($rankColor) != 6){
			return response()->json(['status' => 'err', 'msg' => 'Invalid rank color.']);
		}

		$ranks = DB::table('roles')->get();
		if($ranks->where('name', $rankName)->count() > 0){
			return response()->json(['status' => 'err', 'msg' => 'A role with this name already exists.']);
		}

		DB::table('roles')->insert(['name' => $rankName, 'text' => $rankText, 'color' => $rankColor]);
		return response()->json(['status' => 'done', 'msg' => 'done']);
	}

	public function delRank(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}
		$myUser = newGetUser();
		if(is_null($myUser) || !$myUser->isAdmin()){
			return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
		}
		$rankId = Input::get('rankId');
		
		if(empty($rankId)){
			return response()->json(['status' => 'err', 'msg' => 'Role does not exist.']);
		}

		if($rankId <= 3){
			return response()->json(['status' => 'err', 'msg' => 'Cannot delete this role.']);
		}

		if(DB::table('roles')->where('id', $rankId)->count() == 0){
			return response()->json(['status' => 'err', 'msg' => 'Role does not exist.']);
		}
		DB::table('roles')->where('id', $rankId)->delete();
		DB::table('users')->where('role', $rankId)->update(['role' => '0']);
		return response()->json(['status' => 'done', 'msg' => 'done']);
	}

	public function editBan(Request $request){
		if(!$request->isMethod('post')){
			return $this->jsonError();
		}

		$myUser = newGetUser();

		if(is_null($myUser) || !$myUser->isDeveloper(true)){
			return $this->jsonError();
		}

		$id = Input::get('doxid');

		if(empty($id)){
			return $this->jsonError();
		}

		$paste = Paste::where('id', $id)->first();

		if($paste == null){
			return $this->jsonError();
		}
		
		$paste->editbanned = !$paste->editbanned;
		$paste->save();

		return response()->json(['status' => 'done', 'editban' => $paste->editbanned]);
	}

	public function add_to_blacklist(Request $request){
		if(!$request->isMethod('post')){
			return $this->jsonError();
		}

		$myUser = newGetUser();
		if(is_null($myUser) || !$myUser->isAdmin()){
			return $this->jsonError();
		}

		$alias = $request->input('alias');
		$email = $request->input('email');
		$words = $request->input('words');
		$info = $request->input('info');
		$time = floor(microtime(true) * 1000);
		
		if(strlen($alias) > 50){ // checks
			return $this->jsonError('Alias max length 50');
		}
		if(strlen($email) > 255){
			return $this->jsonError('Email max length 255');
		}
		if(strlen($info) > 300){
			return $this->jsonError('Info max length 300');
		} // -
		
		$words = preg_split('/\r\n|[\r\n]/', $words);
		
		if(count($words) > count(array_unique($words))){ // check if there are duplicate words
			return $this->jsonError('Duplicate blacklist words');
		}
		if(count($words) > 10){ // chech kfi too many words
			return $this->jsonError('Too many words, max 10');
		}
		
		$duplicate = DB::table('word_blacklist')->whereIn('word', $words)->first();
		if(!is_null($duplicate)){ // check if blacklisted word is alaready in table
			return $this->jsonError('"'.$duplicate->word.'" is already in the blacklist');
		}

		$w = [];

		$blid = DB::table('blacklist')->insertGetId(['alias' => $alias, 'email' => $email, 'info' => $info]);
		foreach($words as $word){ // sort out blacklsitged words
			array_push($w, ['blid' => $blid, 'word' => $word, 'date' => $time]);
		}
		


		// all, good, execute
		DB::table('word_blacklist')->insert($w);

		return response()->json(['status' => 'done']);
	}

	public function remove_from_blacklist(Request $request){
		if(!$request->isMethod('post')){
			return $this->jsonError();
		}

		$myUser = newGetUser();
		if(is_null($myUser) || !$myUser->isAdmin()){
			return $this->jsonError();
		}

		$id = $request->input('id');

		$time = floor(microtime(true) * 1000);
		if(empty($id) || !is_numeric($id)){
			return $this->jsonError();
		}

		// all, good, execut
		DB::transaction(function() use ($id){
			DB::table('blacklist')->where('id', $id)->delete();
			DB::table('word_blacklist')->where('blid', $id)->delete();
		});

		return response()->json(['status' => 'done']);
	}

	// Flagger Start - Reiko, Mar 18th 2024.
	public function add_to_flagger(Request $request){
		if(!$request->isMethod('post')){
			return $this->jsonError();
		}

		$myUser = newGetUser();
		if(is_null($myUser) || !$myUser->isAdmin()){ // only admins allowed
			return $this->jsonError();
		}

		$flag_word = $request->input('flag_word'); // name of input 
		$time = date("Y-m-d H:i:s", floor(microtime(true)));
		
		if(strlen($flag_word) > 50){ // checks
			return $this->jsonError('Max Length 50 for flagged words');
		}
		
		$flag_word = preg_split('/\r\n|[\r\n]/', $flag_word);
		
		if(count($flag_word) > count(array_unique($flag_word))){ // check if there are duplicate words
			return $this->jsonError('Duplicate blacklist words');
		}
		if(count($flag_word) > 10){ // chech if too many words
			return $this->jsonError('Too many words, max 10');
		}
		
		$duplicate = DB::table('flag_words')->whereIn('word', $flag_word)->first();
		if(!is_null($duplicate)){ // check if flagged word is alaready in table
			return $this->jsonError('"'.$duplicate->word.'" is already in the blacklist');
		}

		$w = [];

		foreach($flag_word as $word){ // sort out flagged words
			array_push($w, ['word' => $word, 'created_at' => $time]);
		}

		// all, good, execute
		DB::table('flag_words')->insert($w);

		return response()->json(['status' => 'done']);
	}
	// Flagger End

	// Flagger Remove Start  - Reiko, Mar 18th 2024.
	public function remove_from_flagger(Request $request){
		if(!$request->isMethod('post')){
			return $this->jsonError();
		}
	
		$myUser = newGetUser();
		if(is_null($myUser) || !$myUser->isAdmin()){
			return $this->jsonError();
		}
	
		$id = $request->input('id');
	
		if(empty($id) || !is_numeric($id)){
			return $this->jsonError();
		}
	
		// all good, execute
		DB::table('flag_words')->where('id', $id)->delete();
	
		return response()->json(['status' => 'done']);
	}
	// Flagger Remover End

	public function flag_action(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err']);
		}

		$myUser = newGetUser();

		if(is_null($myUser) || (!$myUser->isDeveloper(true))){
			return response()->json(['status' => 'err']);
		}

		$pid = Input::get('pid');
		$fid = Input::get('fid');
		$action = Input::get('action');

		if(!is_numeric($pid)){
			return response()->json(['status' => 'err']);
		}
		
		$paste = Paste::find($pid);
		if(is_null($paste)){
			return response()->json(['status' => 'err']);
		}

		if(!is_numeric($fid)){
			return response()->json(['status' => 'err', 'msg' => 'That flag does not exist.']);
		}
		
		$flag = DB::table('flags')->where('id', $fid)->get();
		if($flag->count() == 0){
			return response()->json(['status' => 'err', 'msg' => 'That flag does not exist.']);
		}
		$flag = $flag->first();
		if($flag->status != 0){
			return response()->json(['status' => 'err', 'msg' => 'Flag already handled']);
		}
		$time = floor(microtime(true) * 1000);
		if($action == "accept"){
			$notifyUser = Input::get('notifyUser') == "true" ? 1 : 0;
			if(!$myUser->isManager(true)){
				$notifyUser = 1; // Force users with roles below manager to notify user
			}
			$reason = null;
			$by = null;
			
			if(!$paste->hidden){ // dont rehide and renotify user
				// if(!$paste->hidden && $myUser->mod && strlen(Input::get('reason')) < 1){
				// 	$reason = Input::get('reason');
				// 	return $this->jsonError('Reason is required.');
				// }
				if(!$paste->hidden && strlen(Input::get('reason')) > 255){
					return $this->jsonError('Reason max length is 255 chars');
				}
				$reason = Input::get('reason');
			}
				
			$by = $myUser->id;
			
			// execute
			DB::transaction(function () use ($flag, $paste, $time, $myUser, $by, $reason) {
				DB::table('flags')->where('id', $flag->id)->update(['status' => 1, 'handled_at' => $time, 'handled_by' => $myUser->id]);
				
				DB::table('pastes')->where('id', $paste->id)->update(['flagged' => 0, 'flagdate' => NULL]);
				if(!$paste->hidden){
					DB::table('pastes')->where('id', $paste->id)->update(['hidden' => 1, 'hidden_at' => Carbon::now(), 'hidden_by' => $by, 'hidden_reason' => $reason]);
					if($paste->created_by){ // decrement pastes if someoen creéted paste
						DB::table('users')->where('id', $paste->created_by)->decrement('pastes');
					}
				}
			});
			//
			
			if($notifyUser && strlen($reason) > 0 && !$paste->hidden){ // ntofiy user 
				if($paste->created_by != 0){
					$user = \App\User::find($paste->created_by);
					if(!is_null($user)){
						DB::table('notifications')->insert(['uid' => $user->id, 'pasteId' => $paste->id, 'type' => 6, 'text' => 'Paste <a href="/upload/'.$paste->link.'">'.htmlentities($paste->title).'</a> was removed by staff for reason:<br><b>'.htmlentities($reason).'</b>', 'date' => floor(microtime(true) * 1000)]);
					}
				}
			}
			return response()->json(['status' => 'done', 'msg' => 'accepted']);

		}else if($action == "deny"){

			DB::transaction(function () use($flag, $time, $myUser, $paste){
				DB::table('flags')->where('id', $flag->id)->update(['status' => 2, 'handled_at' => $time, 'handled_by' => $myUser->id]);
				DB::table('pastes')->where('id', $paste->id)->update(['flagged' => 2]);
			});
			return response()->json(['status' => 'done', 'msg' => 'denied']);

		}
		
		return response()->json(['status' => 'err', 'msg' => 'Unknown error']);

	}
	
	// New function to accept all flags. Reiko, Apr 12th 2024
	public function acceptAllFlags(Request $request) {
		if(!$request->isMethod('post')){
			return $this->jsonError();
		}
		// Finds all flags with status 0 (AKA unaccepted flags)
		DB::transaction(function () {
			$flags = DB::table('flags')
				->join('pastes', 'flags.pid', '=', 'pastes.id')
				->where('flags.status', 0)
				->select('flags.*', 'pastes.*')
				->get();
	
			// Variables set
			$time = floor(microtime(true) * 1000);
			$myUser = newGetUser();

			if(is_null($myUser) || (!$myUser->isDeveloper(true))){
				return response()->json(['status' => 'err']);
			}
			
			// for loop for each flag to update the flags, give a hide reason and so on. Reiko, Apr 12th 2024
			foreach ($flags as $flag) {
					DB::table('flags')->where('pid', $flag->pid)->update([
						'status' => 1,
						'handled_at' => $time,
						'handled_by' => $myUser->id
					]);
					
				if (!$flag->hidden) {
					DB::table('pastes')->where('id', $flag->pid)->update([
						'hidden' => 1,
						'hidden_at' => Carbon::now(),
						'hidden_by' => $myUser->id,
						'hidden_reason' => 'Automatically hidden due to flag processing' // Hide reason
					]);
	
					if ($flag->created_by) {
						DB::table('users')->where('id', $flag->created_by)->decrement('pastes');
					}
	
					// Sidenote, this function was heavily inspired by the original function to accept flags. A deny all button is not needed at this point. Reiko, Apr 12th 2024
					$user = \App\User::find($flag->created_by);
					if (!is_null($user)) {
						DB::table('notifications')->insert([
							'uid' => $user->id,
							'pasteId' => $flag->pid,
							'type' => 6,
							'text' => 'Your paste titled "'.htmlentities($flag->title).'" has been removed by our staff.',
							'date' => floor(microtime(true) * 1000)
						]);
					}
				} else {
					DB::table('pastes')->where('id', $flag->pid)->update([
						'flagged' => 0,
						'flagdate' => NULL
					]);
				}
			}
		});
	
		return response()->json(['status' => 'done', 'msg' => 'done']);
	}

	public function blacklist_fingerprint(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err']);
		}

		$myUser = newGetUser();
		
		$pid = $request->input('pid');
		$paste = Paste::find($pid);
		if(is_null($paste) || $paste->fingerprint == null){
			return response()->json(['status' => 'err']);
		}
		$fingerprint = $paste->fingerprint;
		$fp = DB::table('fp_blacklist')->where('fingerprint', $fingerprint)->first();
		if(!is_null($fp) && $paste->banned){
			
			$pastes = Paste::where('fingerprint', $fingerprint)->get();
			if($pastes->count() > 1){
				Paste::where('fingerprint', $fingerprint)->update(['banned' => 0]);
			}

			$fp->delete();
			$paste->banned = 0;
		}else{
			$time = floor(microtime(true) * 1000);
			
			$pastes = Paste::where('fingerprint', $fingerprint)->get();
			if($pastes->count() > 1){
				Paste::where('fingerprint', $fingerprint)->update(['banned' => 1]);
			}
			DB::table('fp_blacklist')->insert(['fingerprint' => $fingerprint, 'date' => $time]);
		}
		$paste->save();
		return response()->json(['status' => 'done']);
	}

	public function staff_note(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err']);
		}
		$myUser = newGetUser();

		if(is_null($myUser)){
			return response()->json(['status' => 'err']);
		}

		if(!$myUser->isDeveloper(true)){
			return response()->json(['status' => 'err']);
		}
		$pid = $request->input('pid');
		$action = $request->input('action');
		$id = $request->input('nid');
		$note = $request->input('note');
		
		$paste = Paste::find($pid);
		if(is_null($paste)){
			return response()->json(['status' => 'err']);
		}
		$time = floor(microtime(true) * 1000);
		if($action == 'create'){
			if(strlen($note) < 3){
				return response()->json(['status' => 'err', 'msg' => '3 chars minimum...']);
			}
			if(strlen($note) > 300){
				return response()->json(['status' => 'err', 'msg' => 'Comment exceeds char limit of 300']);
			} // 500 Max
			DB::table('staffnotes')->insert(['pid' => $paste->id, 'uid' => $myUser->id, 'comment' => $note, 'date' => $time]);
			$paste->increment('staffnotes');
		}else if($action == 'remove'){
			$note = DB::table('staffnotes')->where('id', $id)->first();
			if(is_null($note)){
				return response()->json(['status' => 'done']);
			}
			if($myUser->id != $note->uid && !$myUser->isManager(true)){
				return response()->json(['status' => 'err']);
			}
			DB::table('staffnotes')->where('id', $id)->delete();
			$paste->decrement('staffnotes');
		}
		return response()->json(['status' => 'done']);
	}

	
	
	public function clearerrorlogs(Request $request){
		if(!$request->isMethod('post')){
			return redirect('/');
		}
		
		$myUser = newGetUser();
		if($myUser == null){
			return redirect('/');
		}
		if(!$myUser->isManager(true)){
			return redirect('/');
		}
		try{
			file_put_contents(env('SYSTEM_LOG_LOCATION'), '');
		}catch(Exception $e){
			//nothin
		}
		return response()->json(['done']);
	}


	public function downloaderrorlogs(){
		$myUser = newGetUser();
		if($myUser == null){
			return redirect('/');
		}
		if(!$myUser->isManager(true)){
			return redirect('/');
		}
		try{
			$filename = 'errors.log'; // File name of the log file
			$filepath = env('SYSTEM_LOG_LOCATION');
			return response()->download($filepath, $filename); // Downloads the log file
		}catch(Exception $e){
			Log::error("Failed to download error logs: " . $e->getMessage()); // logs the error
			return redirect()->back()->withErrors(['msg' => 'Failed to download error logs.']);
		}
	}
	
	public function hide_profile_comment(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}

		$myUser = newGetUser();
		if($myUser == null || !$myUser->isDeveloper(true)){
			return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
		}
		$id = Input::get('cid');

		$comment = DB::table('profile_comments')->where('id', $id)->first();
		
		if(is_null($comment)){
			return response()->json(['status' => 'err', 'msg' => 'Invalid comment ID.']);
		}
		$profileUser = User::find($comment->uid);
		if(!$profileUser){
			return response()->json(['status' => 'err', 'msg' => 'Error']);
		}

		DB::table('profile_comments')->where('id', $id)->update(['hidden' => !$comment->hidden]);
		if($myUser->role > RoleId::COUNCIL){
			Log::create(['uid' => $myUser->id, 'username' => $myUser->username, 'log' => 'Deleted profile comment from <a href="/user/' . $profileUser->username . '" target="_blank">' . $profileUser->username . '</a>']);
		}
		return response()->json(['status' => 'done', 'msg' => 'done', 'hidden' => !$comment->hidden]);
		
	}

}