<?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']['palettes']['default'] = str_replace(array('{publish_legend}','{publish_legend:hide}'),array('{nc_legend:hide},nc_sent,nc_testmail;{publish_legend}','{nc_legend:hide},nc_sent,nc_testmail;{publish_legend:hide}'),$GLOBALS['TL_DCA']['tl_news']['palettes']['default']);


/**
 * Fields
 */

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

$GLOBALS['TL_DCA']['tl_news']['fields']['nc_testmail'] = array
(
  'label'                   => &$GLOBALS['TL_LANG']['tl_news']['nc_testmail'],
  'exclude'                 => true,
  'inputType'               => 'checkbox',
  'eval'                    => array('doNotSaveEmpty'=>true),
  'load_callback'         => array
  (
    array('tl_news_eSM_nc_news', 'loadTestmail'),
  ),
  'save_callback' => array
  (
    array('tl_news_eSM_nc_news', 'sendTestmail'),
  ),
);


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

  public function __construct()
  {
    parent::__construct();
    $this->import('BackendUser', 'User');
  }

  /**
   * Reset field
   *
   * @return array
   */
  public function loadTestmail($varValue, DataContainer $dc)
  {
    return '';
  }

  /**
   * Reset field
   *
   * @return array
   */
  public function sendTestmail($varValue, DataContainer $dc)
  {
    if ($varValue)
    {
      $News = \Contao\NewsModel::findByPk($dc->id);

      if ($News !== null && ($Archive = $News->getRelated('pid')) !== null && ($Notification = \NotificationCenter\Model\Notification::findByPk($Archive->nc_notification)) !== null)
      {
        $arrRow = array(
          'date' => date('d.m.Y',$News->date),
          'headline' => $News->headline,
          'teaser' => \Contao\StringUtil::substr(strip_tags(str_ireplace(array('<br />','<br>','<br/>','</p>','<p>'),' ',$News->teaser)),128)
        );

        if (($objJumpTo = $Archive->getRelated('jumpTo')) !== null)
        {
          $objJumpTo->loadDetails();
          $arrRow['url'] = ($objJumpTo->rootUseSSL ? 'https://' : 'http://') . $objJumpTo->domain . TL_PATH . '/' . \Controller::generateFrontendUrl($objJumpTo->row(),((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ? '/' : '/items/') . ((!\Config::get('disableAlias') && $News->alias != '') ? $News->alias : $News->id)).'?ltoken=%%_TOKEN_%%';
        }


        $arrNewsPlain[] = date('d.m.Y',$News->date).' - '.$News->headline;
        $arrNewsHtml[] = '<div style="margin-bottom: 15px;"><h3>'.$arrRow['date'].' '.$arrRow['headline'].'</h3><p>'.$arrRow['teaser'].'</p>'. ($arrRow['url'] ? '<p><a href="'.$arrRow['url'].'">&raquo; Neuigkeit lesen...</a></p>' : '') .'</div>';

        // User
        if (($Member = \MemberModel::findActiveByEmailAndUsername($this->User->email)) !== null)
        {
          $strLastname = $Member->firstname;
          $strFirstname = $Member->lastname;
          $strToken = \TokenLogin::getOrRenewUserToken($Member);
        } else {
          $arrSplitName = explode(" ", $this->User->name);
          $strLastname = array_pop($arrSplitName);
          $strFirstname = implode(" ", $arrSplitName);
          $strToken = '';
        }

        $Notification->send(array
        (
          'member_email'      => $this->User->email,
          'member_firstname' => $strFirstname,
          'member_lastname' => $strLastname,
          'news_topics'       => implode("\n",$arrNewsPlain),
          'news_topics_html'  => "<ul>\n<li>".str_replace('%%_TOKEN_%%',$strToken,implode("</li>\n<li>",$arrNewsHtml))."</li>\n</ul>",
          'member_login_token'  => $strToken
        ),
          $GLOBALS['TL_LANGUAGE']);

        Message::addConfirmation($GLOBALS['TL_LANG']['tl_news']['MSC']['nc_news_testletter']);
      }
    }
  }
}