Your IP : 216.73.216.84


Current Path : /home/h/e/l/helpink/www/components/com_jbusinessdirectory/models/
Upload File :
Current File : /home/h/e/l/helpink/www/components/com_jbusinessdirectory/models/orders.php

<?php
/**
 * @package    J-BusinessDirectory
 *
 * @author     CMSJunkie http://www.cmsjunkie.com/
 * @copyright  Copyright (C) 2007 - 2022 CMSJunkie. All rights reserved.
 * @license    https://www.gnu.org/licenses/agpl-3.0.en.html
 */
defined('_JEXEC') or die('Restricted access');
use Joomla\Utilities\ArrayHelper;

jimport('joomla.application.component.modelitem');
JTable::addIncludePath(DS.'components'.'com_jbusinessdirectory'.DS.'tables');
require_once(HELPERS_PATH.'/fpdf_helper.php');


class JBusinessDirectoryModelOrders extends JModelItem {
	public function __construct() {
		$this->log = Logger::getInstance();
		parent::__construct();

		$this->appSettings = JBusinessUtil::getApplicationSettings();
		
		$mainframe = JFactory::getApplication();

		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = JFactory::getApplication()->input->get('limitstart', 0, '', 'int');

		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

	/**
	 * Apply a discount to an order
	 *
	 * @param unknown $orderId
	 * @param unknown $discountCode
	 */
	public function applyDiscount($orderId, $discountCode) {
		$table = JTable::getInstance("Order", "JTable", array());
		$table->load($orderId);
		$properties = $table->getProperties(1);
		$order = ArrayHelper::toObject($properties, 'JObject');
		
		if (empty($order->id)) {
			return null;
		}

		$order->discount_amount = 0 ;
		if (!empty($discountCode)) {
			$discount_applied = false;
			$discountTable = JTable::getInstance("Discount", "JTable", array());
			$discount = $discountTable->getDiscount($discountCode, $order->id);

			if (!empty($discount)) {
				$discount->package_ids = explode(",", $discount->package_ids);
				if (in_array($order->package_id, $discount->package_ids)) {
					$order->discount = $discount;
					$order->discount_code = $discount->code;
					if ($discount->price_type==1) {
						$order->discount_amount = $discount->value;
					} else {
						$order->discount_amount = $order->initial_amount * $discount->value/100;
					}
					$discount_applied = true;
				}
			} else {
				$order->discount_code = "";
				$order->discount_amount =0;
			}
			
			if (!$discount_applied) {
				JFactory::getApplication()->enqueueMessage(JText::_('LNG_ERROR_DISCOUNT_CODE'), 'warning');
				return false;
			} else {
				JFactory::getApplication()->enqueueMessage(JText::_('LNG_SUCCES_DISCOUNT_CODE'), 'success');
			}
		} else {
			$order->discount_code = "";
			$order->discount_amount =0;
		}

		if($order->discount_amount > $order->initial_amount){
			$order->discount_amount = $order->initial_amount;
		}
		
		$order->amount = $order->initial_amount - $order->discount_amount;
		// dump($order->amount);
		$order->vat_amount =floatval($order->vat)*$order->amount/100;
		$order->amount +=  $order->vat_amount;
		
		// dump($order);
		//exit;
		$this->saveOrder($order);
		
		return true;
	}
	
	public function getItem($pk = NULL) {		
	}
	
	public function getOrder($orderId) {
		$orderTable = JTable::getInstance("Order", "JTable", array());
		$orderTable->load($orderId);
		
		$properties = $orderTable->getProperties(1);
		$order = ArrayHelper::toObject($properties, 'JObject');

		if (empty($order->id)) {
			return null;
		}
		$packageTable = JTable::getInstance("Package", "JTable", array());
		$package = $packageTable->getPackage($order->package_id);
		
		$order->packageName = $package->name;
		$order->package = $package;
		
		if($order->company_id != -1) {
			$companyTable = $table = JTable::getInstance("Company", "JTable", array());
			$company = $companyTable->getCompany($order->company_id);
			$order->company = $company;
		}
		
		if (! empty($company)) {
			$order->companyName = $company->name;
		} else {
			$order->companyName = "";
		}
 
		$referer= isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"";
		$user = JBusinessUtil::getUser();
		
		if (strpos($referer, "administrator")===false) {
			if($order->company_id != -1) {
				if ($company->userId != $user->id) {
					return null;
				}
			}
		}

		if (isset($company->userId)) {
			$user = JBusinessUtil::getUser($company->userId);
		}
		
		$billingDetailsTable = JTable::getInstance("BillingDetails", "JTable", array());
		$order->billingDetails = $billingDetailsTable->getBillingDetails($user->id);

		//calculate the amount
		$amount = (float)$order->initial_amount - (float)$order->discount_amount;

		if(!empty($order->trial_initial_amount)){
			//$amount = $order->trial_initial_amount;
		}

		$countryId = null;
		if(!empty($order->billingDetails->country->id)){
			$countryId = $order->billingDetails->country->id;
		}
		
		$order = $this->calculateTaxes($amount, $order, $countryId);

		$order->amount = $amount + $order->vat_amount + $order->tax_amount;

		//save updated order
		$this->saveOrder($order);

		//apply the trial price
		if(isset($order->trial_initial_amount)){
			$amount = $order->initial_amount = $order->trial_initial_amount;
			$order = $this->calculateTaxes($amount, $order, $countryId);
			$order->amount = $amount + $order->vat_amount + $order->tax_amount;
		}

		return $order;
	}

	/**
	 * Calculate taxes
	 */
	public function calculateTaxes($amount, $order, $countryId){
		$vatObject = TaxService::getVat($amount,$countryId);
		$order->vat_amount = $vatObject->vat_amount;
		$order->vat = $vatObject->vat;

		$taxObject= TaxService::calculateTaxes($amount, JBD_PACKAGES, $countryId);
		$order->taxes = $taxObject->taxes;
		$order->tax_amount = $taxObject->tax_amount;

		TaxService::updateOrderTaxes($order->id, $countryId);
		OrderService::updateOrderVAT($order->id, $countryId);

		return $order;
	}
	
	public function saveOrder($order) {
		$table = JTable::getInstance("Order", "JTable", array());
		
		// Bind the data.
		if (!$table->bind($order)) {
			$this->setError($table->getError());
			return false;
		}
		
		// Check the data.
		if (!$table->check()) {
			$this->setError($table->getError());
			return false;
		}
		
		// Store the data.
		if (!$table->store()) {
			$this->setError($table->getError());
			return false;
		}
	}
	
	public function updateOrder($data, $processor) {
		$this->log->LogDebug("Update Order ".json_encode($data));
		$appSettings = JBusinessUtil::getApplicationSettings();
		$orderTable = JTable::getInstance("Order", "JTable", array());
		$orderTable->load($data->order_id);
		
		$orderTable->transaction_id = $data->transaction_id;
		$orderTable->amount_paid = $data->amount;
		$orderTable->paid_at = date("Y-m-d h:m:s");
		if(!empty($data->subscription_id)) {
			$orderTable->subscription_id = $data->subscription_id;
		}
		
		// set start_date
		$packageTable = JTable::getInstance("Package", "JTable", array());
		$lastPaidPackage = $packageTable->getLastPaidPackage($orderTable->company_id);
		
		$paidPackage = $packageTable->getPackage($orderTable->package_id);
		if (isset($data->reccuring) && $data->reccuring==1) {
			$intialPaymentDetails = PaymentService::getPaymentDetails($data->order_id);
			if ($intialPaymentDetails->payment_status==PAYMENT_STATUS_PENDING && $data->payment_status==PAYMENT_STATUS_PAID) {
				$this->log->LogDebug("Set trial date ");
				$orderTable->start_trial_date = date("Y-m-d");

				//calculate the trial end date
				$timeUnit = JBusinessUtil::getTimeUnit($paidPackage->trial_period_unit);
				$endDate = date('Y-m-d', strtotime($orderTable->start_trial_date. " + $paidPackage->trial_period_amount $timeUnit"));
				$orderTable->end_trial_date =  $endDate ;
			
				$orderTable->start_date = date("Y-m-d");
			} else {
				$this->log->LogDebug("Set date ");
				$orderTable->start_date = date("Y-m-d");
			}
		} else {
			$this->log->LogDebug("Set default date ");
		}
		
		switch($data->payment_status) {
			case PAYMENT_STATUS_NOT_PAID:
			case PAYMENT_STATUS_PENDING:
			case PAYMENT_STATUS_WAITING:
				$orderTable->state = 0;
				break;
			case PAYMENT_STATUS_FAILURE:
			case PAYMENT_STATUS_CANCELED:
				$orderTable->state = 2;
				break;
			case PAYMENT_STATUS_PAID:
				$orderTable->state = 1;
				break;
			default:
				$orderTable->state = 0;
				break;
		} 
		
		if (!$orderTable->store()) {

			throw  new Exception(JText::_("LNG_ERROR_ADDING_ORDER")." ".$orderTable->getError());
			$this->log->LogError("Error updating order. Order ID: ".$data->order_id);
		}

		if($data->payment_status == PAYMENT_STATUS_PAID && !empty($appSettings->paid_business_usergroup)){
			$userId = $orderTable->user_id;			
			JUserHelper::addUserToGroup($userId, $appSettings->paid_business_usergroup);
		}
		
		$this->log->LogDebug("Order has been successfully updated. Order ID: ".$data->order_id);
		
		return $orderTable;
	}
	
	public function generateInvoicePDF() {
		$menuItemId = JBusinessUtil::getActiveMenuItem();
		$user = JBusinessUtil::getUser();
		$appSettings = JBusinessUtil::getApplicationSettings();
		JModelLegacy::addIncludePath(JPATH_COMPONENT_SITE . '/models', 'Invoice');
		$model = JModelLegacy::getInstance('Invoice', 'JBusinessDirectoryModel', array('ignore_request' => true));
		$invoice = $model->getInvoice();

		if (empty($invoice->company) && $invoice->company_id != -1) {
			die(JText::_('LNG_BUSINESS_DELETED'));
		}
				
		$coverImg = BD_PICTURES_UPLOAD_PATH."/inv_background.png";
		
		header('Content-type: application/pdf');
		header('Content-Disposition: inline; filename="Invoice.pdf"');
		header('Content-Transfer-Encoding: binary');
		header('Accept-Ranges: bytes');

		$pdf = new FPDF_HELPER ();
		
		$pdf->AddPage();

		$pdf->AddFont('DejaVu', '', 'DejaVuSans.ttf', true);
		$pdf->AddFont('DejaVu', 'B', 'DejaVuSans-Bold.ttf', true);
		$pdf->SetFont("DejaVu", "B", "25");
		$pdf->Image($coverImg, 100, 0, 110, 297/2.6);

		$pdf->Cell(5,10, '#'.$appSettings->invoice_prefix.$invoice->id, 0, 0, 'L', false );
		$pdf->SetTextColor(125,125,125); 
		$pdf->SetFont("DejaVu", "", "10");
		$pdf->Cell(5,22, strtoupper($invoice->companyName), 0, 0, 'L', false );   

		// Site logo
		if (!empty($appSettings->logo) && file_exists(BD_PICTURES_UPLOAD_PATH.$appSettings->logo) ){ 
			//Important, exclude unsupported image file types 
			$path_info = pathinfo($appSettings->logo);	
			if (in_array($path_info["extension"], array("jpg", "jpeg", "png", "gif"))) {
				$logo = BD_PICTURES_UPLOAD_PATH . $appSettings->logo;
				$pdf->Cell(1, 40, $pdf->Image($logo, 150, 10, 40), 0, 0, 'L', false );   
			}			
		}
		$pdf->setXY(15,10);
		$pdf->Cell(8,60, JText::_('LNG_DATE'), 0, 0, 'L', false );   
		$pdf->SetTextColor(0); 
		$pdf->setXY(15,10);
		$pdf->Cell(20,70, JBusinessUtil::getDateGeneralFormat($invoice->created), 0, 0, 'L', false );

		$pdf->setXY(15,15);
		$pdf->SetTextColor(125,125,125); 
		
		
		$address = '';
		if(!empty($invoice->billingDetails->first_name) || !(empty($invoice->billingDetails->last_name))) {
			$address .= $invoice->billingDetails->first_name . ' ' . $invoice->billingDetails->last_name;
		}

		if(!empty($invoice->billingDetails->company_name)) {
			$address .= "\r\n" . $invoice->billingDetails->company_name. "\r\n";
		}else {
			$address .= "\r\n" . $invoice->companyName . "\r\n" ;
		}

		if(!empty($invoice->billingDetails->address) || !empty($invoice->billingDetails->city) || !empty($invoice->billingDetails->country) || !empty($invoice->billingDetails->region)) {
			if (!empty(implode(", ", array_filter(array($invoice->billingDetails->address, $invoice->billingDetails->city))))) {
				$address .= implode(", ", array_filter(array($invoice->billingDetails->address, $invoice->billingDetails->city))). ', ';
			}
			if (!empty(implode(", ", array_filter(array($invoice->billingDetails->region, $invoice->billingDetails->postal_code))))) {
				$address .= implode(", ", array_filter(array($invoice->billingDetails->region, $invoice->billingDetails->postal_code))). ', ';
			}
			if (!empty($invoice->billingDetails->country)) {
				$address .= $invoice->billingDetails->country->country_name;
			}
		}
		else{
			$address .= "\r\n". JBusinessUtil::getAddressText($invoice->company).' ';
		}

		if(!empty($invoice->billingDetails->phone) || !empty($invoice->billingDetails->email)) {
			$address .= "\r\n". implode("\r\n", array_filter(array($invoice->billingDetails->phone, $invoice->billingDetails->email)));
		}else {
			$address .= "\r\n". implode("\r\n", array_filter(array($invoice->company->phone, $invoice->company->email)));
		}

		$pdf->Cell(5,90, JText::_('LNG_INVOICE_FOR'), 0, 0, 'L', false );   
		$pdf->SetTextColor(0);
		$pdf->setXY(15,63);
		$pdf->MultiCell(100, 6, !empty($address) ? JBusinessUtil::make_safe_for_utf8_use($address) : "", 0, "L");

		$pdf->SetTextColor(100,100,100); 
		$pdf->SetFont("DejaVu", "", "8");

			
		if (!empty($appSettings->invoice_company_name)) {				
			$companyName = $appSettings->invoice_company_name ;				
		}
		if (!empty($appSettings->invoice_company_address)) {			
			$companyAddress = $appSettings->invoice_company_address;			
		}			
		if (!empty($appSettings->invoice_company_email)) {			
			$companyEmail =  $appSettings->invoice_company_email;			
		}
		if (!empty($appSettings->invoice_company_email)) {			
			$companyPhone =  $appSettings->invoice_company_phone;			
		}
		if (!empty($appSettings->invoice_vat)) {			
			$companyVat =  $appSettings->invoice_vat;			
		}		

		$pdf->setXY(152, 32);
		$pdf->MultiCell(49, 4, isset($companyName) ? JBusinessUtil::make_safe_for_utf8_use(strtoupper($companyName)) : "", 0, "R");

		$pdf->setXY(152, 42);
		$pdf->MultiCell(49, 4, isset($companyAddress) ? JBusinessUtil::make_safe_for_utf8_use(strtoupper($companyAddress)) : "", 0, "R");

		$pdf->setXY(152, 52);
		$pdf->MultiCell(49, 4, isset($companyEmail) ? JBusinessUtil::make_safe_for_utf8_use(strtoupper($companyEmail)) : "", 0, "R");

		$pdf->setXY(152, 62);
		$pdf->MultiCell(49, 4, isset($companyPhone) ? JBusinessUtil::make_safe_for_utf8_use(strtoupper($companyPhone)) : "", 0, "R");

		$pdf->setXY(152, 68);
		$pdf->MultiCell(49, 4, isset($companyVat) ? JBusinessUtil::make_safe_for_utf8_use(strtoupper($companyVat)) : "", 0, "R");

		$pdf->SetDrawColor(225,225,225);
		$pdf->SetLineWidth(".4");
		$pdf->Rect(10, 106, 192, 40, "L");
		
		$pdf->SetFont("", "", "10");
		$pdf->SetTextColor(100,100,100);
		$pdf->SetXY(17,110);
		$pdf->Write(0, JText::_('LNG_PRODUCT_SERVICE'));
		$pdf->SetX(60);
		$pdf->Write(0, JText::_('LNG_DESCRIPTION'));
		$pdf->SetX(123);
		$pdf->Write(0, JText::_('LNG_QTY'));
		$pdf->SetX(140);
		$pdf->Write(0, JText::_('LNG_UNIT_PRICE'));
		$pdf->SetX(170);
		$pdf->Write(0, JText::_('LNG_TOTAL'));

		$pdf->SetTextColor(50,50,50);
		$pdf->SetXY(17,120);
		$pdf->MultiCell(40, 5, $invoice->service, 5, "L");

		$pdf->SetXY(60,120);
		$pdf->MultiCell(60, 5, $invoice->description, 0, "L");
		$pdf->SetXY(125,120);
		$pdf->Write(5, "1");
		$pdf->SetXY(140, 120);
		$pdf->MultiCell(30, 5, JBusinessUtil::getPriceFormat($invoice->initial_amount), 0, "L");

		$pdf->SetXY(170, 120);
		$pdf->MultiCell(30, 5, JBusinessUtil::getPriceFormat($invoice->initial_amount), 0, "L");
		$pdf->SetXY(140, 138);
		$pdf->SetFont("", "", "10");
		$pdf->SetTextColor(100,100,100);
		// Discount
		if($invoice->discount_amount!=0){
			$pdf->Line(140,135, 190,135);
			$pdf->MultiCell(60, 4, JText::_("LNG_DISCOUNT"). ": ".JBusinessUtil::getPriceFormat($invoice->discount_amount), 0, "L");
		} 
		$offsetY = 150;		
		$pdf->SetXY(140, $offsetY);	
		$pdf->MultiCell(60, 4, JText::_("LNG_SUB_TOTAL"). ": ".JBusinessUtil::getPriceFormat($invoice->initial_amount- $invoice->discount_amount), 0, "L");
		
		 if(!empty($invoice->vat_amount) && $invoice->vat_amount>0){ 
			$offsetY = $offsetY+8;
			$pdf->SetXY(140, $offsetY);
			$vatPercent = !empty($invoice->vat)?$invoice->vat:$appSettings->vat ;
			$pdf->MultiCell(60, 4, JText::_("LNG_VAT") . ": (".$vatPercent."%) " . JBusinessUtil::getPriceFormat($invoice->vat_amount), 0, "L");
		}

		if(!empty($invoice->taxes)) { 
			foreach ($invoice->taxes as $tax) { 
			$offsetY = $offsetY+8;
			$pdf->SetXY(140, $offsetY);
			$taxPercent = $tax->tax_type==2?"(".$tax->tax_amount."%)":"";
			$pdf->MultiCell(60, 4, $tax->tax_name . " " . $taxPercent . ": ". JBusinessUtil::getPriceFormat($tax->tax_calc_amount), 0, "L");
			} 

			$offsetY = $offsetY+8;
			$pdf->SetXY(140, $offsetY);
		} else {
			$offsetY = $offsetY+8;
			$pdf->SetXY(140, $offsetY);
		}

		// Total amount
		$pdf->SetTextColor(0);
		$pdf->Line(140,$offsetY-1, 193,$offsetY-1);

		$pdf->MultiCell(60, 5, JText::_('LNG_TOTAL_AMOUNT') . " ". JBusinessUtil::getPriceFormat($invoice->amount), 0, "L");

		$pdf->SetFont("", "", "9");
		$pdf->SetXY(15, 140);
		$pdf->MultiCell(100, 5, $invoice->observation, 0, "L");


		$pdf->Rect(10, 220, 192, 21, "L");
		$pdf->SetFont("", "", "12");
		$pdf->SetTextColor(0);
		$pdf->SetXY(18,226);

		if($invoice->state == 0) {
			$pdf->Write(0, JText::_('LNG_NOT_PAID'));

			$pdf->SetXY(18,235);
			$pdf->SetFont("", "", "9");
			$pdf->SetTextColor(100,100,100);
			$pdf->Write(0, JText::_('LNG_PAY_INVOICE_DESC') ." ". JBusinessUtil::getDateGeneralFormat($invoice->created));
			$pdf->SetFillColor(41,163,41);

			if ($user->id == $invoice->billingDetails->user_id) {	
				$pdf->Rect(150, 225, 40, 10, "F");		
				$pdf->SetTextColor(255,255,255);
				$pdf->SetFont("", "", "12");
				$pdf->SetXY(152,230);
				$pdf->Write(0, JText::_('LNG_PAY')." ".JBusinessUtil::getPriceFormat($invoice->amount), JRoute::_('index.php?option=com_jbusinessdirectory&task=billingdetails.checkBillingDetails&orderId='.$invoice->id.$menuItemId) );
			}
		} elseif ($invoice->state == 1) {
			$pdf->Write(0, JText::_('LNG_PAID'));

			$pdf->SetXY(18,235);
			$pdf->SetFont("", "", "9");
			$pdf->SetTextColor(100,100,100);
			$pdf->Write(0, JText::_('LNG_PAID_INVOICE_DESC') . JBusinessUtil::getDateGeneralFormat($invoice->paid_at));
			$pdf->SetFillColor(41,163,41);
		} elseif ($invoice->state == 2) {
			$pdf->Write(0, JText::_('LNG_CANCELED'));

			$pdf->SetXY(18,235);
			$pdf->SetFont("", "", "9");
			$pdf->SetTextColor(100,100,100);
			$pdf->Write(0, JText::_('LNG_CANCELED_INVOICE_DESC'));
			$pdf->SetFillColor(41,163,41);
		}
		
		$pdf->SetFont("", "", "10");
		$pdf->SetTextColor(0);
		$pdf->SetXY(15,260);
		$pdf->MultiCell(90, 5, !empty($appSettings->invoice_details)?$appSettings->invoice_details:"", 0, "L");

		if($invoice->company_id != -1) {
			$footerText  = !empty($appSettings->invoice_company_name)?$appSettings->invoice_company_name.' | ':"";
			$footerText .= !empty($invoice->billingDetails->company_name)?$invoice->billingDetails->company_name:$invoice->companyName;
		} else {
			$footerText  = !empty($appSettings->invoice_company_name)?$appSettings->invoice_company_name.' | ':"";
			$footerText .= !empty($invoice->billingDetails->name)?$invoice->billingDetails->name:$invoice->user_name;
		}
		
		$pdf->SetXY(130,260);
		$pdf->MultiCell(90, 5, $footerText, 0, "L");

		$pdf->Output('Invoice.pdf', 'I');
		exit;	
	}

	/**
	 * Sends a payment reminder email for all pending orders
	 *
	 */
	public function sendPaymentReminderEmail() {
		$orderTable = JTable::getInstance("Order", "JTable", array());
		$orders = $orderTable->getPendingOrders();

		foreach ($orders as $order) {
			$billingDetailsTable = JTable::getInstance("BillingDetails", "JTable", array());

			if (!empty($order->user_id)) {
				$order->billingDetails = $billingDetailsTable->getBillingDetails($order->user_id);
			}

			$db = JFactory::getDBO();
			$query = "UPDATE #__jbusinessdirectory_orders SET notify_payment=1 WHERE id=".$order->id;
			$db->setQuery($query);

			if($db->execute()) {
				EmailService::sendPaymentReminderEmail($order);
			}
		}

	}
}
?>