<?php

namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Validator;
use App\Customer;
use App\CustomerSource;
use App\Property;
use App\Invoice;
use App\CustomerStatusLog;
use App\Tag;
use App\MessageTemplate;
use App\WorkOrder;
use Illuminate\Support\Facades\Mail;
use App\Mail\NewCustomerWelcome;
use App\Http\Requests\CustomerRequest;
use BrandedCrate\PayJunction;

class CustomerController extends Controller
{

    public function index(Request $request)
    {
		
		if (isset($request->status) && $request->status >= 0 && $request->status != 99) {
			$customers = Customer::with(['properties'])
										->where('company_id', $this->_getCompany()->id)
											->where('status', $request->status)
												->orderBy('name', 'asc')
													->get();
		} else if (isset($request->status) && $request->status == 99) {
			$customers = Customer::with(['properties'])
										->where('company_id', $this->_getCompany()->id)
											->where('status', '!=', 0)
												->orderBy('name', 'asc')
													->get();
		} else if (isset($request->status) && $request->status == -1) {
			$customers = Customer::with(['properties'])
										->where('company_id', $this->_getCompany()->id)
											->orderBy('name', 'asc')
												->get();
		} else if (isset($request->letter) && $request->letter) {
			$customers = Customer::with(['properties'])
										->where('company_id', $this->_getCompany()->id)
											->where('status', '!=', 0)
												->where('name', 'like', $request->letter . '%')
													->orderBy('name', 'asc')
														->get();
		} else if (isset($request->search) && $request->search) {
			
			$arrCustomer = array();
			
			$properties = Property::where('company_id', $this->_getCompany()->id)
										->where('location', 'like', '%' . $request->search . '%')
											->select('customer_id')
												->get();
											
			foreach ($properties as $property) {
				$arrCustomer[] = $property->customer_id;
			}
			
			$customers = Customer::with(['properties'])
										->where('company_id', $this->_getCompany()->id)
											->where('status', '!=', 0)
												->where(function($query) use ($request, $arrCustomer) {
													$query->where('name', 'like', '%' . $request->search . '%')
															->orWhereIn('id', $arrCustomer);
												})
													->orderBy('name', 'asc')
														->get();
														
		} else {
			$customers = Customer::with(['properties'])
										->where('company_id', $this->_getCompany()->id)
											->orderBy('name', 'asc')
												->get();
		}

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

    public function store(CustomerRequest $request)
    {
		
		$unique = Customer::where('company_id', $this->_getCompany()->id)
								->where('name', 'like', '%' . $request->name . '%')
									->where(function($q) use ($request) {
										$q->where('contacts', 'like', '%' . $request->contacts['email'] . '%')
											->orWhere('contacts', 'like', '%' . $request->contacts['phone_primary'] . '%');
									})
										->get();
		
		if (count($unique)) {
			return response()->json([
					'title' => 'Customer',
					'message' => 'Customer already exists. Try another one.'
				], 422);
		}
		
		$customer = $this->_save($request);
		
		if ($customer) {
			
			if ($request->send_to_quickbooks && $this->_hasQuickbooks()) {
				$this->sendToQuickbooks($request, $customer->id);
			}
			
			$template = MessageTemplate::where('company_id', $this->_getCompany()->id)
											->where('category', 'WELCOME_CUSTOMER')
												->first();
												
			if ($template) {
				
				$send_to = array();
				$send_to[] = $customer->contacts['email'];
				
				if ($customer->contacts['email_secondary']) {
					$send_to[] = $customer->contacts['email_secondary'];
				}
				
				Mail::to($send_to)->send(new NewCustomerWelcome($template->subject, $template->description, $customer));
				
			}
			
			$status_log = new CustomerStatusLog();
			$status_log->created_at = date('Y-m-d H:i:s');
			$status_log->updated_at = date('Y-m-d H:i:s');
			$status_log->company_id = $this->_getCompany()->id;
			$status_log->customer_id = $customer->id;
			$status_log->status = $customer->status;
			$status_log->save();
			
			return response()->json([
					'title' => 'Customer',
					'message' => 'Customer was added successfully.',
					'object' => $customer
				], 201);
			
		} else {
			return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to add the Customer.'
				], 500);
		}
		
    }

    public function show($id)
    {

		$customer = Customer::with(['customer_source', 'properties'])->find($id);

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

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

    public function update(CustomerRequest $request, $id)
    {
		
		$unique = Customer::where('company_id', $this->_getCompany()->id)
								->where('id', '!=', $id)
									->where('name', 'like', '%' . $request->name . '%')
										->where(function($q) use ($request) {
											$q->where('contacts', 'like', '%' . $request->contacts['email'] . '%')
												->orWhere('contacts', 'like', '%' . $request->contacts['phone_primary'] . '%');
										})
											->get();
		
		if (count($unique)) {
			return response()->json([
					'title' => 'Customer',
					'message' => 'Customer already exists. Try another one.'
				], 422);
		}

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

    public function destroy($id)
    {

        $customer = Customer::find($id);

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

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

		if ($id) {

			$customer = Customer::find($id);

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

		} else {

			$customer = new Customer();
			
			$customer->created_at = date('Y-m-d H:i:s');
			$customer->leaded_at = date('Y-m-d');
			$customer->status = 2;
			$customer->password = rand(100000, 999999);

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

        $customer->contacts = array(
                'phone_primary' => $request->contacts['phone_primary'],
				'phone_secondary' => (isset($request->contacts['phone_secondary'])) ? $request->contacts['phone_secondary'] : null,
				'fax' => (isset($request->contacts['fax'])) ? $request->contacts['fax'] : null,
                'email' => $request->contacts['email'],
				'email_secondary' => (isset($request->contacts['email_secondary'])) ? $request->contacts['email_secondary'] : null
            );

        $customer->preferences = array(
				'terms' => (isset($request->preferences['terms'])) ? $request->preferences['terms'] : null,
				'statement_day' => (isset($request->preferences['statement_day'])) ? $request->preferences['statement_day'] : null,
                'statement_by_print' => (isset($request->preferences['statement_by_print']) && $request->preferences['statement_by_print']) ? true : false,
				'statement_by_email' => (isset($request->preferences['statement_by_email']) && $request->preferences['statement_by_email']) ? true : false,
				'work_order_updates_by_text' => (isset($request->preferences['work_order_updates_by_text']) && $request->preferences['work_order_updates_by_text']) ? true : false,
				'work_order_updates_by_email' => (isset($request->preferences['work_order_updates_by_email']) && $request->preferences['work_order_updates_by_email']) ? true : false
            );

		$customer->customer_source_id = $request->customer_source_id;
		$customer->about = $request->about;
		$customer->recurring = $request->recurring;
		
		if ($customer->save()) {
			return $customer;
		}
       
        return null;

    }
	
	public function status(Request $request, $id)
    {

		$customer = Customer::find($id);

		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer',
				'message' => 'Record not found',
			], 404);
		}
		
		$customer->status = $request->status;
		$customer->updated_at = date('Y-m-d H:i:s');
		
		if ($customer->status == 0) {
			
			$customer->archived_at = date('Y-m-d');
			$customer->leaded_at = null;
			$customer->activated_at = null;
			
			$work_orders = WorkOrder::where('company_id', $this->_getCompany()->id)
										->where('customer_id', $customer->id)
											->where('recurring', 1)
												->get();
											
			foreach ($work_orders as $work_order) {
				$work_order->delete();
			}
			
		} else if ($customer->status == 1) {
			
			$customer->activated_at = date('Y-m-d');
			$customer->archived_at = null;
			$customer->leaded_at = null;
			
		} else if ($customer->status == 2) {
			
			$customer->leaded_at = date('Y-m-d');
			$customer->activated_at = null;
			$customer->archived_at = null;
			
		}
		
		if ($customer->save()) {
			
			$status_log = new CustomerStatusLog();
			$status_log->created_at = date('Y-m-d H:i:s');
			$status_log->updated_at = date('Y-m-d H:i:s');
			$status_log->company_id = $this->_getCompany()->id;
			$status_log->customer_id = $customer->id;
			$status_log->status = $customer->status;
			$status_log->save();
			
			return response()->json([
					'title' => 'Customer',
					'message' => 'Status was edited successfully.',
					'object' => $customer
				], 200);
				
		} else {
			return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to edit the Status.'
				], 500);
		}
	
    }
	
	public function tag(Request $request, $id)
    {

		$customer = Customer::find($id);

		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer',
				'message' => 'Record not found',
			], 404);
		}
		
		if (is_array($customer->tags)) {
			$arrTags = $customer->tags;
		} else {
			$arrTags = [];
		}
		
		if (!count($arrTags) || !in_array($request->tag, $arrTags)) {
			$arrTags[] = $request->tag;
		} else {
			$key = array_search($request->tag, $arrTags);
			array_splice($arrTags, $key, 1);
		}
		
		$customer->tags = $arrTags;
		$customer->updated_at = date('Y-m-d H:i:s');
		
		if ($customer->save()) {			
			return response()->json([
					'title' => 'Customer',
					'message' => 'Customer was edited successfully.',
					'object' => $customer
				], 200);
		} else {
			return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to edit the Customer.'
				], 500);
		}
	
    }
	
	public function work_orders($id)
	{
		
		$customer = Customer::find($id);

		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer',
				'message' => 'Record not found',
			], 404);
		}
		
		return response()->json($customer->work_orders, 200);
		
	}
	
	public function reports(Request $request)
	{
		
		if (isset($request->year) && $request->year) {
			$year = $request->year;
		} else {
			$year = date('Y');
		}
		
		$arrActive = array();
		$arrLeads = array();
		$arrArchived = array();
		
		for ($i=1; $i<=12; $i++) {
			$total = $this->_getTotalCustomersByMonth($i, $year);
			$arrActive[] = array($i, $total['1']);
			$arrLeads[] = array($i, $total['2']);
			$arrArchived[] = array($i, $total['0']);
		}
		
		$arrReport = array(
			array(
				'label' => 'Active',
				'data' => $arrActive
			),
			array(
				'label' => 'Lead',
				'data' => $arrLeads
			),
			array(
				'label' => 'Archived',
				'data' => $arrArchived
			)
		);
		
		return response()->json($arrReport, 200);
		
	}
	
	private function _getTotalCustomersByMonth($month, $year)
	{
		
		$logs = CustomerStatusLog::where('company_id', $this->_getCompany()->id)
											->whereMonth('created_at', '<=', $month)
												->whereYear('created_at', $year)
													->orderBy('customer_id', 'asc')
														->orderBy('created_at', 'desc')
															->get();
															
		$arrCustomer = array();
		$arrTotal = array(
			'0' => 0,
			'1' => 0,
			'2' => 0
		);
																		
		foreach ($logs as $log) {
			if (!in_array($log->customer_id, $arrCustomer)) {
				$arrTotal[$log->status]++;
				$arrCustomer[] = $log->customer_id;
			}
		}
		
		return $arrTotal;
		
	}
	
	public function getCustomersToImport(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;
		}
		
		$customers = $quickbooks->getCustomers($start_position, $total);
		
		$arrCustomer = array();
		
		if ($customers) {
		
			foreach ($customers as $customer) {
				
				$check = Customer::where('company_id', $this->_getCompany()->id)
									->where('quickbooks_id', $customer->Id)
										->count();
				
				$status = 'Imported';
				
				if (!$check) {
					$status = 'Not Imported';
				}
				
				$address = '';
						
				if (isset($customer->BillAddr->Line1)) {
					$address .= $customer->BillAddr->Line1;
				}
				
				if (isset($customer->BillAddr->City)) {
					$address .= ', ' . $customer->BillAddr->City;
				}
				
				if (isset($customer->BillAddr->CountrySubDivisionCode)) {
					$address .= ', ' . $customer->BillAddr->CountrySubDivisionCode;
				}
				
				if (isset($customer->BillAddr->PostalCode)) {
					$address .= ', ' . $customer->BillAddr->PostalCode;
				}
				
				$address .= ', USA';
				
				$email = null;
				$email_secondary = null;
				if (isset($customer->PrimaryEmailAddr->Address)) {
					$arrEmail = explode(',', $customer->PrimaryEmailAddr->Address);
					$email = $arrEmail[0];
					if (count($arrEmail) > 1) {
						$email_secondary = $arrEmail[1];
					}
				}
				
				$arrCustomer[] = array(
					'id' => $customer->Id,
					'name' => $customer->DisplayName,
					'location' => array(
						'address' => $address,
						'city' => (isset($customer->BillAddr->City)) ? $customer->BillAddr->City : null,
						'state' => (isset($customer->BillAddr->CountrySubDivisionCode)) ? $customer->BillAddr->CountrySubDivisionCode : null,
						'zip_code' => (isset($customer->BillAddr->PostalCode)) ? $customer->BillAddr->PostalCode : null,
						'lat' => (isset($customer->BillAddr->Lat)) ? $customer->BillAddr->Lat : null,
						'lng' => (isset($customer->BillAddr->Long)) ? $customer->BillAddr->Long : null
					),
					'contacts' => array(
						'phone_primary' => (isset($customer->PrimaryPhone->FreeFormNumber)) ? $this->_onlyPhoneNumbers($customer->PrimaryPhone->FreeFormNumber) : null,
						'phone_secondary' => (isset($customer->Mobile->FreeFormNumber)) ? $this->_onlyPhoneNumbers($customer->Mobile->FreeFormNumber) : null,
						'fax' => (isset($customer->Fax->FreeFormNumber)) ? $this->_onlyPhoneNumbers($customer->Fax->FreeFormNumber) : null,
						'email' => $email,
						'email_secondary' => $email_secondary
					),
					'balance' => $customer->Balance,
					'status' => $status
				);
				
			}
			
		}
		
		return response()->json($arrCustomer, 200);
		
	}
	
	public function saveFromQuickbooks(Request $request)
	{
		
		foreach ($request->customers as $customer) {
				
			$obj = new Customer();
			
			$customer_source = CustomerSource::where('company_id', $this->_getCompany()->id)
													->where('name', 'Imported From Quickbooks')
														->first();
														
			$customer_source_id = null;
			
			if ($customer_source) {
				$customer_source_id = $customer_source->id;
			}
		
			$obj->created_at = date('Y-m-d H:i:s');
			$obj->leaded_at = date('Y-m-d');
			$obj->balance = $customer['balance'];
			$obj->status = 2;
			$obj->company_id = $this->_getCompany()->id;
			$obj->customer_source_id = $customer_source_id;
			$obj->name = $customer['name'];
			$obj->preferences = array(
				'terms' => 0,
				'statement_day' => 1,
                'statement_by_print' => false,
				'statement_by_email' => true,
				'work_order_updates_by_text' => false,
				'work_order_updates_by_email' => true
            );
			
			$obj->contacts = array(
				'phone_primary' => $customer['contacts']['phone_primary'],
				'phone_secondary' => $customer['contacts']['phone_secondary'],
				'fax' => $customer['contacts']['fax'],
				'email' => $customer['contacts']['email'],
				'email_secondary' => null
			);
			
			$obj->quickbooks_id = $customer['id'];
				
			if ($obj->save()) {
				
				$status_log = new CustomerStatusLog();
				$status_log->created_at = date('Y-m-d H:i:s');
				$status_log->updated_at = date('Y-m-d H:i:s');
				$status_log->company_id = $this->_getCompany()->id;
				$status_log->customer_id = $obj->id;
				$status_log->status = $obj->status;
				$status_log->save();
				
				$property = new Property();
				
				$property->created_at = date('Y-m-d H:i:s');
				$property->updated_at = date('Y-m-d H:i:s');
				$property->company_id = $this->_getCompany()->id;
				$property->customer_id = $obj->id;
				$property->address_type = 0;
				
				$property->location = array(
						'address' => $customer['location']['address'],
						'city' => $customer['location']['city'],
						'state' => $customer['location']['state'],
						'zip_code' => $customer['location']['zip_code'],
						'lat' => ($customer['location']['lat'] && is_numeric($customer['location']['lat'])) ? (float) $customer['location']['lat'] : null,
						'lng' => ($customer['location']['lng'] && is_numeric($customer['location']['lng'])) ? (float) $customer['location']['lng'] : null
					);
					
				$property->general_informations = array(
						'gate_code' => null,
						'has_dog' => 0
					);
					
				$property->bodies_of_water = array();
				$property->about = null;

				$property->save();
				
			}
			
		}
				
		return response()->json([
					'title' => 'Customer',
					'message' => 'Customers were imported from Quickbooks successfully',
				], 201);
		
	}
	
	public function sendToQuickbooks(Request $request, $id)
	{
		
		$customer = Customer::find($id);

		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer',
				'message' => 'Record not found',
			], 404);
		}
		
		if (!$this->_hasQuickbooks()) {
			return response()->json([
				'title' => 'Quickbooks',
				'message' => 'No Quickbooks Settings found!',
			], 404);
		}
		
		$quickbooks = new Quickbooks();
		
		if ($customer->quickbooks_id) {
			
			$result = $quickbooks->updateCustomer($customer);
			
			if ($result) {	
				return response()->json([
					'title' => 'Customer',
					'message' => 'Customer was updated to Quickbooks successfully',
				], 201);
			} else {
				return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to update the Customer to Quickbooks',
				], 500);
			}
			
		} else {
			
			$result = $quickbooks->addCustomer($customer);
			
			if ($result) {
				
				$customer->quickbooks_id = $result->Id;
				$customer->save();
				
				return response()->json([
					'title' => 'Customer',
					'message' => 'Customer was sent to Quickbooks successfully',
				], 201);
				
			} else {
				return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to send the Customer to Quickbooks',
				], 500);
			}
			
		}
		
	}
	
	public function updateBalanceFromQuickbooks(Request $request, $id)
	{
		
		if (!$this->_hasQuickbooks()) {
			return response()->json([
				'title' => 'Quickbooks',
				'message' => 'No Quickbooks Settings found!',
			], 404);
		}
		
		$customer = Customer::find($id);
		
		if ($customer) {
			
			$quickbooks = new Quickbooks();
			
			$customer_qbo = $quickbooks->getCustomer($customer->quickbooks_id);
			
			if ($customer_qbo) {
				
				$customer->updated_at = date('Y-m-d H:i:s');
				$customer->balance = $customer_qbo->Balance;
				$customer->save();
				
				return response()->json([
					'title' => 'Customer',
					'message' => 'Customer Balance was updated successfully',
				], 200);
				
			} else {
				return response()->json([
					'title' => 'Customer',
					'message' => 'Record not found',
				], 404);
			}
			
		} else {
			return response()->json([
					'title' => 'Customer',
					'message' => 'Record not found',
				], 404);
		}
		
	}
	
	public function getTotal(Request $request) {
		
		$total = Customer::where('company_id', $this->_getCompany()->id)
								->where('status', $request->status)
									->count();

        return response()->json($total, 200);
		
	}
	
	public function getBalance(Request $request, $id)
    {
		
		$invoices = Invoice::where('company_id', $this->_getCompany()->id)
								->where('customer_id', $id)
									->get();
		
		$billed = 0;
		$paid = 0;
		
		foreach ($invoices as $invoice) {
			if ($invoice->status_formatted == 'Paid') {
				$paid += $invoice->amount;
			} else if ($invoice->status_formatted == 'Billed') {
				$billed += $invoice->amount;
			}
		}
		
		$result = array(
					'billed' => $billed,
					'paid' => $paid
				);
		
		return response()->json($result, 200);
		
    }
	
	public function getDuplicated()
	{
		
		$customers = Customer::where('company_id', \Auth::user()->employee->company_id)->get();
		
		$arrCustomer = array();
		$arrCustomerIds = array();
		$arrCustomerDuplicated = array();
		
		foreach ($customers as $customer) {
			if (!in_array($customer->quickbooks_id, $arrCustomer)) {
				$arrCustomer[] = $customer->quickbooks_id;
				$arrCustomerIds[] = $customer->id;
			} else {
				$arrCustomerDuplicated[] = $customer->id;
			}
		}
		
		return response()->json(array(
				'total' => count($arrCustomerDuplicated),
				'ids' => $arrCustomerDuplicated,
				'total-not' => count($arrCustomerIds),
				'not' => $arrCustomerIds,
			), 200);
		
	}
	
	public function savePaymentMethod(Request $request) 
	{

		$pj_settings = $this->_getCompany()->payjunction_settings;
		
		if (!$pj_settings || !$pj_settings->active) {
			return response()->json([
				'title' => 'Customer Payment Method',
				'message' => 'PayJunction Settings not found'
			], 500);
		}
		
		$customer = Customer::find($request->payment_method['customer_id']);
		
		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer Payment Method',
				'message' => 'Customer not found'
			], 500);
		}
		
		$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'
		));
		
		if (!$customer->payjunction_id) {
			
			try {
			
				$customer_name = explode(' ', $customer->name);
				$first_name = current($customer_name);
				$last_name = end($customer_name);
				
				$pj_customer = $pj->customer()->create(array(
					'companyName' => $customer->name,
					'email' => $customer->contacts['email'],
					'firstName' => $first_name,
					'lastName' => $last_name,
					'phone' => (isset($customer->contacts['phone_primary']) && $customer->contacts['phone_primary']) ? $customer->contacts['phone_primary'] : '0000000000',
					'phone2' => (isset($customer->contacts['phone_secondary']) && $customer->contacts['phone_secondary']) ? $customer->contacts['phone_secondary'] : '0000000000'
				));
				
			} catch(PayJunction\Exception $e) {
				return response()->json([
					'title' => 'Customer Payment Method',
					'message' => 'It was not possible to save the Customer Payment Method'
				], 500);
			}
			
			$customer->payjunction_id = $pj_customer->customerId;
			$customer->save();
			
		}
		
		try {
			
			if ($request->payment_method['payment_method'] == 'CARD') {
				
				$vault = $pj->customerVault()->create($customer->payjunction_id, array(
					'cardNumber' => $request->payment_method['card_number'],
					'cardExpMonth' => $request->payment_method['exp_month'],
					'cardExpYear' => $request->payment_method['exp_year']
				));
				
			} else {
				
				$vault = $pj->customerVault()->create($customer->payjunction_id, array(
					'achRoutingNumber' => $request->payment_method['routing_number'],
					'achAccountNumber' => $request->payment_method['account_number'],
					'achAccountType' => $request->payment_method['account_type'],
					'achType' => $request->payment_method['transaction_type']
				));
				
			}
			
		} catch(PayJunction\Exception $e) {
			return response()->json([
				'title' => 'Customer Payment Method',
				'message' => 'It was not possible to save the Customer Payment Method'
			], 500);
		}
		
		$customer->payjunction_vault_id = $vault->vaultId;
		$customer->auto_payment = $request->payment_method['auto_payment'];
		$customer->save();
		
		return response()->json([
				'title' => 'Customer',
				'message' => 'Customer Payment Method was saved successfully',
			], 200);
		
	}
	
	public function getPayjunctionVault(Request $request, $id)
	{
		
		$pj_settings = $this->_getCompany()->payjunction_settings;
		
		if (!$pj_settings || !$pj_settings->active) {
			return response()->json([
				'title' => 'Customer Payment Method',
				'message' => 'PayJunction Settings not found'
			], 500);
		}
		
		$customer = Customer::find($id);
		
		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer Payment Method',
				'message' => 'Customer not found'
			], 500);
		}
		
		$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'
		));
		
		if ($customer->payjunction_id && $customer->payjunction_vault_id) {
			
			try {
			
				$vault = $pj->customerVault()->read($customer->payjunction_id, $customer->payjunction_vault_id);
				
			} catch(PayJunction\Exception $e) {
				return response()->json([
						'title' => 'Customer Payment Method',
						'message' => 'It was not possible to get the Customer Vault'
					], 500);
			}
			
			return response()->json($vault, 200);
			
		}
		
		return response()->json([
					'title' => 'Customer Payment Method',
					'message' => 'It was not possible to get the Customer Vault'
				], 500);
		
	}
	
	public function changeAutoPayment(Request $request, $id)
    {

		$customer = Customer::find($id);

		if (!$customer || $customer->company_id != $this->_getCompany()->id) {
			return response()->json([
				'title' => 'Customer',
				'message' => 'Record not found',
			], 404);
		}
		
		if ($customer->auto_payment == 0 && (!$customer->payjunction_id || !$customer->payjunction_vault_id)) {
			return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to edit the Customer Auto Payment.'
				], 500);
		}
		
		$customer->auto_payment = !$customer->auto_payment;
		
		if ($customer->save()) {			
			return response()->json([
					'title' => 'Customer',
					'message' => 'Customer Auto Payment was edited successfully.',
					'object' => $customer
				], 200);
		} else {
			return response()->json([
					'title' => 'Customer',
					'message' => 'It was not possible to edit the Customer Auto Payment.'
				], 500);
		}
	
    }
	
}
