<?php

namespace App\Http\Controllers\v1\Robots;

use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use App\WorkOrder;
use App\WorkOrderVisit;
use RRule\RRule;
use Illuminate\Support\Facades\Mail;

class WorkOrderVisitController extends BaseController
{
	
	public function generate()
	{		
		
		$work_orders = WorkOrder::with(['work_order_schedule'])
										->where('recurring', 1)
											->whereDate('next_robot_visits', '<=', date('Y-m-d', strtotime(date('Y-m-d') . '+30 days')))
												->orderBy('next_robot_visits', 'ASC')
													->get();
													
		$arrWorkOrders = array();
		
		$arrDuplicated = array();
		
		foreach($work_orders as $work_order) {
			
			$schedule = $work_order->work_order_schedule;
			
			// Checking If There is a Limit of Visits
			
			if ($schedule->count) {
				continue;
			}
			
			// Adding Work Order To Array
			
			$arrWorkOrders[$work_order->id] = array(
				'company' => $work_order->company_id,
				'id' => $work_order->id,
				'time' => date('Y-m-d H:i:s'),
				'dates' => array()
			);
			
			// Getting Last Work Order Visit
			
			$last_work_order_visit = $work_order->next_robot_visits;
			
			// Getting Dates
		
			$arrRule = array();
			
			$schedule->start_date = date('Y-m-d', strtotime($last_work_order_visit . '+1 days'));
			$arrRule['dtstart'] = $schedule->start_date;
			
			if (date('Y-m-d') > $schedule->start_date) {
				
				$end_date = date('Y-m-d', strtotime(date('Y-m-d') . '+30 days'));
				
				if ($schedule->frequency == 'weekly') {
					$end_date = date('Y-m-d', strtotime(date('Y-m-d') . '+' . ($schedule->interval * 30) . ' days'));
				}
				
				if ($schedule->frequency == 'monthly') {
					$end_date = date('Y-m-d', strtotime(date('Y-m-d') . '+' . $schedule->interval . ' month'));
				}
				
			} else {
				
				$end_date = date('Y-m-d', strtotime($schedule->start_date . '+30 days'));
				
				if ($schedule->frequency == 'weekly') {
					$end_date = date('Y-m-d', strtotime($schedule->start_date . '+' . ($schedule->interval * 30) . ' days'));
				}
				
				if ($schedule->frequency == 'monthly') {
					$end_date = date('Y-m-d', strtotime($schedule->start_date . '+' . $schedule->interval . ' month'));
				}
				
			}
			
			if ($schedule->end_date && date('Y-m-d', strtotime($schedule->end_date)) < $end_date) {
				$end_date = date('Y-m-d', strtotime($schedule->end_date));
			}
			
			$arrRule['until'] = $end_date;		
			$arrRule['freq'] = $schedule->frequency;
			$arrRule['interval'] = $schedule->interval;
				
			if ($schedule->byday) {
				$arrRule['byday'] = $schedule->byday;
			}
			
			if ($schedule->bymonthday) {
				$arrRule['bymonthday'] = $schedule->bymonthday;
			}
			
			$rrule = new RRule($arrRule);
			
			$total = 0;
			foreach ($rrule as $occurrence) {
				$total++;
				$arrWorkOrders[$work_order->id]['dates'][] = $occurrence->format('Y-m-d');
			}
			
			$count = 1;
			$next_robot_visits = null;
			foreach ($rrule as $occurrence) {
				
				if ($count == $total) {
					$next_robot_visits = $occurrence->format('Y-m-d');
				}
				
				$count++;
			
				// Work Order Visit
				
				$created = false;
				
				try {
					
					$work_order_visit = new WorkOrderVisit();
					
					$work_order_visit->created_at = date('Y-m-d H:i:s');
					$work_order_visit->updated_at = date('Y-m-d H:i:s');
					$work_order_visit->company_id = $work_order->company_id;
					$work_order_visit->work_order_id = $work_order->id;
					$work_order_visit->date = $occurrence->format('Y-m-d');
					$work_order_visit->start_time = $schedule->start_time;
					$work_order_visit->end_time = $schedule->end_time;
					$work_order_visit->status = -1;
					$work_order_visit->finished = 0;
					$work_order_visit->billing = 1;
					$work_order_visit->visit_order = $work_order->visit_order;
					
					if ($work_order_visit->save()) {
						$created = true;
					}
					
				} catch (\Exception $e) {
					
					$arrDuplicated[] = array(
						'company_id' => $work_order->company_id,
						'work_order_id' => $work_order->id,
						'date' => $occurrence->format('Y-m-d')
					);
					
				}
				
				if ($created) {
				
					// Work Order Visit Employees
					
					$data = [];
					foreach ($work_order->employees as $employee) {
						$data[] = $employee->pivot->employee_id;
					}
					$work_order_visit->employees()->sync($data);
					
					// Work Order Visit Services

					$data = [];
					foreach ($work_order->services as $service) {
						$data[$service->pivot->service_id] = ['qty' => $service->pivot->qty];
					}
					$work_order_visit->services()->sync($data);
					
					// Work Order Visit Products

					$data = [];
					foreach ($work_order->products as $product) {
						$data[$product->pivot->product_id] = ['qty' => $product->pivot->qty];
					}
					$work_order_visit->products()->sync($data);
					
				}
				
			}
			
			// Saving Last Work Order Visit Date
		
			$work_order->next_robot_visits = $next_robot_visits;
			$work_order->updated_at = date('Y-m-d H:i:s');
			$work_order->save();
			
		}
		
		// Sending Email
		
		$content  = '<pre>' . print_r($arrWorkOrders, true) . '</pre>';
		$content .= '<pre>' . print_r($arrDuplicated, true) . '</pre>';
		
		Mail::to(env('MAIL_DEV'))->send(new \App\Mail\Email($content));
		
	}
	
}
