<?php

namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Validator;
use App\Customer;
use App\Employee;
use App\Property;
use App\WorkOrder;
use App\WorkOrderVisit;
use App\Note;
use App\Notification;
use App\Http\Requests\NoteRequest;

class NoteController extends Controller
{

	public function index(Request $request)
    {

		if (isset($request->customer) && $request->customer) {
			$notes = Note::where('company_id', $this->_getCompany()->id)
								->where('customer_id', $request->customer)
									->orderBy('created_at', 'desc')
										->get();
		} else if (isset($request->notable_type) && !isset($request->notable_id) && $request->notable_type) {
			$notes = Note::where('company_id', $this->_getCompany()->id)
								->where('notable_type', $request->notable_type)
										->orderBy('created_at', 'desc')
											->get();
		} else if (isset($request->notable_type) && isset($request->notable_id)) {
			$notes = Note::where('company_id', $this->_getCompany()->id)
								->where('notable_type', $request->notable_type)
									->where('notable_id', $request->notable_id)
										->orderBy('created_at', 'desc')
											->get();
		} else {
			$notes = Note::where('company_id', $this->_getCompany()->id)
								->orderBy('created_at', 'desc')
									->get();
		}

		return response()->json($notes, 200);
	
    }

    public function store(NoteRequest $request)
    {

		$note = $this->_save($request);
		
		if ($note) {
			
			// Push Notification ----->
			
			if (count($note->notified_employees)) {
				
				$ids = array();
				
				foreach ($note->notified_employees as $emp) {
					
					$employee = Employee::find($emp);
					
					if ($employee && $employee->one_signal_push_id && $employee->receive_push_notification && !in_array($employee->one_signal_push_id, $ids)) {
						$ids[] = $employee->one_signal_push_id;
					}
					
				}
				
				$one_signal = new OneSignal();
				
				$one_signal->title = 'NOTE';
				$one_signal->content = 'You were tagged in a new note';
				$one_signal->ids = $ids;
				$one_signal->url = 'note/' . $note->id;
				$one_signal->send();
			
			}
			
			// Push Notification <-----
			
			$note->load('employee');
			
			return response()->json([
					'title' => 'Note',
					'message' => 'Note was added successfully.',
					'note' => $note
				], 201);
				
		} else {
			return response()->json([
					'title' => 'Note',
					'message' => 'It was not possible to add the Note.'
				], 500);
		}
	
    }

    public function show($id)
    {

		$note = Note::find($id);

		if (!$note) {
			return response()->json([
				'title' => 'Note',
				'message' => 'Record not found'
			], 404);
		}

		return response()->json($note, 200);
	
    }

    public function update(NoteRequest $request, $id)
    {
		
		$note = $this->_save($request, $id);

		if ($note) {
			
			// Push Notification ----->
			
			if (count($note->notified_employees)) {
				
				$ids = array();
				
				foreach ($note->notified_employees as $emp) {
					
					$employee = Employee::find($emp);
					
					if ($employee && $employee->one_signal_push_id && $employee->receive_push_notification && !in_array($employee->one_signal_push_id, $ids)) {
						$ids[] = $employee->one_signal_push_id;
					}
					
				}
				
				$one_signal = new OneSignal();
				
				$one_signal->title = 'NOTE';
				$one_signal->content = 'A note you are tagged was edited';
				$one_signal->ids = $ids;
				$one_signal->url = 'note/' . $note->id;
				$one_signal->send();
			
			}
			
			// Push Notification <-----
			
			return response()->json([
					'title' => 'Note',
					'message' => 'Note was edited successfully.',
					'note' => $note
				], 200);
				
		} else {
			return response()->json([
					'title' => 'Note',
					'message' => 'It was not possible to edit the Note.'
				], 500);
		}
		
    }

    public function destroy($id)
    {

		$note = Note::find($id);

		if (!$note) {
			return response()->json([
				'title' => 'Note',
				'message' => 'Record not found',
			], 404);
		}

		$note->delete();
		
		return response()->json([
				'title' => 'Note',
				'message' => 'Note was deleted successfully.'
			], 200);
	
    }
	
	private function _save(Request $request, $id = null) 
    {

		if ($id) {

			$note = Note::find($id);

			if (!$note) {
				return response()->json([
					'title' => 'Note',
					'message' => 'Record not found',
				], 404);
			}

		} else {

			$note = new Note();
			
			$note->created_at = date('Y-m-d H:i:s');
			
			if ($request->notable_type == 'App\\Customer' || $request->notable_type == 'App\Customer') {
				$note->customer_id = $request->notable_id;
			} else if ($request->notable_type == 'App\\Property' || $request->notable_type == 'App\Property') {
				$property = Property::find($request->notable_id);
				if ($property) {
					$note->customer_id = $property->customer->id;
				}
			} else if ($request->notable_type == 'App\\WorkOrder' || $request->notable_type == 'App\WorkOrder') {
				$work_order = WorkOrder::find($request->notable_id);
				if ($work_order) {
					$note->customer_id = $work_order->customer_id;
				}
			} else if ($request->notable_type == 'App\\WorkOrderVisit' || $request->notable_type == 'App\WorkOrderVisit') {
				$work_order_visit = WorkOrderVisit::find($request->notable_id);
				if ($work_order_visit) {
					$note->customer_id = $work_order_visit->work_order->customer_id;
				}
			}

		}
		
		$note->updated_at = date('Y-m-d H:i:s');
		$note->company_id = $this->_getCompany()->id;
		$note->employee_id = $this->_getEmployee()->id;
		$note->notified_employees = (isset($request->notified_employees)) ? $request->notified_employees : [];
        $note->notable_type = $request->notable_type;
		$note->notable_id = $request->notable_id;
		$note->follow_up_until = $request->follow_up_until;
		$note->follow_up_done = (!$request->follow_up_until) ? null : $request->follow_up_done;
		$note->content = $request->content;
		
		$notified_employees_objects = [];
		
		if (isset($request->notified_employees) && count($request->notified_employees) > 0) {
			foreach ($request->notified_employees as $employee_id) {
				$employee = Employee::find($employee_id);
				if ($employee) {
					$notified_employees_objects[] = array(
						'id' => $employee->id,
						'name' => $employee->name
					);
				}
			}
		}
		
		$note->notified_employees_objects = $notified_employees_objects;

        $note->save();

        return $note;

    }
	
	public function pin($id) {
		
		$note = Note::find($id);

		if (!$note) {
			return response()->json([
				'title' => 'Note',
				'message' => 'Record not found',
			], 404);
		}

		if ($note->pinned) {
			$note->pinned = 0;
		} else {
			$note->pinned = 1;
		}
		
		$note->updated_at = date('Y-m-d H:i:s');
		
		if ($note->save()) {
			return response()->json([
					'title' => 'Note',
					'message' => ($note->pinned) ? 'Note was pinned successfully.' : 'Note was unpinned successfully.',
					'note' => $note
				], 200);			
		} else {
			return response()->json([
					'title' => 'Note',
					'message' => 'It was not possible to pin/unpin the Note.'
				], 500);
		}
		
	}
	
	public function follows_up()
	{
		
		$follows_up = Note::where('company_id', $this->_getCompany()->id)
								->with(['notable', 'customer'])
									->whereNotNull('follow_up_until')
										->whereNull('follow_up_done')
											->orderBy('follow_up_until', 'asc')
												->get();
												
		$arrFollowsUp = array();
		
		foreach ($follows_up as $follow_up) {			
			if ($follow_up->notified_employees && is_array($follow_up->notified_employees) && in_array($this->_getEmployee()->id, $follow_up->notified_employees)) {
				$arrFollowsUp[] = $follow_up;
			}
		}
		
		return response()->json($arrFollowsUp, 200);
		
	}
	
	public function follows_up_total()
	{
		
		$follows_up = Note::where('company_id', $this->_getCompany()->id)
								->with('notable')
									->whereNotNull('follow_up_until')
										->whereNull('follow_up_done')
											->get();
											
		$arrFollowsUp = array();
		
		foreach ($follows_up as $follow_up) {
			if ($follow_up->notified_employees && is_array($follow_up->notified_employees) && in_array($this->_getEmployee()->id, $follow_up->notified_employees)) {
				$arrFollowsUp[] = $follow_up;
			}
		}
		
		return response()->json(count($arrFollowsUp), 200);
		
	}
	
	public function follow_up_done($id) {
		
		$note = Note::find($id);

		if (!$note) {
			return response()->json([
				'message' => 'Record not found',
			], 404);
		}
		
		if ($note->follow_up_done) {
			$note->follow_up_done = null;
		} else {
			$note->follow_up_done = date('Y-m-d');
		}
		
		$note->updated_at = date('Y-m-d H:i:s');
		
		if ($note->save()) {
			return response()->json([
					'title' => 'Note',
					'message' => ($note->follow_up_done) ? 'Follow up was setted as done successfully.' : 'Follow up was setted as undone successfully.',
					'note' => $note
				], 200);
		} else {
			return response()->json([
					'title' => 'Note',
					'message' => 'It was not possible to edit the Note.'
				], 500);
		}
		
	}

}
