Your IP : 216.73.216.84


Current Path : /home/h/e/l/helpink/www/administrator/components/com_jbusinessdirectory/models/
Upload File :
Current File : /home/h/e/l/helpink/www/administrator/components/com_jbusinessdirectory/models/offercoupon.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');

jimport('joomla.filesystem.file');
jimport('joomla.application.component.modeladmin');
require_once(JPATH_COMPONENT_SITE.DS.'libraries'.DS.'phpqrcode'.DS.'qrlib.php');
require_once(HELPERS_PATH.'/fpdf_helper.php');
use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Session\Session;

/**
 * OfferCoupon Model.
 *
 */
class JBusinessDirectoryModelOfferCoupon extends JModelAdmin {

	/**
	 * @var        string    The prefix to use with controller messages.
	 * @since   1.6
	 */
	protected $text_prefix = 'COM_JBUSINESSDIRECTORY_OFFER_COUPON';

	/**
	 * Model context string.
	 *
	 * @var        string
	 */
	protected $_context = 'com_jbusinessdirectory.offercoupon';

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object    A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 */
	protected function canDelete($record) {
		return true;
	}

	/**
	 * Returns a Table object, always creating it
	 *
	 * @param   type    The table type to instantiate
	 * @param   string    A prefix for the table class name. Optional.
	 * @param   array  Configuration array for model. Optional.
	 * @return  JTable    A database object
	 */
	public function getTable($type = 'OfferCoupon', $prefix = 'JTable', $config = array()) {
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get a menu item.
	 *
	 * @param   integer    The id of the menu item to get.
	 *
	 * @return  mixed  Menu item data object on success, false on failure.
	 */
	public function &getItem($itemId = null) {
		$itemId = (!empty($itemId)) ? $itemId : (int)$this->getState('offer.id');
		$false = false;

		// Get a menu item row instance.
		$table = $this->getTable();

		// Attempt to load the row.
		$return = $table->load($itemId);

		// Check for a table object error.
		if ($return === false && $table->getError()) {
			$this->setError($table->getError());
			return $false;
		}

		$properties = $table->getProperties(1);
		$value = ArrayHelper::toObject($properties, 'JObject');

		$value->generated_time = JBusinessUtil::convertToFormat($value->generated_time);
		$value->expiration_time = JBusinessUtil::convertToFormat($value->expiration_time);

		return $value;
	}

	/**
	 * Method to get the menu item form.
	 *
	 * @param   array $data Data for the form.
	 * @param   boolean $loadData True if the form is to load its own data (default case), false if not.
	 * @return  JForm    A JForm object on success, false on failure
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true) {
		// The folder and element vars are passed when saving the form.
		if (empty($data)) {
			$item = $this->getItem();
			// The type should already be set.
		}
		// Get the form.
		$form = $this->loadForm('com_jbusinessdirectory.offercoupon', 'item', array('control' => 'jform', 'load_data' => $loadData), true);
		if (empty($form)) {
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 * @since   1.6
	 */
	protected function loadFormData() {
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_jbusinessdirectory.edit.offercoupon.data', array());

		if (empty($data)) {
			$data = $this->getItem();
		}

		return $data;
	}

	/**
	 *
	 * Show PDF by coupon ID
	 */
	public function show($id) {
		$appSettings = JBusinessUtil::getApplicationSettings();
		$offercouponsTable = $this->getTable("OfferCoupon");
		$this->coupon = $offercouponsTable->getCoupon($id);

		$offerTable = $this->getTable("Offer");
		$offer = $offerTable->getOffer($this->coupon->offer_id);

		$allowedUser = JBusinessUtil::getUser($this->coupon->user_id);

		//set it to writable location, a place for temp generated PNG files
		$PNG_TEMP_DIR = BD_PICTURES_UPLOAD_PATH . DS . 'coupons' . DS . $this->coupon->offer_id . DS;

		//html PNG location prefix
		$PNG_WEB_DIR = BD_PICTURES_UPLOAD_PATH . DS . 'coupons' . DS . $this->coupon->offer_id . DS;

		//we need rights to create temp dir
		if (!file_exists($PNG_TEMP_DIR)) {
			mkdir($PNG_TEMP_DIR);
		}

		$filename = $PNG_TEMP_DIR . 'test.png';

		//options
		$errorCorrectionLevel = 'L';
		$matrixPointSize = 5;

		if ($this->coupon->code) {
			//it's very important!
			if (trim($this->coupon->code) == '') {
				die('data cannot be empty!');
			}

			$filename = $PNG_TEMP_DIR . md5($this->coupon->code) . '.png';

			QRcode::png($this->coupon->code." " .$allowedUser->name , $filename, $errorCorrectionLevel, $matrixPointSize, 2);
		} else {
			//default data
			echo 'You can provide data in GET parameter';
			QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
		}

		header('Content-type: application/pdf');
		header('Content-Disposition: inline; filename="coupon.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", "14");

		if (!empty($appSettings->logo)){ 			
			$logo = BD_PICTURES_PATH . $appSettings->logo;
			$pdf->Cell(1, 40, $pdf->Image($logo, 25, 22, 50), 0, 0, 'L', false );   
		}

		$this->coupon->offerSpecialPrice = (float)$this->coupon->offerSpecialPrice;
		$this->coupon->offerPrice = (float)$this->coupon->offerPrice;
		
		$pdf->SetTextColor(100,100,100); 
		$pdf->Cell(0, 10, "", 0, 1, "L");
		$pdf->setX(90);
		$pdf->setX(100);

		$pdf->SetFont("", "", "15");
		$pdf->Cell(0, 10, ($this->coupon->offer), 0, 1, "L");

		$pdf->SetFont("", "", "11");
		if (!empty($this->coupon->offerPrice)) {
			$pdf->setX(100);
			$pdf->Cell(0, 8, JText::_('LNG_PRICE') . ": " . (JBusinessUtil::getPriceFormat($this->coupon->offerPrice, $this->coupon->offerCurrencyId)), 0, 1, "L");
		} ?>
		<?php if (!empty($this->coupon->offerSpecialPrice)) {
			$pdf->setX(100);
			$pdf->Cell(0, 8, JText::_('LNG_SPECIAL_PRICE') . ": " . (JBusinessUtil::getPriceFormat($this->coupon->offerSpecialPrice, $this->coupon->offerCurrencyId)), 0, 1, "L");
		} ?>
		<?php if (!empty($this->coupon->offerSpecialPrice) && !empty($this->coupon->offerPrice) && $this->coupon->offerSpecialPrice < $this->coupon->offerPrice) {
			$pdf->setX(100);
			$pdf->Cell(0, 8, JText::_('LNG_DISCOUNT') . ": " . (JBusinessUtil::getPriceDiscount($this->coupon->offerSpecialPrice, $this->coupon->offerPrice)) . "%", 0, 1, "L");
		} ?>
		<?php if (!empty($this->coupon->priceText)) {
			$pdf->setX(100);
			$this->coupon->priceText = strip_tags(($this->coupon->priceText));
			$pdf->Cell(0, 8, JText::_('LNG_PRICE_TEXT') . ": " . $this->coupon->priceText, 0, 1, "L");
		} elseif (empty($this->coupon->offerPrice) && empty($this->coupon->offerSpecialPrice) && ($appSettings->show_offer_free)) {
			$pdf->setX(100);
			$pdf->Write(5, JText::_('LNG_FREE'));
		}

		$offsetY = 70;
		$pdf->setXY(20,$offsetY);

		$mailIcon = BD_PICTURES_PATH . "/mailicon.png";
		$webIcon = BD_PICTURES_PATH . "/webicon.png";
		$phoneIcon = BD_PICTURES_PATH . "/phoneicon.png";
		$locationIcon = BD_PICTURES_PATH . "/locationicon.png";
		$businessIcon = BD_PICTURES_PATH . "/business.png";
		$calendarIcon = BD_PICTURES_PATH . "/calendar.png";

		$pdf->Cell(0, 8, $pdf->Image($businessIcon, null,$offsetY , 7,7) ."        ". ($this->coupon->company), 0, 1, "L");	
		if (!empty($this->coupon->offer_address) || !empty($this->coupon->offer_city)) {
			$pdf->setX(20);
			$offsetY+=8;
			$pdf->Cell(0, 8,$pdf->Image($locationIcon, null, $offsetY, 7,7). "        ".($this->coupon->offer_address) . ', ' . ($this->coupon->offer_city), 0, 1, "L");
		}
		if (!empty($this->coupon->phone)) {
			$pdf->setX(20);
			$offsetY+=8;
			$pdf->Cell(0, 8,$pdf->Image($phoneIcon, null, $offsetY, 7,7). "        ".($this->coupon->phone), 0, 1, "L");
		}
		$pdf->setX(20);
		$offsetY+=8;
		$pdf->Cell(0, 8,$pdf->Image($calendarIcon, null, $offsetY, 7,7). "        ".JBusinessUtil::getDateGeneralFormatWithTime($this->coupon->generated_time), 0, 1, "L");

		$translations = JBusinessDirectoryTranslations::getAllTranslations(OFFER_DESCRIPTION_TRANSLATION, $this->coupon->offer_id);
		$lng = JBusinessUtil::getLanguageTag();

		if ($appSettings->enable_multilingual) {
			$description = isset($translations[$lng]) ? $translations[$lng] : "";
			if (empty($description)) {
				$description = $this->coupon->offer_description;
			}
		} else {
			//This can be improved with the addon html2pdf for fpdf library.
			$description = $this->coupon->offer_description;
		}
		$description = strip_tags(($description));

		$pdf->SetXY(20,115);
		$pdf->SetFont("DejaVu", "", "10");
		$pdf->MultiCell(170, 5, utf8_decode(preg_replace('/\s+/', ' ', JBusinessUtil::truncate($description, 1450, '...'))));	
	
		$pdf->SetLineWidth(0.5);
		$pdf->SetDrawColor(150,150,150);
		$pdf->SetDash(5,5); //5mm on, 5mm off
		$pdf->Line(17,200,193,200);

		try {
			$pdf->Image($filename, 75,205, 58);
		} catch (Exception $ex) {
			$this->setError($ex->getMessage());
		}

		$pdf->SetXY(80,257);
		$pdf->Cell(0, 10, "NO. ".strtoupper($this->coupon->code), 0, 1, "L");

		$pdf->SetXY(80,266);
		$pdf->SetFont("DejaVu", "", "8");
		$pdf->Cell(0, 10, JText::_('LNG_VALID_UNTIL'). " " .JBusinessUtil::getDateGeneralFormat($this->coupon->expiration_time) , 0, 1, "L");

		$pdf->SetFont("DejaVu", "", "6");
		$pdf->RotatedText(205,290, JBusinessUtil::getOfferLink($offer->id, $offer->alias), 90);

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

	/**
	 * Method to delete groups.
	 *
	 * @param   array  An array of item ids.
	 * @return  boolean  Returns true on success, false on failure.
	 */
	public function delete(&$itemIds) {
		// Sanitize the ids.
		$itemIds = (array)$itemIds;
		ArrayHelper::toInteger($itemIds);

		// Get a group row instance.
		$table = $this->getTable();

		// Iterate the items to delete each one.
		foreach ($itemIds as $itemId) {
			// Detele coupon image
			if (!$this->deleteFiles($itemId)) {
				$this->setError("Could not delete files");
				return false;
			}
			// Delete coupon
			if (!$table->delete($itemId)) {
				$this->setError($table->getError());
				return false;
			}
		}
		// Clean the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Delete coupon files
	 * @param $itemId
	 * @return boolean
	 */
	public function deleteFiles($itemId) {
		$offercouponsTable = $this->getTable("OfferCoupon");
		$coupon = $offercouponsTable->getCoupon($itemId);
		$file = BD_PICTURES_PATH . DS . 'coupons' . DS . $coupon->offer_id . DS . md5($coupon->code) . '.png';
		JFile::delete($file);
		return true;
	}
}