<?php  
class ControllerSaleBilling extends Controller {
	private $error = array(); 
   
  	public function index() {
		$this->load->language('sale/shipping');
	
    	$this->document->setTitle('Shipping Summary');
		
		$this->load->model('sale/shipping');
		
    	$this->getList();
  	}
              
  	public function insert() {
		$this->load->language('sale/shipping');
	
    	$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('sale/shipping');
			
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      		$this->model_sale_shipping->addStockStatus($this->request->post);
		  	
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';
			
			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}
						
      		$this->redirect($this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}
	
    	$this->getForm();
  	}

  	public function update() {
		$this->load->language('sale/shipping');
	
    	$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('sale/shipping');
		
    	if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
	  		$this->model_sale_shipping->editStockStatus($this->request->get['shipping_id'], $this->request->post);
			
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';
			
			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}
			
			$this->redirect($this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    	}
	
    	$this->getList2();
  	}

  	public function updateBillInfo() {
		$this->load->language('sale/shipping');
	
    	$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('sale/shipping');
				
		
    	//if (isset($this->request->post['selected']) && isset($this->request->post['TrackingNum']) && $this->request->post['TrackingNum'] != "" ) {
			
			$orderIds='0';
			foreach ($this->request->post['selected'] as $order_id) {
				$orderIds = $orderIds . ',' . $order_id;
			}
			$invoicedata = $this->model_sale_shipping->updateBillInformation($this->request->post,$orderIds);
			
			$InvoiceNo = $invoicedata['InvoiceNo'];
			$customercode = $invoicedata['customercode'] ;
			$TotalAmount = $invoicedata['TotalPrice'];
			$TrackingNum = $invoicedata['TrackingNum'];
			$billingemail = $invoicedata['billingemail'];
			$entitybillingemail = $invoicedata['entitybillingemail'];
			
			$InvoiceFileName = "Invoice-"  . $customercode . '-' . $InvoiceNo . '-' . $TotalAmount ;

			$this->PrepareInvoice($InvoiceNo, $InvoiceFileName);
			
			// Invoice-CustomerCode-InvoiceNo-$TotalAmount

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';
			
			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}
			
			// $email='sundeep.maheshwari@gmail.com';
			$email = $billingemail ;
			$subject = $InvoiceFileName ;
			$message = "Your order is on your way! <br>
Please find attached invoice for tracking number:<br>
<a href='https://auspost.com.au/mypost/track/#/details/". $TrackingNum . "'>https://auspost.com.au/mypost/track/#/details/". $TrackingNum . "</a><br>
<br>
Thanks,<br>
Portobello";

			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->hostname = $this->config->get('config_smtp_host');
			$mail->username = $this->config->get('config_smtp_username');
			$mail->password = $this->config->get('config_smtp_password');
			$mail->port = $this->config->get('config_smtp_port');
			$mail->timeout = $this->config->get('config_smtp_timeout');
			$mail->setTo($email);
			//$mail->setFrom($this->config->get('config_email'));
			$mail->setFrom('sales@portobellojewellery.com.au');
			$mail->setSender("Portobello");
			$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
			$mail->setHtml(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
			$mail->addAttachment( DIR_APPLICATION . 'invoices/' .  $InvoiceFileName . '.pdf' );
			$mail->send();
			
			
			$mail->setTo($entitybillingemail);
			$mail->send();
			
			$mail->setTo('soft.technee@yahoo.com');
//			$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
//			$mail->setHtml(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
			$mail->send();			
			
			$this->redirect($this->url->link('sale/billing', 'token=' . $this->session->data['token'] . $url, 'SSL'));
   		//}
		
	
    	$this->getList2();
  	}
    
  	private function getList() {
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'name';
		}
		
		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}
		
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}
				
		$url = '';
			
		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}
		
		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => 'Billing Summary',
			'href'      => $this->url->link('sale/billing', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      		'separator' => ' :: '
   		);
							
		$this->data['insert'] = $this->url->link('sale/shipping/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$this->data['shippinges'] = array();

		$data = array(
			'sort'  => $sort,
			'order' => $order,
			'start' => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit' => $this->config->get('config_admin_limit')
		);
		
	
		$results = $this->model_sale_shipping->getBillings();
 
    	foreach ($results as $result) {
			$action = array();
				
			$this->data['shippinges'][] = array(
				'customercode'            => $result['customercode'],
				'customerparentcode' => $result['customerparentcode'],
				'total'        => $result['total'],
				'url'        =>  $this->url->link('sale/billing/update', 'token=' . $this->session->data['token'] . '&membershipno=' . $result['membershipno']. '&customerparentcode=' . $result['customerparentcode'] . '&customercode=' . $result['customercode'] . $url, 'SSL')
			);
		}
		
		$shipping_total = sizeof($results);

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_name'] = $this->language->get('column_name');
		$this->data['column_action'] = $this->language->get('column_action');		
		
		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');
 
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}
		
		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];
		
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		$url = '';

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}
		
		$this->data['sort_name'] = $this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');
		
		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}
												
		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $shipping_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
			
		$this->data['pagination'] = $pagination->render();

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;

		$this->template = 'sale/billing_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
				
		$this->response->setOutput($this->render());
  	}
  
  	private function getList2() {
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'name';
		}
		
		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}
		
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}
				
		$url = '';
			
		if (isset($this->request->get['customercode'])) {
			$url .= '&customercode=' . $this->request->get['customercode'];
			$customercode = $this->request->get['customercode'];
			$this->data['customercode'] = $customercode;
		}
		if (isset($this->request->get['customerparentcode'])) {
			$url .= '&customerparentcode=' . $this->request->get['customerparentcode'];
			$customerparentcode = $this->request->get['customerparentcode'];
			$this->data['customerparentcode'] = $customerparentcode;
		}
		
		if (isset($this->request->get['membershipno'])) {
			$url .= '&membershipno=' . $this->request->get['membershipno'];
			$membershipno = $this->request->get['membershipno'];
			$this->data['membershipno'] = $membershipno;
		}
		
		if (isset($this->request->get['customer_id'])) {
			$url .= '&customer_id=' . $this->request->get['customer_id'];
			$customer_id = $this->request->get['customer_id'];
			$this->data['customer_id'] = $customer_id;
		}
		
		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}
		
		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => 'Billing Summary',
			'href'      => $this->url->link('sale/billing', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      		'separator' => ' :: '
   		);
							
		$this->data['insert'] = $this->url->link('sale/billing/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$this->data['update'] = $this->url->link('sale/billing/updateBillInfo', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$this->data['shippinges'] = array();

		$data = array(
			'sort'  => $sort,
			'order' => $order,
			'start' => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit' => $this->config->get('config_admin_limit')
		);
		
	
		$results = $this->model_sale_shipping->getBillingLists($customerparentcode,$customercode,$membershipno);
		
		$this->data['customerinfo'] =  $this->model_sale_shipping->getCustomerInfo($customer_id);		
		
		$datas = array();
		$gemstones = $this->model_sale_shipping->getGemstones();		
		$this->data['gemstones']  = $gemstones ;
		
  	    $metals = $this->model_sale_shipping->getMetals();
		$this->data['metals'] = $metals;

		$gem = array();
    	foreach ($gemstones as $gemstone) { 
			$gem[ $gemstone['gemstone_id'] ] = $gemstone['gemcode'];			
		}
		$this->data['gemstone'] = $gem;
		
		$metaldata = array();
     	foreach ($metals as $metal) { 
			$metaldata[ $metal['metal_id'] ] = $metal['metal_code'];
		}
		$this->data['metal'] = $metaldata;
	
    	foreach ($results as $result) {
			$action = array();
			
			$this->data['shippinges'][] = array(
				'data' => $result,
				//'customerparentcode' => $result['customerparentcode'],
				'storebillingshippingname' => $result['storebillingshippingname'],
				'customerparentcode' => $result['customerparentcode'],
				'customercode'            => $result['customercode'],
				'url'        =>  $this->url->link('sale/shipping/update', 'token=' . $this->session->data['token'] . '&customerparentcode=' . $result['customerparentcode'] . '&customercode=' . $result['customercode'] . $url, 'SSL')
			);
		}	
		$shipping_total = sizeof($results);

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_name'] = $this->language->get('column_name');
		$this->data['column_action'] = $this->language->get('column_action');		
		
		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');
 
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}
		
		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];
		
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		$url = '';

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}
		
		$this->data['sort_name'] = $this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');
		
		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}
												
		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $shipping_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
			
		$this->data['pagination'] = $pagination->render();

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;

		$this->template = 'sale/billing_info.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
				
		$this->response->setOutput($this->render());
  	}
  
  	private function getForm() {
     	$this->data['heading_title'] = $this->language->get('heading_title');

    	$this->data['entry_name'] = $this->language->get('entry_name');
		$this->data['entry_sort_order'] = $this->language->get('entry_sort_order');

    	$this->data['button_save'] = $this->language->get('button_save');
    	$this->data['button_cancel'] = $this->language->get('button_cancel');

    	$this->data['tab_general'] = $this->language->get('tab_general');
    
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

 		if (isset($this->error['name'])) {
			$this->data['error_name'] = $this->error['name'];
		} else {
			$this->data['error_name'] = array();
		}
		
		$url = '';
			
		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}
		
		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      		'separator' => ' :: '
   		);
		
		if (!isset($this->request->get['shipping_id'])) {
			$this->data['action'] = $this->url->link('sale/shipping/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
		} else {
			$this->data['action'] = $this->url->link('sale/shipping/update', 'token=' . $this->session->data['token'] . '&shipping_id=' . $this->request->get['shipping_id'] . $url, 'SSL');
		}
			
		$this->data['cancel'] = $this->url->link('sale/shipping', 'token=' . $this->session->data['token'] . $url, 'SSL');
		
		$this->load->model('sale/language');
		
		$this->data['languages'] = $this->model_report_language->getLanguages();
		
		if (isset($this->request->post['shipping'])) {
			$this->data['shipping'] = $this->request->post['shipping'];
		} elseif (isset($this->request->get['shipping_id'])) {
			$this->data['shipping'] = $this->model_sale_shipping->getStockStatusDescriptions($this->request->get['shipping_id']);
		} else {
			$this->data['shipping'] = array();
		}

		$this->template = 'sale/billing_info.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
				
		$this->response->setOutput($this->render());	
  	}
  	
	private function validateForm() {
    	if (!$this->user->hasPermission('modify', 'sale/shipping')) {
      		$this->error['warning'] = $this->language->get('error_permission');
    	}
	
    	foreach ($this->request->post['shipping'] as $language_id => $value) {
      		if ((utf8_strlen($value['name']) < 3) || (utf8_strlen($value['name']) > 32)) {
        		$this->error['name'][$language_id] = $this->language->get('error_name');
      		}
    	}
		
		if (!$this->error) {
	  		return true;
		} else {
	  		return false;
		}
  	}

  	private function validateDelete() {
		if (!$this->user->hasPermission('modify', 'sale/shipping')) {
      		$this->error['warning'] = $this->language->get('error_permission');
    	}
		
		$this->load->model('setting/store');
		$this->load->model('catalog/product');
		
		foreach ($this->request->post['selected'] as $shipping_id) {
						
			$product_total = $this->model_catalog_product->getTotalProductsByStockStatusId($shipping_id);
		
		
			if ($product_total) {
	  			$this->error['warning'] = sprintf($this->language->get('error_product'), $product_total);	
			}  
	  	}
		
		if (!$this->error) { 
	  		return true;
		} else {
	  		return false;
		}
  	}

	public function PrepareInvoice($NewInvoiceNo, $InvoiceFileName) {
		

		$this->load->model('sale/shipping');
			
		$query = $this->model_sale_shipping->getInvoiceHeader($NewInvoiceNo);		
		//$query = $this->db->query("select cct.billerentity,cct.billerbusinessidentifier,cct.billeraddress, cct.billerbankdetails,cct.image,cct.gstrate,cih.InvoiceNo,cih.InvoiceDate ,cih.totalitems,cih.totalprice,cih.sumgst,cih.discountamount,cih.exp1desc ,cih.exp1amount,cih.exp2to4desc,cih.exp2to4amount,cih.expensesgst,cih.totalgst, cbg.name,cbg.billingaddress, cbg.billingcountry, cbg.billingcurrency, ccd.storebillingshippingname,ccd.membershipno,ccd.discount,  adr.address_1,adr.address_2,adr.city,adr.postcode,zon.name as zonname,zon.code, cou.name as couname from  custom_invoice_header cih,custom_customer_details ccd,custom_buying_group cbg,zone zon,address adr,country cou,custom_currency_tax cct where cih.BuyingGroupMemberId=ccd.membershipno and ccd.buyinggroupcode=cbg.code and ccd.shipping_address_id=adr.address_id and adr.zone_id=zon.zone_id and zon.country_id=cou.country_id and cbg.billingcurrency=cct.billingcurrency ");
		
		$logo =  $query['image'];								// './image/Invoicelogo.png';
		$CompanyName =  $query['billerentity']; 				// 'Astral Jewels Pty Ltd';
		$CompanyInfo = trim($query['billerentity1']); 				// 'ATF Dreamers Family Trust  T/A Portobello Camberwell';
		$CompanyIBAN =  $query['billerbusinessidentifier'];	// 'ABN 50 500 435 027';
		$CompanyAddress =  $query['billeraddress'];	 		// 'PO Box 1099, Surrey Hills North VIC 3127 | sales@portobellojewellery.com.au | 0432 444 267';
		$InvoiceNo =  $query['InvoiceNo']; 					// 'JE1520A190502';
		$InvoiceDate =  date('d-M-Y', strtotime($query['InvoiceDate'])); 				// '2-May-2019';
		$BillingAddress1 =  $query['name']; 					// 'Leading Edge Group Limited';
		$BillingAddress2 =  $query['billingaddress'] . ',' . $query['billingcountry'] ; 	// '72 Archer Street, Chatswood, NSW 2067';		
		if( strlen($BillingAddress2)>50 ){
			$BillingAddress2_1 =  $query['billingaddress'] ;
			$BillingAddress2_2 =  $query['billingcountry'];
		}
		
		//$BillingAddress3 =  $query['']; // '';
		$ShipingAddress1 =  $query['storebillingshippingname']; // 'Almas Gold Centre';
		$ShipingAddress2 =  $query['address_1'] . ',' . $query['address_2'] . ',' . $query['city'] . ',' . $query['postcode'] . ',' . $query['zonname'] . ',' . $query['code'] . ',' . $query['couname'];
		
		if( strlen($ShipingAddress2)>50 ){
			$ShipingAddress2_1 =  $query['address_1'] . ',' . $query['address_2'] ;
			$ShipingAddress2_2 =  $query['city'] . ',' . $query['postcode'] . ',' . $query['zonname'] . ',' . $query['code'] . ',' . $query['couname'];
		}
		// 'Shop 25A Churchill Shopping Centre, KILBURN, SA 5084';
		$ShipingAddress3 =  $query['membershipno']; // 'JE1520A';

		$DiscountDescr = '(-) Discount '. $query['discount'] .'%';		
		//$DiscountAmount1 = $query['discountamount'];		
		$DiscountAmount1 = $query['discountamount'] * -1 ;
		//$DiscountAmount2 = $query['totalgst']-($query['exp1amount']*$query['gstrate'])-($query['Exp2to4Amount']*$query['gstrate']);
		//$Discount = $query['discount'];
		
		$OthersDescr = $query['exp2to4desc'];
		$OthersAmount1 = $query['exp2to4amount'];
		$OthersAmount2 = $query['expensesgst'] - ($query['exp1amount'] * $query['gstrate']/100);
		$Others = $OthersAmount1 + $OthersAmount2;		
		
		
		$ShippingDescr = $query['exp1desc'];
		$ShippingAmount1 = $query['exp1amount'];
		//$ShippingAmount2 = $query['exp2to4desc'];
		$ShippingAmount2 = $query['exp1amount']*$query['gstrate'] / 100;
		//$Shipping = $query['exp1amount']*$query['gstrate'];
		$Shipping =  $ShippingAmount1 + $ShippingAmount2;
		
		$TotalQty = $query['totalitems'];
		$TotalAmount1 = $query['totalprice']-$query['totalgst'];
		$TotalAmount2 = $query['totalgst'];
		$Total = $query['totalprice'];
		
		 $BankName = $query['billerbankdetails'];
		 $BankBSB = 'BSB: 033-089';
		 $BankAccount = 'Account: 468320';

		//call the FPDF library
		require('./fpdf181/fpdf.php');

		//create pdf object
		$pdf = new FPDF('P','mm','A4');
		
		//add new page		
		$pdf->AddPage();

		$pdf->Cell(10 ,10,'',0,0);

		//set font to arial, bold, 14pt 
		 $pdf->SetFont('Arial','B',16);

		 $pdf->Image($logo,160,15,30,30);
		 $pdf->Ln();

		 $pdf->Cell(10 ,5,$CompanyName,0,1);

		 $pdf->Cell(10,3,'',0,1);
		 $pdf->SetFont('Arial','B',12);

		 $pdf->Cell(10 ,5,$CompanyInfo,0,1);

		 $pdf->Cell(10 ,5,$CompanyIBAN,0,1);
		 $pdf->Ln();

		 $pdf->SetFont('Arial','',10);
		 $pdf->Cell(10 ,5,$CompanyAddress,0,1);
		 //$pdf->Ln();

		 $pdf->SetFillColor(255,253,253);
		 $pdf->SetFont('Arial','B',12);
		 $pdf->Cell(190 ,8,'TAX INVOICE',1,1,'C',true);

// Billing address
		 //$pdf->Ln();
		 $pdf->Cell(120 ,5,'Bill to',0,0);
		 $pdf->SetFont('Arial','',12);
		 $pdf->Cell(30,5,'Invoice No.',0,0);
		 $pdf->Cell(50,5,$InvoiceNo,0,1);
		 $pdf->SetFont('Arial','',12);
		 $pdf->Cell(10,8,'',0,0);
		 $pdf->Cell(110,5,$BillingAddress1,0,0);
		 $pdf->Cell(30 ,5,'Invoice Date:',0,0);
		 $pdf->Cell(50 ,5,$InvoiceDate,0,1);
		$pdf->Cell(10 ,5,'',0,0);
 		if( strlen($BillingAddress2)<=50 ){			
			$pdf->Cell(15 ,5,$BillingAddress2,0,1);
		}else{		 
			$pdf->Cell(110,5,$BillingAddress2_1,0,1);
			$pdf->Cell(10 ,5,'',0,0);			
			$pdf->Cell(110,5,$BillingAddress2_2,0,1);
		}
		$pdf->Ln();
		
// Shipping address
		 $pdf->SetFont('Arial','B',12);
		 $pdf->Cell(10 ,5,'Ship to',0,1);
		 $pdf->Cell(10 ,8,'',0,0);
		 $pdf->SetFont('Arial','',12);
		 $pdf->Cell(15 ,5,$ShipingAddress1,0,1);
 		if( strlen($ShipingAddress2)<=50 ){
			$pdf->Cell(10 ,5,'',0,0);
			$pdf->Cell(15 ,5,$ShipingAddress2,0,1);
		}else{
			$pdf->Cell(10 ,5,'',0,0);
			$pdf->Cell(15 ,5,$ShipingAddress2_1,0,1);			
			$pdf->Cell(10 ,5,'',0,0);
			$pdf->Cell(15 ,5,$ShipingAddress2_2,0,1);
		}
		 $pdf->Cell(10 ,5,'',0,0);
		 $pdf->Cell(15 ,5,$ShipingAddress3,0,1);
		 $pdf->Ln();
		 
// Invoice Header
		 $pdf->SetFillColor(220,220,220);
		 $pdf->SetFont('Arial','B',10);
		 $pdf->Cell(99 ,8,'Description',1,0,'',true);
		 $pdf->Cell(15 ,8,'Order #',1,0,'C',true);
		 $pdf->Cell(20 ,8,'PO Ref.',1,0,'C',true);
		 $pdf->Cell(8 ,8,'Qty',1,0,'C',true);
		 $pdf->Cell(15 ,8,'Price',1,0,'C',true);
		 $pdf->Cell(13 ,8,'GST',1,0,'C',true);
		 $pdf->Cell(12 ,8,'Total','LTB',0,'R',true);
		 $pdf->SetFont('Arial','B',6);
		 $pdf->Cell(8 ,8,'(AUD)','RTB',1,'L',true);

// Invoice contents

		//$OSquery = $this->db->query("select os.order_id,os.descr,os.aj_price,os.aj_price-os.gst as price,os.gst,os.custtrackingnum from  custom_invoice_header cih, order_stockist os where os.invoicenum=cih.invoiceno");
		$OSquery = $this->model_sale_shipping->getInvoiceDetails($NewInvoiceNo);		
		$gsttotal= 0;
		foreach ($OSquery as $result) {
			$pdf->SetFont('Arial','',9);

			//$pdf->Cell(75 ,6, $result['Label'] ,1,0);
			
			$ProductName = strstr($result['descr'], "<br>", true);
			$ProductDescr = strstr($result['Label'], "|");
			if($result['RRP']>0){
				$ProductDescr = $ProductDescr . "|RRP $" . $result['RRP'];
			}
			//$pdf->SetFont('Arial','B',9);
			//$pdf->Cell(75 ,7, $ProductName . ' - ' . substr($ProductDescr, 1),1,0);
			
			$DescrCellWidth=99;
			$ProductWidth =  ceil(strlen($ProductName) * 1.5)+1;
			$pdf->Cell($ProductWidth ,6, $ProductName ,'LB',0);
			$pdf->SetFont('Arial','',6);
			//$pdf->Cell($DescrCellWidth-$ProductWidth ,6, substr($ProductDescr, 1),0,0);
			$pdf->Cell($DescrCellWidth-$ProductWidth ,6, substr($ProductDescr, 1),'RB',0);			
			
			$pdf->SetFont('Arial','',9);
			//$pdf->Cell(75 ,6,strstr($result['descr'], "<br>", true),1,0);
			$pdf->SetFont('Arial','',8);
			
			if($result['Customized']==1){
				$pdf->Cell(15 ,6,$result['order_id'],  1,0,'C');
			}else{
				//$pdf->Cell(20 ,6,$result['order_id'],  1,0,'C');
				$pdf->Cell(15 ,6, 'Restock' ,  1,0,'C');
			}
			$pdf->Cell(20 ,6,$result['SupplierOrderRef'],  1,0,'C');
			$pdf->SetFont('Arial','',9);
			$pdf->Cell(8 ,6,'1',  1,0,'C');
			$pdf->Cell(15 ,6,round($result['price'],2),1,0,'R');
			$pdf->Cell(13 ,6,round($result['gst'],2),1,0,'R');
			$pdf->Cell(20 ,6,round($result['aj_price'],2),1,1,'R');		 
			$gsttotal = $gsttotal + $result['gst'];
		}
 		$DiscountAmount2 =  $query['totalgst'] - $query['expensesgst'] - $gsttotal ; //-($query['exp1amount']*$query['gstrate'])-($query['Exp2to4Amount']*$query['gstrate']);
		$this->log->write( $query['totalgst'] .  " -  " .  $query['expensesgst'] . " - " . $gsttotal);
		$Discount =  $DiscountAmount1 + $DiscountAmount2;

		 $pdf->Cell(99 ,6,'',1,0);
		 $pdf->Cell(15 ,6,'', 1  , 0,'C');
		 $pdf->Cell(20 ,6,'', 1  , 0,'C');
		 $pdf->Cell(8 ,6,'', 1  , 0,'C');
		 $pdf->Cell(15 ,6,'', 1  , 0,'R');
		 $pdf->Cell(13 ,6,'', 1  , 0,'R');
		 $pdf->Cell(20 ,6,'', 1,1,'R');
/*
		 $pdf->Cell(75 ,7,'',1,0);
		 $pdf->Cell(20 ,7,'', 1  , 0,'C');
		 $pdf->Cell(20 ,7,'', 1  , 0,'C');
		 $pdf->Cell(10 ,7,'', 1  , 0,'C');
		 $pdf->Cell(20 ,7,'', 1  , 0,'R');
		 $pdf->Cell(20 ,7,'', 1  , 0,'R');
		 $pdf->Cell(25 ,7,'', 1,1,'R');
*/
// Invoice contents - Total Section

		 if($query['discount']>0){
			$pdf->Cell(142 ,6,$DiscountDescr,1,0,'R');
			$pdf->Cell(15 ,6,round($DiscountAmount1,2), 1  , 0,'R');
			$pdf->Cell(13 ,6,round($DiscountAmount2,2), 1  , 0,'R');
			$pdf->Cell(20 ,6,round($Discount,2), 1,1,'R');
		 }

		 if($query['Others']>0){
			$pdf->Cell(142 ,6,$OthersDescr,1,0,'R');
			$pdf->Cell(15 ,6,round($OthersAmount1,2) , 1  , 0,'R');
			$pdf->Cell(13 ,6,round($OthersAmount2,2) , 1  , 0,'R');
			$pdf->Cell(20 ,6,round($Others,2) , 1,1,'R');
		 }
		 
		 //if($Shipping>0){
			$pdf->Cell(142 ,6,$ShippingDescr,1,0,'R');
			$pdf->Cell(15 ,6,round($ShippingAmount1,2), 1  , 0,'R');
			$pdf->Cell(13 ,6,round($ShippingAmount2,2) , 1  , 0,'R');
			$pdf->Cell(20 ,6,round($Shipping,2) , 1,1,'R');	 
		 //}

		 //$pdf->SetFont('Arial','B',12);
		 $pdf->Cell(142 ,8,'Total',1,0,'R');
		 $pdf->Cell(15 ,8,'$'.round($TotalAmount1,2), 1  ,0,'R');
		 $pdf->Cell(13 ,8,'$'.round($TotalAmount2,2), 1  , 0,'R');
		 $pdf->Cell(20 ,8,'$'.round($Total,2), 1,1,'R');
		 //$pdf->Ln();
		 
// Footer
		 $pdf->SetFont('Arial','',12);
		 //$pdf->Cell(10 ,15,'Please pay using credit card or transfer funds to:',0,1);
		 $pdf->Cell(10 ,8,'Please pay by transfering funds to: ' . $BankName,0,1);
		 //$pdf->Cell(12 ,5,'',0,0);
		 //$pdf->Cell(30,5,$BankName,0,1);
		 //$pdf->Cell(12 ,5,'',0,0);
		 //$pdf->Cell(30,5,$BankBSB,0,1);
		 //$pdf->Cell(12 ,5,'',0,0);
		 //$pdf->Cell(30,5,$BankAccount,0,1);

		 $pdf->Ln();
		 //$pdf->Ln();

//		 $pdf->Cell(10 ,10);
		 $pdf->SetFont('Arial','B',12);
		 $pdf->Cell(50 ,5,'For Astral Jewels Pty Ltd',0,1);
		 $pdf->Ln();

		 $pdf->Image('./image/Signature.png',10, $pdf->GetY(),45,10);
		 $pdf->Ln();
		 $pdf->Ln();
		 $pdf->Ln();
		 $pdf->Cell(10 ,5,'SIGNED',0,1);
		
		//output the result
		 $pdf->Output("F","./invoices/". $InvoiceFileName .".pdf");

	}

	
}
?>