<?php

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

namespace eSM_nc_news;

class NewsNotifications extends \System
{
  /**
   * Make the constuctor public
   */
  public function __construct()
  {
    parent::__construct();
  }

  public function sendNotifications()
  {
    // Get archives with notifications enabled
    $Archives = \NewsArchiveModel::findBy('nc_enable','1');

    if ($Archives !== null)
    {
      while ($Archives->next())
      {
        $Archive = $Archives->current();
        $arrGroupIds = deserialize($Archive->nc_notification_groups,true);
        $time = \Date::floorToMinute();

        // Do we have new news items
        $News = \Database::getInstance()->prepare("SELECT id, headline, date FROM tl_news WHERE pid = ? AND nc_sent != '1' AND (start='' OR start<='$time') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1' ORDER BY date DESC, time DESC")
                                        ->execute($Archive->id);

        // Load groups and notification models if we have news to share
        if ($News->numRows && ($Notification = \NotificationCenter\Model\Notification::findByPk($Archive->nc_notification)) !== null && ($Groups = \MemberGroupModel::findMultipleByIds($arrGroupIds)) !== null)
        {

          while ($Groups->next())
          {
            // Skip disabled groups
            if ($Groups->disable)
            {
              continue;
            }

            // Get group members
            $Members = \MemberModel::findBy(array("groups LIKE '%\"".$Groups->id."\"%'","login='1' AND (start='' OR start<='$time') AND (stop='' OR stop>'" . ($time + 60) . "') AND disable=''"),null);

            // Send notification to each member
            if ($Members !== null)
            {
              $arrNews = array();
              $News->reset();
              while ($News->next())
              {
                $arrNews[] = date('d.m.Y',$News->date)." - ".$News->headline;
              }
              while ($Members->next())
              {
                $Notification->send(array
                (
                  'member_email'      => $Members->email,
                  'member_firstname' => $Members->firstname,
                  'member_lastname' => $Members->lastname,
                  'news_topics'       => implode("\n",$arrNews),
                  'news_topics_html'  => "<ul>\n<li>".implode("</li>\n<li>",$arrNews)."</li>\n</ul>"
                ),
                $GLOBALS['TL_LANGUAGE']);
              }
            }

            // Flag news as sent
            $arrNewsIds = $News->fetchEach('id');
            \Database::getInstance()->execute("UPDATE tl_news SET nc_sent = '1' WHERE id IN (".implode(',',$arrNewsIds).")");
          }
        }
      }
    }
  }
}