<?php

/**
 * Custom extension for Isotope for Contao
 *
 * Copyright (c) 2014 Benjamin Roth [http://www.esales-media.de]
 *
 * @package eSM_isotope_custom
 * @link    http://www.esales-media.de
 * @license commercial
 */

namespace eSM_isotope_custom;


use Haste\Util\Format;
use Isotope\Interfaces\IsotopeAttribute;
use Isotope\Model\Product;
use Isotope\Model\ProductPrice;
use Isotope\Model\ProductType;

class tl_iso_product extends \Backend
{
  public function injectIntoPalettes(\DataContainer $dc)
  {
    foreach ($GLOBALS['TL_DCA']['tl_iso_product']['palettes'] as $key => $palette)
    {
      if ($key == '__selector__' || in_array($palette, array('not_buyable', 'price_rrp', 'product_of_month','search_keywords')))
      {
        continue;
      }
//      $GLOBALS['TL_DCA']['tl_iso_product']['palettes'][$key] = str_replace('published', 'not_buyable,published', $GLOBALS['TL_DCA']['tl_iso_product']['palettes'][$key]);
    }
  }

  public function generateLabel($row, $label, $dc, $args)
  {
    $objProduct = Product::findByPk($row['id']);

    foreach ($GLOBALS['TL_DCA'][$dc->table]['list']['label']['fields'] as $i => $field) {
      switch ($field) {
        case 'images':
          $args[$i] = static::generateIsoImage($objProduct);
          break;

        case 'name':
          $args[$i] = $this->generateName($row, $objProduct, $dc);
          break;

        case 'price':
          $args[$i] = $this->generatePrice($row);
          break;

        case 'variantFields':
          $args[$i] = $this->generateVariantFields($args[$i], $objProduct, $dc);
          break;

        default:
          $args[$i] = ($this->generateAttribute($field,$objProduct) ?: '');
          break;
      }
    }

    return $args;
  }

  /**
   * Generate image label for product.
   *
   * @param \Isotope\Model\Product $objProduct
   *
   * @return string
   */
  public static function generateIsoImage($objProduct)
  {
    $arrImages = deserialize($objProduct->images);

    if (!empty($arrImages) && is_array($arrImages)) {
      foreach ($arrImages as $image) {
        $strImage = 'isotope/' . strtolower(substr($image['src'], 0, 1)) . '/' . $image['src'];

        if (is_file(TL_ROOT . '/' . $strImage)) {
          $size = @getimagesize(TL_ROOT . '/' . $strImage);

          $script = sprintf(
            "Backend.openModalImage({'width':%s,'title':'%s','url':'%s'});return false",
            $size[0],
            str_replace("'", "\\'", $objProduct->name),
            TL_FILES_URL . $strImage
          );

          /** @noinspection BadExpressionStatementJS */
          /** @noinspection HtmlUnknownTarget */
          return sprintf(
            '<a href="%s" onclick="%s"><img src="%s" alt="%s" align="left"></a>',
            TL_FILES_URL . $strImage,
            $script,
            TL_ASSETS_URL . \Image::get($strImage, 50, 50, 'proportional'),
            $image['alt']
          );
        }
      }
    }

    return '&nbsp;';
  }

  /**
   * Generate name label for product with link to variants if enabled.
   *
   * @param array          $row
   * @param \Isotope\Model\Product        $objProduct
   * @param \DataContainer $dc
   *
   * @return string
   */
  private function generateName($row, $objProduct, $dc)
  {
    // Add a variants link
    if ($row['pid'] == 0
      && ($objProductType = ProductType::findByPk($row['type'])) !== null
      && $objProductType->hasVariants()
    ) {
      /** @noinspection HtmlUnknownTarget */
      return sprintf(
        '<a href="%s" title="%s">%s</a>',
        ampersand(\Environment::get('request')) . '&amp;id=' . $row['id'],
        specialchars($GLOBALS['TL_LANG'][$dc->table]['showVariants']),
        $objProduct->name
      );
    }

    return ($this->generateAttribute('lage',$objProduct) ?: '').' '.$objProduct->name.' '.$objProduct->zusatz.' '.($this->generateAttribute('qualitaet',$objProduct) ?: '').' '.($this->generateAttribute('geschmack',$objProduct) ?: '');
  }

  /**
   * Generate price label for product.
   *
   * @param array $row
   *
   * @return string
   */
  private function generatePrice($row)
  {
    $objPrice = ProductPrice::findPrimaryByProductId($row['id']);

    if (null !== $objPrice) {
      try {
        /** @var \Isotope\Model\TaxClass $objTax */
        $objTax = $objPrice->getRelated('tax_class');
        $strTax = (null === $objTax ? '' : ' (' . $objTax->getName() . ')');

        return $objPrice->getValueForTier(1) . $strTax;
      } catch (\Exception $e) {
        return '';
      }
    }

    return '';
  }

  /**
   * Generate variant fields for product.
   *
   * @param string         $label
   * @param Product        $objProduct
   * @param \DataContainer $dc
   *
   * @return string
   */
  private function generateVariantFields($label, $objProduct, $dc)
  {
    $attributes = [];

    foreach ($GLOBALS['TL_DCA'][$dc->table]['list']['label']['variantFields'] as $variantField) {
      $attributes[] = sprintf(
        '<strong>%s:</strong>&nbsp;%s',
        Format::dcaLabel($dc->table, $variantField),
        Format::dcaValue($dc->table, $variantField, $objProduct->$variantField)
      );
    }

    return ($label ? $label . '<br>' : '') . implode(', ', $attributes);
  }

  protected function generateAttribute($strAttribute, $objProduct, $blnStripTags = false, array $arrOptions = array()) {

    $objAttribute = $GLOBALS['TL_DCA']['tl_iso_product']['attributes'][$strAttribute];

    if (!($objAttribute instanceof IsotopeAttribute)) {
      return '';
    }

    $strBuffer = $objAttribute->generate($objProduct, $arrOptions);

    if ($blnStripTags)
    {
      $strBuffer = strip_tags($strBuffer,'<br><br /><br/></p></ p>');
      $strBuffer = str_ireplace(array('<br />','<br>','<br/>'),"\n",$strBuffer);
      $strBuffer = str_ireplace(array('</p>','</ p>'),"\n",$strBuffer);
      $strBuffer = preg_replace('/(\r\n|\n)$/','',$strBuffer);
    }

    return $strBuffer;
  }

  public function generateSearchKeywords(\DataContainer $dc)
  {
    $objProduct = Product::findByPk($dc->id);

    $arrKeywords = array();

    foreach ($GLOBALS['TL_DCA']['tl_iso_product']['fields'] as $field => $arrData) {
      if ($arrData['attributes']['fe_filter'] && !$arrData['attributes']['fe_search'] && $arrData['attributes']['type'] == 'select') {
        if (($varValue = $this->generateAttribute($field,$objProduct)))
        {
          $arrKeywords[] = $varValue;
        }
      }
    }

    $objProduct->search_keywords = implode(', ',$arrKeywords);
    $objProduct->save();
  }

  /**
   * Reset fallback checkbox for other variants of a product.
   *
   * @param mixed          $varValue
   * @param \DataContainer $dc
   *
   * @return mixed
   */
  public function reset($varValue, \DataContainer $dc)
  {
    if (!$dc->activeRecord->pid) {
      return $varValue;
    }

    if ($varValue)
    {
      \Database::getInstance()
        ->prepare("UPDATE tl_iso_product SET fallback='' WHERE pid=? AND id!=?")
        ->execute($dc->activeRecord->pid, $dc->activeRecord->id);
    }

    return $varValue;
  }

}