<?php

namespace App\Http\Controllers\v1\Robots;

use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use App\Customer;
use App\WorkOrder;
use App\Company;
use App\WorkOrderVisit;
use App\Invoice;
use App\Product;
use App\Service;
use App\Http\Controllers\v1\Quickbooks;
use Illuminate\Support\Facades\Mail;

class InvoiceController extends BaseController
{
	
	public function generate()
	{		
	
		$arrInvoices = [];
	
		// Get Companies (Generate Invoices Automatically = 1)
		
		$companies = Company::where('active', 1)
								->where('generate_invoices_automatically', 1)
									->get();
									
		foreach ($companies as $company) {
			
			echo '========== ' . $company->name . ' ==========<br />';
			
			// Get Customers according to the Statement Day
			
			$customers = Customer::where('company_id', $company->id)
									->where('status', '>', 0)
										->get();
										
			$arrCustomers = [];
								
			foreach ($customers as $customer) {
				if (isset($customer->preferences['statement_day']) && $customer->preferences['statement_day'] == date('d')) {
					$arrCustomers[] = $customer;
				}
			}
			
			// Generate Invoices
			
			foreach ($arrCustomers as $customer) {
				
				echo '.:: ' . $customer->name . ' ::.<br />';
				
				$work_orders = WorkOrder::with(['services', 'products'])
												->where('company_id', $company->id)
													->where('customer_id', $customer->id)
														->get();
															
				foreach ($work_orders as $work_order) {
					
					// Check Work Order
					
					$check = $this->_checkWorkOrder($work_order);
																
					if ($check) {
						
						// Save Invoice
						
						echo '- Work Order ' . $work_order->id . '...<br />';
						
						$invoice = $this->_saveInvoice($work_order);
				
						if ($invoice) {
							
							$arrInvoices[] = $invoice;
							
							// Update Work Order Visits
							
							$this->_updateWorkOrderVisits($invoice);
							
							// Send To Quickbooks
							
							$this->_sendToQuickbooks($invoice);
							
						}
						
					}
					
				}
				
			}
				
		}
		
		// Sending Email
		
		$arrContent = [];
		
		foreach ($arrInvoices as $invoice) {
			$arrContent[] = array(
				'id_invoice' => $invoice->id,
				'id_company' => $invoice->company_id,
				'company_name' => $invoice->company->name,
				'id_customer' => $invoice->customer_id,
				'customer_name' => $invoice->customer->name,
				'id_property' => $invoice->property_id,
				'property_address' => $invoice->property->address,
				'id_work_order' => $invoice->work_order_id,
				'date' => $invoice->date,
				'date_due' => $invoice->date_due,
				'amount' => $invoice->amount,
				'discount' => $invoice->discount,
				'status' => $invoice->status
			);
		}
		
		$content = '<pre>' . print_r($arrContent, true) . '</pre>';
		
		Mail::to(env('MAIL_DEV'))->send(new \App\Mail\Email($content));
		
	}
	
	private function _checkWorkOrder($work_order)
	{
		
		// When Not Recurring
		
		if ($work_order->recurring == 0) {
			
			$invoices = Invoice::where('work_order_id', $work_order->id)
									->count();
									
			if ($invoices > 0) {
				return false;
			}
			
		}
		
		// When Recurring
		
		if ($work_order->recurring == 1) {
			
			$invoices = Invoice::where('work_order_id', $work_order->id)
									->whereMonth('date', date('m'))
										->whereYear('date', date('Y'))
											->count();
									
			if ($invoices > 0) {
				return false;
			}
			
			$work_order_visits = WorkOrderVisit::where('work_order_id', $work_order->id)
													->whereDate('date', '>=', date('Y-m-d'))
														->count();
		
			if ($work_order_visits == 0) {
				return false;
			}
			
		}
		
		return true;
		
	}
	
	private function _saveInvoice($work_order)
	{
		
		try {
			
			$invoice = new Invoice();
			
			$invoice->created_at = date('Y-m-d H:i:s');
			$invoice->updated_at = date('Y-m-d H:i:s');
			$invoice->company_id = $work_order->company_id;
			$invoice->customer_id = $work_order->customer_id;
			$invoice->property_id = $work_order->property_id;
			$invoice->work_order_id = $work_order->id;
			$invoice->date = date('Y-m-d');
			$invoice->date_paid = null;
			$invoice->about = 'Generated automatically';
			
			$arrSendBy = array();
			
			if (isset($work_order->customer->preferences['statement_by_email']) && $work_order->customer->preferences['statement_by_email'] == true) {
				$arrSendBy[] = 'EMAIL';
			}
			
			if (isset($work_order->customer->preferences['statement_by_print']) && $work_order->customer->preferences['statement_by_print'] == true) {
				$arrSendBy[] = 'PRINT';
			}
			
			$invoice->send_by = $arrSendBy;
			
			if (isset($work_order->customer->preferences['terms'])) {
				$invoice->date_due = date('Y-m-d', strtotime('+' . $work_order->customer->preferences['terms'] . ' days', strtotime(date('Y-m-d'))));
			} else {
				$invoice->date_due = date('Y-m-d');
			}
			
			$arrDescription = array();
			
			foreach($work_order->services as $service) {
				
				if ($service) {
				
					$arrDescription[] = array(
						'id' => $service->id,
						'quickbooks_id' => $service->quickbooks_id,
						'name' => $service->name,
						'qty' => $service->pivot->qty,
						'price' => $service->price,
						'type' => 'Service',
						'description' => $service->description
					);
				
				}
				
			}
			
			foreach($work_order->products as $product) {
				
				$arrDescription[] = array(
					'id' => $product->id,
					'quickbooks_id' => $product->quickbooks_id,
					'name' => $product->name,
					'qty' => $product->pivot->qty,
					'price' => $product->price,
					'type' => 'Product',
					'description' => $product->description
				);
				
			}
			
			$invoice->description = $arrDescription;
			
			$total = 0;
		
			foreach($work_order->services as $service) {
				$total += $service->price * $service->pivot->qty;
			}
			
			foreach($work_order->products as $product) {
				$total += $product->price * $product->pivot->qty;
			}
			
			$invoice->amount = $total;
			$invoice->discount = 0;
			$invoice->status = 0;
			
			if ($invoice->save()) {
				return $invoice;
			} else {
				return null;
			}
			
		} catch (\Exception $e) {
			return null;
		}
		
	}
	
	private function _updateWorkOrderVisits($invoice)
	{
		
		if ($invoice->work_order->recurring == 0) {
			
			$work_order_visits = WorkOrderVisit::where('work_order_id', $invoice->work_order_id)
													->get();
														
		} else {
			
			$work_order_visits = WorkOrderVisit::where('work_order_id', $invoice->work_order_id)
													->whereMonth('date', date('m'))
														->whereYear('date', date('Y'))
															->get();
			
		}
		
		foreach ($work_order_visits as $work_order_visit) {
			
			$work_order_visit->updated_at = date('Y-m-d');
			$work_order_visit->invoice_id = $invoice->id;
			$work_order_visit->save();
			
		}
		
	}
	
	private function _sendToQuickbooks($invoice)
	{
		
		$company = Company::find($invoice->company_id);
		
		if (!$company) {
			return false;
		}
		
		$settings = $company->quickbooks_settings()->where('active', 1)->count();
		
		if (!$settings) {
			return false;
		}

		$qbo_check = true;
			
		if (!$invoice->customer->quickbooks_id) {
			$qbo_check = false;
		}
			
		foreach ($invoice->description as $item) {
			if (!$item['quickbooks_id']) {
				$qbo_check = false;
				break;
			}
		}
		
		if ($qbo_check) {
			
			$result = null;
			
			try {
				
				$quickbooks = new Quickbooks();
			
				$result = $quickbooks->addInvoice($invoice);
				
			} catch(\Exception $e) {
				//
			}
			
			if ($result) {
			
				$invoice->quickbooks_id = $result->Id;
				$invoice->save();
			
			}
			
		}
		
	}
	
}
