<?php

/**
 * Slick slider for Contao
 *
 * Copyright (c) 2016 Benjamin Roth
 *
 * @license LGPL-3.0+
 */


/**
 * Table tl_content
 */

/**
 * Add callback
 */
$GLOBALS['TL_DCA']['tl_content']['config']['onload_callback'][] = array('tl_content_eSM_slider', 'showJsLibraryHint');
$GLOBALS['TL_DCA']['tl_content']['config']['onsubmit_callback'][] = array('tl_content_eSM_slider', 'insertEndElement');

/**
 * Add palettes to tl_content
 */
$GLOBALS['TL_DCA']['tl_content']['palettes']['__selector__'][] = 'eSM_addImage';
$GLOBALS['TL_DCA']['tl_content']['palettes']['__selector__'][] = 'eSM_addText';
$GLOBALS['TL_DCA']['tl_content']['palettes']['__selector__'][] = 'eSM_slider_addImageLink';
$GLOBALS['TL_DCA']['tl_content']['palettes']['swiperSliderStart'] = '{type_legend},type;{swiper_legend},eSM_slider_autoPlaySpeed,eSM_slider_speed,eSM_slider_initialSlide,eSM_slider_preload,eSM_slider_slidesToShow,eSM_slider_slidesToScroll,eSM_slider_infinite,eSM_slider_arrows,eSM_slider_pagination,eSM_slider_stopOnInteraction,eSM_slider_fade,eSM_slider_adaptiveHeight;{image_legend},eSM_addImage;{template_legend:hide},customTpl;{protected_legend:hide},protected;{expert_legend:hide},guests,cssID,space;{invisible_legend:hide},invisible,start,stop';
$GLOBALS['TL_DCA']['tl_content']['palettes']['swiperSliderStop'] = '{type_legend},type;{template_legend:hide},customTpl;{protected_legend:hide},protected;{expert_legend:hide},guests;{invisible_legend:hide},invisible,start,stop';
$GLOBALS['TL_DCA']['tl_content']['palettes']['swiperSliderSlideStart'] = '{type_legend},type;{swiper_legend},eSM_addImage;{template_legend:hide},customTpl;{protected_legend:hide},protected;{expert_legend:hide},guests,cssID,space;{invisible_legend:hide},invisible,start,stop';
$GLOBALS['TL_DCA']['tl_content']['palettes']['swiperSliderSlideStop'] = '{type_legend},type;{template_legend:hide},customTpl;{protected_legend:hide},protected;{expert_legend:hide},guests;{invisible_legend:hide},invisible,start,stop';
$GLOBALS['TL_DCA']['tl_content']['palettes']['swiperSliderImage'] = '{type_legend},type;{swiper_legend},multiSRC,size,eSM_slider_bgSize,eSM_slider_bgPosition,eSM_slider_minHeight,eSM_slider_bgOpacity,eSM_slider_bgRepeat,eSM_slider_addImageLink,eSM_addText;{template_legend:hide},customTpl;{protected_legend:hide},protected;{expert_legend:hide},guests,cssID,space;{invisible_legend:hide},invisible,start,stop';


$GLOBALS['TL_DCA']['tl_content']['subpalettes']['eSM_addImage'] = 'multiSRC,size,eSM_slider_bgSize,eSM_slider_bgPosition,eSM_slider_minHeight,eSM_slider_bgOpacity,eSM_slider_bgRepeat';
$GLOBALS['TL_DCA']['tl_content']['subpalettes']['eSM_addText'] = 'eSM_slider_text,eSM_slider_url';
$GLOBALS['TL_DCA']['tl_content']['subpalettes']['eSM_slider_addImageLink'] = 'imageUrl,fullsize';

/**
 * Add fields to tl_content
 */

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_autoPlaySpeed'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_autoPlaySpeed'],
  'exclude'                 => true,
  'inputType'               => 'text',
  'eval'                    => array('tl_class'=>'w50','rgxp'=>'digit'),
  'sql'                     => "int(10) unsigned NOT NULL default '0'"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_speed'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_speed'],
  'exclude'                 => true,
  'inputType'               => 'text',
  'default'                 => '500',
  'eval'                    => array('tl_class'=>'w50','rgxp'=>'digit'),
  'sql'                     => "int(10) unsigned NOT NULL default '0'"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_initialSlide'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_initialSlide'],
  'exclude'                 => true,
  'inputType'               => 'text',
  'eval'                    => array('tl_class'=>'w50','rgxp'=>'digit'),
  'sql'                     => "int(10) unsigned NOT NULL default '0'"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_slidesToShow'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_slidesToShow'],
  'exclude'                 => true,
  'inputType'               => 'text',
  'eval'                    => array('rgxp'=>'natural','minval'=>1,'tl_class'=>'w50'),
  'sql'                     => "int(10) unsigned NOT NULL default '1'"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_slidesToScroll'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_slidesToScroll'],
  'exclude'                 => true,
  'inputType'               => 'text',
  'eval'                    => array('rgxp'=>'natural','minval'=>1,'tl_class'=>'w50'),
  'sql'                     => "int(10) unsigned NOT NULL default '1'"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_infinite'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_infinite'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_arrows'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_arrows'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_pagination'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_pagination'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_stopOnInteraction'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_stopOnInteraction'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_preload'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_preload'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default '1'"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_fade'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_fade'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_adaptiveHeight'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_adaptiveHeight'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_text'] = array
(
    'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_text'],
    'exclude'                 => true,
    'inputType'               => 'textarea',
    'eval'                    => array('rows'=>2,'style'=>'height: 2em;', 'maxlength'=>64),
    'sql'                     => "varchar(64) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_url'] = array
(
    'label'                   => &$GLOBALS['TL_LANG']['MSC']['url'],
    'exclude'                 => true,
    'inputType'               => 'text',
    'eval'                    => array('rgxp'=>'url', 'decodeEntities'=>true, 'maxlength'=>255, 'fieldType'=>'radio', 'filesOnly'=>true, 'tl_class'=>'w50 wizard'),
    'wizard' => array
    (
        array('tl_content', 'pagePicker')
    ),
    'sql'                     => "varchar(255) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_addImage'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['addImage'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('submitOnChange'=>true),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_addText'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_addText'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'clr', 'submitOnChange'=>true),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_minHeight'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_minHeight'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'w50 m12'),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_addImageLink'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_addImageLink'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('tl_class'=>'clr w50','submitOnChange'=>true),
  'sql'                     => "char(1) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_bgPosition'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_bgPosition'],
  'exclude'                 => true,
  'inputType'               => 'select',
  'options'                 => array
  (
    '0 0' => 'Links | Oben',
    '50% 0' => 'Mitte | Oben',
    '100% 0' => 'Rechts | Oben',
    '0 50%' => 'Links | Mitte',
    '50% 50%' => 'Mitte | Mitte',
    '100% 50%' => 'Rechts | Mitte',
    '0 100%' => 'Links | Unten',
    '50% 100%' => 'Mitte | Unten',
    '100% 100%' => 'Rechts | Unten',
  ),
  'eval'                    => array('tl_class' => 'w50','includeBlankOption'=>true),
  'sql'                     => "varchar(16) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_bgSize'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_bgSize'],
  'exclude'                 => true,
  'inputType'               => 'select',
  'options'                 => array
  (
    'contain' => 'Proportional',
    '100% 100%' => 'Verzerrt',
    'auto auto' => 'Originalgröße',
  ),
  'eval'                    => array('tl_class' => 'w50','includeBlankOption'=>true,'blankOptionLabel'=>'Beschnitten'),
  'sql'                     => "varchar(16) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_bgRepeat'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_bgRepeat'],
  'exclude'                 => true,
  'inputType'               => 'select',
  'options'                 => array
  (
    'repeat-x' => 'Horizontal wiederholen',
    'repeat-y' => 'Vertikal wiedeholen',
    'no-repeat' => 'Nicht wiederholen',
  ),
  'eval'                    => array('tl_class' => 'w50','includeBlankOption'=>true,'blankOptionLabel'=>'Wiederholen'),
  'sql'                     => "varchar(16) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['eSM_slider_bgOpacity'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_content']['eSM_slider_bgOpacity'],
  'exclude'                 => true,
  'inputType'               => 'select',
  'options'                 => array
  (
    '10' => '10%',
    '20' => '20%',
    '30' => '30%',
    '40' => '40%',
    '50' => '50%',
    '60' => '60%',
    '70' => '70%',
    '80' => '80%',
    '90' => '90%',
    '100' => '100%',
  ),
  'eval'                    => array('tl_class' => 'w50','includeBlankOption'=>true),
  'sql'                     => "varchar(16) NOT NULL default ''"
);

$GLOBALS['TL_DCA']['tl_content']['fields']['multiSRC']['load_callback'][] = array('tl_content_eSM_slider', 'setMultiSrcFlags');


class tl_content_eSM_slider extends Backend
{

  /**
   * Import the back end user object
   */
  public function __construct()
  {
    parent::__construct();
    $this->import('BackendUser', 'User');
  }

  /**
   * Show a hint if a JavaScript library needs to be included in the page layout
   *
   * @param object
   */
  public function showJsLibraryHint($dc)
  {
    if ($_POST || Input::get('act') != 'edit')
    {
      return;
    }

    // Return if the user cannot access the layout module (see #6190)
    if (!$this->User->hasAccess('themes', 'modules') || !$this->User->hasAccess('layout', 'themes'))
    {
      return;
    }

    $objCte = ContentModel::findByPk($dc->id);

    if ($objCte === null)
    {
      return;
    }

    switch ($objCte->type)
    {
      case 'swiperSliderStart':
      case 'swiperSliderStop':
      case 'swiperSliderSlideStart':
      case 'swiperSliderSlideStop':
      case 'swiperSliderImage':
        Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplatesJQuery'], 'js_swiper'));
        break;
    }
  }

  /**
   * Automatically insert end element if start element ist about to be added
   *
   * @param DataContainer $dc
   */
  public function insertEndElement(\DataContainer $dc)
  {
    $activeRecord = $dc->activeRecord;
    if (!$activeRecord) {
      return;
    }

    if ($activeRecord->type === 'swiperSliderStart' || $activeRecord->type === 'swiperSliderSlideStart') {

      // Find the next wrapper element
      $nextElement = \Database::getInstance()
        ->prepare("
					SELECT type
					FROM tl_content
					WHERE pid = ?
						AND (ptable = ? OR ptable = ?)
            AND type IN ('swiperSliderSlideStart', 'swiperSliderSlideStop','swiperSliderStart', 'swiperSliderStop')
						AND sorting > ?
					ORDER BY sorting ASC
					LIMIT 1
				")
        ->execute(
          $activeRecord->pid,
          $activeRecord->ptable ?: 'tl_article',
          $activeRecord->ptable === 'tl_article' ? '' : $activeRecord->ptable,
          $activeRecord->sorting
        );

      // Check if a stop element should be created
      if (
        !$nextElement->type
        || ($activeRecord->type === 'swiperSliderStart' && ($nextElement->type === 'swiperSliderStart'))
        || ($activeRecord->type === 'swiperSliderSlideStart' && ($nextElement->type === 'swiperSliderSlideStart' || $nextElement->type === 'swiperSliderStart' || $nextElement->type === 'swiperSliderStop'))
      ) {
        \Database::getInstance()
          ->prepare('INSERT INTO tl_content %s')
          ->set(array(
            'pid' => $activeRecord->pid,
            'ptable' => $activeRecord->ptable ?: 'tl_article',
            'type' => substr($activeRecord->type, 0, -5) . 'Stop',
            'sorting' => $activeRecord->sorting + 1,
            'tstamp' => time(),
          ))
          ->execute();
      }

    }
  }

  /**
   * Dynamically add flags to the "multiSRC" field
   *
   * @param mixed                $varValue
   * @param Contao\DataContainer $dc
   *
   * @return mixed
   */
  public function setMultiSrcFlags($varValue, Contao\DataContainer $dc)
  {
    if ($dc->activeRecord)
    {
      switch ($dc->activeRecord->type)
      {
        case 'swiperSliderStart':
        case 'swiperSliderSlideStart':
        case 'swiperSliderImage':
          $GLOBALS['TL_DCA'][$dc->table]['fields'][$dc->field]['eval']['isGallery'] = true;
          $GLOBALS['TL_DCA'][$dc->table]['fields'][$dc->field]['eval']['extensions'] = Contao\Config::get('validImageTypes').'mp4,ogv,webm,mov';
          break;
      }
    }
    return $varValue;
  }
}