/**
 * Send pending notifications.
 *
 * @param string $max_delayhours; default null for all.
 *
 */
function ct_sendPendingNotifications($max_delayhours = null)
{
    $res = churchcore_getTableData("cc_notificationtype", "delay_hours", $max_delayhours != null ? "delay_hours<={$max_delayhours}" : "");
    foreach ($res as $n) {
        // Check if there is a pending notifications for a person and domain_type
        $personANDtypes = db_query('SELECT n.person_id, n.domain_type FROM {cc_notification} n
          WHERE n.notificationtype_id=:nt_id AND (lastsenddate IS NULL OR
          (TIME_TO_SEC(TIMEDIFF(NOW(), lastsenddate)) / 3600)>:delay_hours)
          GROUP BY n.person_id, n.domain_type', array(':nt_id' => $n->id, ':delay_hours' => $n->delay_hours));
        // Collect all notifications in this type for each person and domain_type
        foreach ($personANDtypes as $personANDtype) {
            $notis = db_query('SELECT * FROM {cc_notification} n
                         WHERE n.person_id=:person_id and n.notificationtype_id=:nt_id and n.domain_type=:dt_id', array(':person_id' => $personANDtype->person_id, ':nt_id' => $n->id, ':dt_id' => $personANDtype->domain_type));
            // Get all logs for each notification after? each lastsenddate
            foreach ($notis as $noti) {
                $logs = db_query("SELECT l.txt AS text, DATE_FORMAT(datum, '%e.%c.%Y %H:%i') date FROM {cdb_log} l\n                          WHERE domain_type=:domain_type AND domain_id=:domain_id\n                            AND (:lastsenddate IS NULL OR TIME_TO_SEC(TIMEDIFF(datum, :lastsenddate))>0)\n                          ORDER BY datum DESC", array(":domain_type" => $personANDtype->domain_type, ":domain_id" => $noti->domain_id, ":lastsenddate" => $noti->lastsenddate));
                $messages = array();
                foreach ($logs as $log) {
                    $messages[] = $log;
                }
            }
            if (count($messages)) {
                $p = churchcore_getUserById($personANDtype->person_id);
                if ($p && $p->email) {
                    $data = array('surname' => $p->vorname, 'name' => $p->name, 'nickname' => $p->spitzname ? $p->spitzname : $p->vorname, 'notifyName' => t($personANDtype->domain_type), 'notifyType' => $n->bezeichnung, 'messages' => $messages);
                    $lang = getUserLanguage($personANDtype->person_id);
                    $content = getTemplateContent("email/notification", 'churchcore', $data, null, $lang);
                    churchcore_systemmail($p->email, "[" . getConf('site_name') . "] " . t2($lang, 'news.for.abo.x', t($personANDtype->domain_type)), $content, true);
                }
            }
            // update send date for notification
            $notis = db_query('UPDATE {cc_notification} n SET lastsenddate=NOW()
                         WHERE n.person_id=:person_id AND n.notificationtype_id=:nt_id AND n.domain_type=:dt_id', array(':person_id' => $personANDtype->person_id, ':nt_id' => $n->id, ':dt_id' => $personANDtype->domain_type));
        }
    }
}
/**
 * Send pending notifications. 
 * @param string $max_delayhours, can be null for all. 
 * 
 * TODO: rename nts/nt to something readable?
 */
function ct_sendPendingNotifications($max_delayhours = null)
{
    $nts = churchcore_getTableData("cc_notificationtype", "delay_hours", $max_delayhours != null ? "delay_hours<={$max_delayhours}" : "");
    foreach ($nts as $nt) {
        // Check if there is a pending notifications for a person and domain_type
        $personANDtypes = db_query('select n.person_id, n.domain_type from {cc_notification} n
             where n.notificationtype_id=:nt_id and (lastsenddate is null or
                  (time_to_sec(timediff(now(), lastsenddate)) / 3600)>:delay_hours)
                  group by n.person_id, n.domain_type', array(':nt_id' => $nt->id, ':delay_hours' => $nt->delay_hours));
        // Collect all notifications in this type for each person and domain_type
        foreach ($personANDtypes as $personANDtype) {
            $notis = db_query('select * from {cc_notification} n 
                where n.person_id=:person_id and n.notificationtype_id=:nt_id and n.domain_type=:dt_id', array(':person_id' => $personANDtype->person_id, ':nt_id' => $nt->id, ':dt_id' => $personANDtype->domain_type));
            $msg = "";
            // Get all logs for each notification after??? each lastsenddate
            foreach ($notis as $noti) {
                $logs = db_query("select l.txt, DATE_FORMAT(datum, '%e.%c.%Y %H:%i') date from {cdb_log} l where domain_type=:domain_type and domain_id=:domain_id\r\n          and (:lastsenddate is null or time_to_sec(timediff(datum, :lastsenddate))>0) order by datum desc", array(":domain_type" => $personANDtype->domain_type, ":domain_id" => $noti->domain_id, ":lastsenddate" => $noti->lastsenddate));
                foreach ($logs as $log) {
                    $msg .= "<li>{$log->date} - <i>{$log->txt}</i>";
                }
            }
            if ($msg != "") {
                $p = churchcore_getUserById($personANDtype->person_id);
                if ($p != null && $p->email != "") {
                    $msg = "<h3>Hallo {$p->vorname}!</h3>" . "<p>Hier Deine neuen Benachrichtigungen f&uuml;r " . t($personANDtype->domain_type) . ":</p>" . "<ul>{$msg}</ul>" . "<p><p><small>Einstellung f&uuml;r Versand: {$nt->bezeichnung}</small>";
                    churchcore_systemmail($p->email, "[" . variable_get('site_name') . "] Neue Abonnement-Benachrichtigung (" . t($personANDtype->domain_type) . ")", $msg, true);
                }
            }
            // update send date for notification
            $notis = db_query('update {cc_notification} n set lastsenddate=now()
                where n.person_id=:person_id and n.notificationtype_id=:nt_id and n.domain_type=:dt_id', array(':person_id' => $personANDtype->person_id, ':nt_id' => $nt->id, ':dt_id' => $personANDtype->domain_type));
        }
    }
}