<?php

namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Validator;
use App\Employee;
use App\Http\Requests\EmployeeRequest;
use RRule\RRule;

class EmployeeController extends Controller
{
	
	public function index(Request $request)
    {
        
        $employees = Employee::where('company_id', $this->_getCompany()->id)
									->with('credential')
										->orderBy('name', 'asc')
											->get();

        return response()->json($employees, 200);

    }
    
	public function store(EmployeeRequest $request)
    {
		
		$employee = $this->_save($request);
		
		if ($employee) {
			
			if ($request->send_to_quickbooks && $this->_hasQuickbooks()) {
				$this->sendToQuickbooks($request, $employee->id);
			}
			
			return response()->json([
				'title' => 'Employee',
				'message' => 'Employee was added successfully.',
				'object' => $employee
			], 201);
			
		} else {
			return response()->json([
				'title' => 'Employee',
				'message' => 'It was not possible to add the Employee.'
			], 500);
		}
		
    }

    public function show($id)
    {

		$employee = Employee::with(['credential'])->find($id);

		if (!$employee || $employee->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Employee',
				'message' => 'Record not found'
			], 404);
		}

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

    public function update(EmployeeRequest $request, $id)
    {

		$employee = $this->_save($request, $id);

		if ($employee) {
			
			if ($request->send_to_quickbooks && $this->_hasQuickbooks()) {
				$this->sendToQuickbooks($request, $employee->id);
			}
			
			return response()->json([
				'title' => 'Employee',
				'message' => 'Employee was edited successfully.',
				'object' => $employee
			], 200);
			
		} else {
			return response()->json([
				'title' => 'Employee',
				'message' => 'It was not possible to edit the Employee.'
			], 500);
		}
	
    }

    public function destroy($id)
    {

        $employee = Employee::find($id);

        if (!$employee || $employee->company_id != $this->_getCompany()->id) {
            return response()->json([
				'title' => 'Employee',
                'message' => 'Record not found',
            ], 404);
        }

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

		if ($id) {

			$employee = Employee::find($id);

			if (!$employee || $employee->company_id != $this->_getCompany()->id) {
				return response()->json([
					'title' => 'Employee',
					'message' => 'Record not found',
				], 404);
			}

		} else {

			$employee = new Employee();
			
			$employee->created_at = date('Y-m-d H:i:s');

		}
		
		$employee->updated_at = date('Y-m-d H:i:s');
		$employee->company_id = $this->_getCompany()->id;
        $employee->name = $request->name;
		$employee->salary = $request->salary;
		$employee->salary_recurrency = $request->salary_recurrency;

        $employee->contacts = array(
                'phone' => $request->contacts['phone'],
				'phone_secondary' => (isset($request->contacts['phone_secondary'])) ? $request->contacts['phone_secondary'] : null,
                'email' => $request->contacts['email']
            );
			
		$employee->location = array(
                'address' => (isset($request->location['address'])) ? $request->location['address'] : null,
                'city' => (isset($request->location['city'])) ? $request->location['city'] : null,
                'state' => (isset($request->location['state'])) ? $request->location['state'] : null,
                'zip_code' => (isset($request->location['zip_code'])) ? $request->location['zip_code'] : null,
                'lat' => (isset($request->location['lat'])) ? $request->location['lat'] : null,
                'lng' => (isset($request->location['lng'])) ? $request->location['lng'] : null
            );

        $employee->preferences = array(
                'image' => (isset($request->preferences['image'])) ? $request->preferences['image'] : null,
				'color' => (isset($request->preferences['color'])) ? $request->preferences['color'] : null
            );
			
		$employee->about = $request->about;

        if ($employee->save()) {
			return $employee;
		}

        return null;

    }
	
	public function complaints($id)
	{
		
		$employee = Employee::find($id);

		if (!$employee || $employee->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Employee',
				'message' => 'Record not found',
			], 404);
		}
		
		return response()->json($employee->complaints, 200);
		
	}
	
	public function work_orders($id)
	{
		
		$employee = Employee::find($id);

		if (!$employee || $employee->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Employee',
				'message' => 'Record not found',
			], 404);
		}
		
		return response()->json($employee->work_orders, 200);
		
	}
	
	public function work_order_visits(Request $request, $id)
	{
		
		$employee = Employee::find($id);

		if (!$employee || $employee->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Employee',
				'message' => 'Record not found',
			], 404);
		}
		
		$work_order_visits = $employee->work_order_visits->where('status', '!=', '0');
		
		if ($request->date) {
			$work_order_visits = $work_order_visits->where('date', $request->date);
		}
		
		$arrWorkOrderVisits = array(
			'employee_id' => $employee->id,
			'employee_name' => $employee->name,
			'employee_color' => (isset($employee->preferences['color'])) ? $employee->preferences['color'] : '',
			'date' => $request->date,
			'date_formatted' => date('D, m/d/Y', strtotime($request->date)),
			'points' => array()
		);
		
		foreach ($work_order_visits as $work_order_visit) {
			$arrWorkOrderVisits['points'][] = array(
				'work_order_visit_id' => $work_order_visit->id,
				'work_order_visit_number' => $work_order_visit->number,
				'work_order_id' => $work_order_visit->work_order->id,
				'work_order_number' => $work_order_visit->work_order->number,
				'recurring' => $work_order_visit->work_order->recurring_formatted,
				'date' => $work_order_visit->date,
				'start_time' => $work_order_visit->start_time,
				'end_time' => $work_order_visit->end_time,
				'start_time_formatted' => ($work_order_visit->start_time == '00:00:00') ? 'ANYTIME' : date('h:i A', strtotime($work_order_visit->start_time)),
				'end_time_formatted' => ($work_order_visit->end_time == '00:00:00') ? 'ANYTIME' : date('h:i A', strtotime($work_order_visit->end_time)),
				'status_formatted' => $work_order_visit->status_formatted,
				'order' => $work_order_visit->visit_order,
				'customer' => $work_order_visit->work_order->customer->name,
				'customer_id' => $work_order_visit->work_order->customer->id,
				'property_address' => $work_order_visit->work_order->property->location['address'],
				'property_lat' => $work_order_visit->work_order->property->location['lat'],
				'property_lng' => $work_order_visit->work_order->property->location['lng']
			);
		}
		
		return response()->json($arrWorkOrderVisits, 200);
		
	}
	
	public function getEmployeesToImport(Request $request)
	{
		
		if (!$this->_hasQuickbooks()) {
			return response()->json([
				'title' => 'Quickbooks',
				'message' => 'No Quickbooks Settings found!',
			], 404);
		}
		
		$quickbooks = new Quickbooks();
		
		if (!$request->start_position) {
			$start_position = 1;
		} else {
			$start_position = $request->start_position;
		}
		
		if (!$request->total) {
			$total = 50;
		} else {
			$total = $request->total;
		}
		
		$employees = $quickbooks->getEmployees($start_position, $total);
		
		$arrEmployee = array();
		
		if ($employees) {
		
			foreach ($employees as $employee) {
				
				$check = Employee::where('company_id', $this->_getCompany()->id)
									->where('quickbooks_id', $employee->Id)
										->count();
										
				$status = 'Imported';
				
				if (!$check) {
					$status = 'Not Imported';
				}
				
				$arrEmployee[] = array(
					'id' => $employee->Id,
					'name' => $employee->DisplayName,
					'contacts' => array(
						'phone' => (isset($employee->PrimaryPhone->FreeFormNumber)) ? $this->_onlyPhoneNumbers($employee->PrimaryPhone->FreeFormNumber) : null,
						'phone_secondary' => (isset($employee->Mobile->FreeFormNumber)) ? $this->_onlyPhoneNumbers($employee->Mobile->FreeFormNumber) : null,
						'email' => (isset($employee->PrimaryEmailAddr->Address)) ? $employee->PrimaryEmailAddr->Address : null
					),
					'status' => $status
				);
				
			}
			
		}
		
		return response()->json($arrEmployee, 200);
		
	}
	
	public function saveFromQuickbooks(Request $request)
	{
		
		foreach ($request->employees as $employee) {
				
			$obj = new Employee();
			
			$obj->created_at = date('Y-m-d H:i:s');
			$obj->updated_at = date('Y-m-d H:i:s');
			$obj->company_id = $this->_getCompany()->id;
			$obj->name = $employee['name'];
			$obj->preferences = array(
				'image' => null,
				'color' => '#000000'
			);
			$obj->location = array();
			
			$obj->contacts = array(
				'phone' => $employee['contacts']['phone'],
				'phone_secondary' => $employee['contacts']['phone_secondary'],
				'email' => $employee['contacts']['email']
			);
			
			$obj->quickbooks_id = $employee['id'];
			
			$obj->save();
			
		}
		
		return response()->json([
					'title' => 'Employee',
					'message' => 'Employees were imported from Quickbooks successfully',
				], 201);
		
	}
	
	public function sendToQuickbooks(Request $request, $id)
	{
		
		$employee = Employee::find($id);

		if (!$employee || $employee->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Employee',
				'message' => 'Record not found',
			], 404);
		}
		
		if (!$this->_hasQuickbooks()) {
			return response()->json([
				'title' => 'Quickbooks',
				'message' => 'No Quickbooks Settings found!',
			], 404);
		}
		
		$quickbooks = new Quickbooks();
		
		if ($employee->quickbooks_id) {
			
			$result = $quickbooks->updateEmployee($employee);
			
			if ($result) {				
				return response()->json([
					'title' => 'Employee',
					'message' => 'Employee was updated to Quickbooks successfully',
				], 201);
			} else {
				return response()->json([
					'title' => 'Employee',
					'message' => 'It was not possible to update the Employee to Quickbooks',
				], 500);
			}
			
		} else {
			
			$result = $quickbooks->addEmployee($employee);
			
			if ($result) {
				
				$employee->quickbooks_id = $result->Id;
				$employee->save();
				
				return response()->json([
					'title' => 'Employee',
					'message' => 'Employee was sent to Quickbooks successfully',
				], 201);
				
			} else {
				return response()->json([
					'title' => 'Employee',
					'message' => 'It was not possible to send the Employee to Quickbooks',
				], 500);
			}
			
		}
		
	}
	
	public function getTotal() {
		
		$total = Employee::where('company_id', $this->_getCompany()->id)->count();

        return response()->json($total, 200);
		
	}
	
	public function setOneSignalId(Request $request, $id)
	{
		
		$employee = Employee::find($id);
		
		if ($employee) {
			
			if ($employee->one_signal_push_id != $request->one_signal_push_id) {
				
				$employee->one_signal_push_id = $request->one_signal_push_id;
			
				if ($employee->save()) {
					return response()->json([
						'title' => 'Employee',
						'message' => 'One Signal Id was updated successfully.'
					], 200);
				}
				
			} else {
				return response()->json([
						'title' => 'Employee',
						'message' => 'One Signal Id is updated.'
					], 200);
			}
			
		}
		
		return response()->json([
					'title' => 'Employee',
					'message' => 'It was not possible to update the One Signal Id.'
				], 500);
		
	}
	
	public function setReceivePushNotification(Request $request, $id)
	{
		
		$employee = Employee::find($id);
		
		if ($employee) {
				
			$employee->receive_push_notification = $request->receive_push_notification;
		
			if ($employee->save()) {
				return response()->json([
					'title' => 'Employee',
					'message' => 'One Signal Receive Push Notification was updated successfully.'
				], 200);
			}
			
		}
		
		return response()->json([
					'title' => 'Employee',
					'message' => 'It was not possible to update the One Signal Receive Push Notification.'
				], 500);
		
	}
	
	public function reportWorkOrderVisits($date_start)
	{
		
		if (!$date_start) {
			$date_start = date('Y-m-d');
		}
		
		$arrRule = array();
		
		$arrRule['dtstart'] = $date_start;
		$arrRule['freq'] = 'daily';
		$arrRule['count'] = 7;
		$arrRule['interval'] = 1;
		
		$rrule = new RRule($arrRule);
		
		$arrReport = array();
		
		$employees = Employee::where('company_id', $this->_getCompany()->id)
								->orderBy('name', 'asc')
									->get();
		
		$arrEmployee = array();
			
		foreach ($employees as $employee) {
			
			$data = array(
				'label' => $employee->name,
				'data' => array()
			);
			
			$count = 1;
			
			foreach ($rrule as $occurrence) {
			
				$date = $occurrence->format('Y-m-d');
				
				$total = \DB::table('work_order_visit_employees')
										->join('work_order_visits', 'work_order_visit_employees.work_order_visit_id', '=', 'work_order_visits.id')
											->select('work_order_visits.id', 'work_order_visits.date')
												->where('work_order_visit_employees.employee_id', $employee->id)
													->where('work_order_visits.date', $date)
														->count();
			
				$data['data'][] = array(
					$count,
					$total,
					date('m/d/Y', strtotime($date))
				);
				
				$count++;
			
			}
			
			$arrReport[] = $data;
			
		}
		
		foreach ($arrReport as $key => $employee) {
			
			$total = 0;
			
			foreach ($employee['data'] as $days) {
				$total = $total + $days[1];
			}
			
			$arrReport[$key]['total'] = $total;
			
		}
		
		return response()->json($arrReport, 200);
		
	}
	
}
