<?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;
use BrandedCrate\PayJunction;

class PaymentController extends BaseController
{
	
	public function generate()
	{		
	
		$arrInvoices = [];
		
		// Get Companies (Enable Automatic Payment = 1)
		
		$companies = Company::where('active', 1)
								->where('enable_automatic_payments', 1)
									->get();
									
		foreach ($companies as $company) {
			
			$pj_settings = $company->payjunction_settings()->where('active', 1)->first();
			
			if ($pj_settings) {
			
				echo '========== ' . $company->name . ' ==========<br />';
				
				// Get Customers according to automatic payment
				
				$customers = Customer::where('company_id', $company->id)
										->where('status', '>', 0)
											->where('auto_payment', 1)
												->whereNotNull('payjunction_vault_id')
													->whereNotNull('payjunction_id')
														->get();
									
				foreach ($customers as $customer) {
					
					echo '.:: ' . $customer->name . ' ::.<br />';
					
					// Get Invoices
					
					$invoices = Invoice::where('customer_id', $customer->id)
											->where('status', 0)
												->whereDate('date_due', '>=', date('Y-m-1'))
													->whereDate('date_due', '<=', date('Y-m-d'))
														->get();
													
					foreach ($invoices as $invoice) {
						
						echo '- ' . $invoice->id . ' - ';
						
						// Make the payment
						
						$payment = $this->_makePayment($pj_settings, $invoice);
						
						$arrInvoices[] = 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,
							'paid' => ($payment) ? 'YES' : 'NO'
						);
						
						echo ($payment) ? 'YES' : 'NO';
						echo '<br />';
						
					}
					
				}
				
			}
			
		}
		
		// Sending Email
		
		$content = '<pre>' . print_r($arrInvoices, true) . '</pre>';
		
		Mail::to(env('MAIL_DEV'))->send(new \App\Mail\Email($content));
	
	}
	
	private function _makePayment($pj_settings, $invoice)
	{
		
		$paid = false;
		
		$pj = new PayJunction\Client(array(
			'username' => $pj_settings->username,
			'password' => $pj_settings->password,
			'appkey'   => $pj_settings->app_key,
			'endpoint' => $pj_settings->environment // 'test' or 'live'
		));
		
		$obj = array(
			'vaultId' => $invoice->customer->payjunction_vault_id,
			'amountBase' => $invoice->amount
		);
		
		$transaction = null;
		
		try {
			$transaction = $pj->transaction()->create($obj);
		} catch(\Exception $e) {
			//
		}
		
		if (isset($transaction->response->approved) && $transaction->response->approved) {
			
			// Send PayJunction Receipt
			
			try {
				
				$pj->receipt()->email($transaction->transactionId, array(
					'to' => $invoice->customer->contacts['email'],
					'replyTo' => $invoice->company->contacts['email'],
					'requestSignature' => 'false'
				));
				
			} catch(\Exception $e) {
				//
			}
			
			$invoice->updated_at = date('Y-m-d H:i:s');
			$invoice->date_paid = date('Y-m-d');
			$invoice->status = 1;
			
			// Update Invoice Status
			
			if ($invoice->save()) {
				
				$paid = true;
				
				// Send Email
				
				if (in_array('EMAIL', $invoice->send_by)) {
					
					if (isset($invoice->customer->contacts['email']) && $invoice->customer->contacts['email']) {
						Mail::to($invoice->customer->contacts['email'])->send(new \App\Mail\ThankYouPayment($invoice));
					}
					
					if (isset($invoice->customer->contacts['email_secondary']) && $invoice->customer->contacts['email_secondary']) {
						Mail::to($invoice->customer->contacts['email_secondary'])->send(new \App\Mail\ThankYouPayment($invoice));
					}
					
				}
				
				// Update Balance
				
				$customer = Customer::find($invoice->customer_id);
			
				if ($customer) {
					$customer->billed = $customer->billed - $invoice->amount;
					$customer->paid = $customer->paid + $invoice->amount;
					$customer->balance = $customer->balance - $invoice->amount;
					$customer->save();
				}
				
				// Update Status on Quickbooks
				
				if ($invoice->quickbooks_id) {
					
					try {
						
						$quickbooks = new Quickbooks($invoice->company);
						$quickbooks->addPayment($invoice);
						
					} catch(\Exception $e) {
						//
					}
					
				}
				
			}
			
		}
		
		return $paid;
		
	}
	
}
