<?php

/**
 * News notification extension for Contao
 *
 * Copyright (c) 2016 Benjamin Roth
 *
 * @link    http://www.esales-media.de
 * @license commercial
 */

/**
 * Palettes
 */

$GLOBALS['TL_DCA']['tl_news_archive']['palettes']['__selector__'][] = 'nc_enable';
$GLOBALS['TL_DCA']['tl_news_archive']['palettes']['default'] = str_replace('{protected_legend:hide}','{nc_legend:hide},nc_enable;{protected_legend:hide}',$GLOBALS['TL_DCA']['tl_news_archive']['palettes']['default']);

/**
 * Subpalettes
 */

$GLOBALS['TL_DCA']['tl_news_archive']['subpalettes']['nc_enable'] = 'nc_notification,nc_notification_groups';

/**
 * Fields
 */

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

$GLOBALS['TL_DCA']['tl_news_archive']['fields']['nc_notification_groups'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_news_archive']['nc_notification_groups'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'foreignKey'              => 'tl_member_group.name',
  'eval'                    => array('mandatory'=>true, 'multiple'=>true,'tl_class'=>'clr'),
  'sql'                     => "blob NULL",
  'relation'                => array('type'=>'hasMany', 'load'=>'lazy')
);

$GLOBALS['TL_DCA']['tl_news_archive']['fields']['nc_notification'] = array
(
  'label'                     => &$GLOBALS['TL_LANG']['tl_news_archive']['nc_notification'],
  'exclude'                   => true,
  'inputType'                 => 'select',
  'options_callback'          => array('tl_news_archive_eSM_nc_news', 'getNotificationChoices'),
  'eval'                      => array('mandatory'=>true,'includeBlankOption'=>true, 'chosen'=>true, 'tl_class'=>'w50'),
  'sql'                       => "int(10) unsigned NOT NULL default '0'"
);

/**
 * Provide miscellaneous methods that are used by the data configuration array.
 *
 * @author Benjamin Roth <http://www.esales-media.de>
 */
class tl_news_archive_eSM_nc_news extends \Backend
{

  public function __construct()
  {
    parent::__construct();
  }

  /**
   * Get notification choices
   *
   * @return array
   */
  public function getNotificationChoices()
  {
    $arrChoices = array();
    $objNotifications = \Database::getInstance()->execute("SELECT id,title FROM tl_nc_notification WHERE type='news_submitted' ORDER BY title");

    while ($objNotifications->next()) {
      $arrChoices[$objNotifications->id] = $objNotifications->title;
    }

    return $arrChoices;
  }
}