<?php

namespace App\Http\Controllers;

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

class ApiController extends Controller
{
	public function follow(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}
		// Changed getUser -> newGetUser. Function name was incorrect - Reiko, Mar 14th 
		$myUser = newGetUser();

		if(is_null($myUser)){
			return response()->json(['status' => 'err', 'msg' => 'Not possible.']);
		}
		$uid = Input::get('uid');

		if($myUser->id == $uid){
			return response()->json(['status' => 'err', 'msg' => 'You can\'t follow yourself.']);
		}

		$myUser = User::find($myUser->id);


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

		$user = User::find($uid);

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


		if(!$myUser->isFollowing($uid)){
			DB::table('followers')->insert(['uid' => $uid, 'fid' => $myUser->id, 'followed_at' => time()]);
			DB::table('users')->where('id', $user->id)->increment('followers');
			DB::table('users')->where('id', $myUser->id)->increment('following');
			return response()->json(['status' => 'done', 'msg' => 'Successfully followed user.', 'following' => 1]);
		}else{
			DB::table('followers')->where(['uid' => $uid, 'fid' => $myUser->id])->delete();
			DB::table('users')->where('id', $user->id)->decrement('followers');
			DB::table('users')->where('id', $myUser->id)->decrement('following');
			return response()->json(['status' => 'done', 'msg' => 'Successfully unfollowed user.', 'following' => 0]);
		}
	}

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

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

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

		$paste = Paste::find($pid);

		// Changed paste visibility to allow manager+ instead of just Admin. this has been authorized. Reiko, Mar 15th 2024
		if(is_null($paste) || $paste->created_by != $myUser->id && !$myUser->isManager(true)){
			return response()->json(['status' => 0]);
		}

		if($myUser->role < 2){ // criminal+
			return response()->json(['status' => 0]);
		}
		$val = Input::get('val');
		if($val == 1){
			if($myUser->role < 2){
				return response()->json(['status' => 0]);
			}
			$paste->private = 0;
			$paste->unlisted = 0;
			$paste->save();
		}else if($val == 2){
			if($myUser->role < 2){
				return response()->json(['status' => 0]);
			}
			$paste->private = 0;
			$paste->unlisted = 1;
			$paste->save();
		}else if($val == 3){
			$paste->private = 1;
			$paste->unlisted = 0;
			$paste->save();
		}
		return response()->json(['status' => 1]);
	}

	public function flag(Request $request){
		/*	pastes.flagged
			 0 = not flagged
			 1 = flagged
			 2 = previously flagged and denied
			
			flags.status
			 0 = open
			 1 = accepted
			 2 = denied
			 3 = closed
		*/
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}
		$myUser = newGetUser();
		if(is_null($myUser) || !$myUser->isCouncil()){
			return response()->json(['status' => 'err', 'msg' => 'You do not have permission.']);
		}
		$pid = Input::get('pid');
		if(!is_numeric($pid)){
			return response()->json(['status' => 'err', 'msg' => 'Paste does not exist.']);
		}
		
		$reason = Input::get('reason');

		if(empty($reason)){
			$reason = null;
		}else{
			if(strlen($reason) > 500){
				return response()->json(['status' => 'err', 'msg' => 'Reason is too long']);
			}
		}

		

		$paste = Paste::find($pid);
		$flags = DB::table('flags')->where('pid', $pid)->get();

		if($paste->flagged == 0){ // Flag paste

			$current_time = floor(microtime(true) * 1000);
			DB::transaction(function() use ($pid, $myUser, $reason, $current_time){
				DB::table('flags')->insert(['pid' => $pid, 'status' => 0, 'uid' => $myUser->id, 'reason' => $reason, 'date' => $current_time]);
				DB::table('pastes')->where('id', $pid)->update(['flagged' => 1, 'flagdate' => $current_time]);
			});
			
			// Discord webhook
			$embed = ["title" => "New Flag",
				"description" => "**[" . $paste->title . "](https://".currentDomain()."/admin/flag/" . $paste->link . ")**\nNew flag by [" . $myUser->username . "](https://".currentDomain()."/user/" . $myUser->username . ")\n**Reason:** *" . $reason . "*",
				"url" => "https://".currentDomain()."/admin/flag/" . $paste->link,
				'color' => 16776960,
				'timestamp' => Carbon\Carbon::now()->toIso8601String()
			];

			sendDiscordWebhook('Staff Notification', '', $embed);
			//---
			return response()->json(['status' => 'done', 'flagged' => 1, 'msg' => 'Flagged']);

		}else if($paste->flagged == 1){ // Check if same user flagged paste, then unflag

			$cflag = $flags->where('status', 0);


			if($cflag->count() == 0){ // Check everything is right
				DB::table('pastes')->where('id', $pid)->update(['flagged' => 0, 'flagdate' => NULL]);
				return response()->json(['status' => 'err', 'msg' => 'Error']);
			}
			$cflag = $cflag->first();
			if($cflag->uid == $myUser->id){ // Same user flagged? --> unflag
				DB::transaction(function() use ($pid, $cflag){
					DB::table('pastes')->where('id', $pid)->update(['flagged' => 0, 'flagdate' => NULL]);
					DB::table('flags')->where('id', $cflag->id)->update(['status' => 3]);
				});
				return response()->json(['status' => 'done', 'flagged' => 0, 'msg' => 'Unflagged']);
			}
			return response()->json(['status' => 'err', 'msg' => 'You cannot unflag this paste because it was not flagged by you.']);

		}else if($paste->flagged == 2){ // Check if paste has been updated since last flag, if it has then flag it

			if($paste->flagdate < $paste->last_edited){

				$current_time = floor(microtime(true) * 1000);
				DB::transaction(function() use ($pid, $myUser, $reason, $current_time){
					DB::table('flags')->insert(['pid' => $pid, 'status' => 0, 'uid' => $myUser->id, 'reason' => $reason, 'date' => $current_time]);
					DB::table('pastes')->where('id', $pid)->update(['flagged' => 1, 'flagdate' => $current_time]);
				});
				
				// Discord webhook
				$embed = ["title" => "New Flag",
					"description" => "**[" . $paste->title . "](https://".currentDomain()."/admin/flag/" . $paste->link . ")**\nNew flag by [" . $myUser->username . "](https://".currentDomain()."/user/" . $myUser->username . ")\n**Reason:** *" . $reason . "*",
					"url" => "https://".currentDomain()."/admin/flag/" . $paste->link,
					'color' => 16776960,
					'timestamp' => Carbon\Carbon::now()->toIso8601String()
				];
				sendDiscordWebhook('Staff Notification', '<@893242462347354182>', $embed);
				// ---

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

			}else{
				return response()->json(['status' => 'err', 'msg' => 'You cannot flag this paste because it was previously flagged and not deleted.']);
			}

		}

		return response()->json(['status' => 'err', 'msg' => 'Unknown error']);
	}
    
	public function cancel_edit_request(Request $request){
		if(!$request->isMethod('post')){
			return response()->json(['status' => 'err', 'msg' => 'Invalid request method.']);
		}
		$myUser = newGetUser();
		if($myUser == null){
			return response()->json(['status' => 'err', 'msg' => 'Not logged in.']);
		}
		$doxid = Input::get('dox_id');
		$dox = DB::table('pastes')->where('id', $doxid)->first();
		if(is_null($dox)){
			return response()->json(['status' => 'err', 'msg' => 'That dox does not exist.']);
		}
		if($dox->created_by != $myUser->id){
			return response()->json(['status' => 'err', 'msg' => 'You do not own this paste.']);
		}
		$edit = DB::table('edit_review')->where(['doxId' => $doxid, 'handled' => 0])->limit(1)->get();
		if($edit->count() < 1){
			return response()->json(['status' => 'err', 'msg' => 'There are no active edit requests for this paste.']);
		}

		DB::table('edit_review')->where('doxId', $doxid)->update(['handled' => 1, 'datehandled' => floor(microtime(true) * 1000), 'handledby' => 0, 'action' => 2]);
		return response()->json(['status' => 'done', 'msg' => 'Successfully canceled edit request.']);
	}

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

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

		DB::table('notifications')->where(['uid' => $myUser->id, 'seen' => 0])->update(['seen' => 1]);

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





