#!/usr/bin/perl
# ----------------------------------------------------------------------------
# This software is Copyright (C) 2007, All Rights Reserved
# ----------------------------------------------------------------------------
# This program is protected by local and international copyright laws. Any
# use of this program is subject to the the terms of the license agreement
# included as part of this distribution archive. Any other uses are strictly
# prohibited without the written permission of the Vendor and all
# other rights are reserved.
# -----------------------------------------------------------------------------
# Warning : Modifying this program violates your license agreement!
# -----------------------------------------------------------------------------

package IT::ArtMan::EmailAlerts;

  # load modules
  use strict;

  use IT::Globals;

  use vars qw(%VALID_ALERT_TYPES);
  %VALID_ALERT_TYPES = map { $_ => 1 } qw(articleCreated articlePublished articleModified articleErased);

# ------------------------------------------------------------------------------
# Function    : onArticleSave
# Description :
# Usage       : &IT::ArtMan::EmailAlerts::onArticleSave();
# ------------------------------------------------------------------------------

sub onArticleSave {
  my $attr = shift || die "no attr provided";

  my $article           = $attr->{'newOrUpdatedFields'};
  my $isNewRecord       = $attr->{'isNewRecord'};
  my $isNowVisible      = $article->{'status'} eq 'visible';
  my $previouslyVisible = $attr->{'originalRecord'}{'status'} eq 'visible'; # will always be false for new records
  my $hasBecomeVisible  = !$previouslyVisible && $isNowVisible;

  # get alert type
  my @alerts;
  if ($isNewRecord)      { push @alerts, 'articleCreated'; }
  if (!$isNewRecord)     { push @alerts, 'articleModified'; }
  if ($hasBecomeVisible) { push @alerts, 'articlePublished'; }

  # send alert
  &sendEmailAlerts($article, \@alerts);
}

# ------------------------------------------------------------------------------
# Function    : onArticleErase
# Description :
# Usage       : &IT::ArtMan::EmailAlerts::onArticleErase();
# ------------------------------------------------------------------------------

sub onArticleErase {
  my $attr = shift || die "no attr provided";

  foreach my $article (@{$attr->{'selectedRecords'}}) {
    &IT::ArtMan::EmailAlerts::sendEmailAlerts($article, ['articleErased']);
  }
}

# ------------------------------------------------------------------------------
# Function    : sendEmailAlerts
# Description :
# Usage       : &IT::ArtMan::EmailAlerts::sendEmailAlerts($articleRecord, @alertTypes);
# ------------------------------------------------------------------------------

sub sendEmailAlerts {
  my $article    = shift || die "no article record specified!";
  my $alertTypes = shift || die "no alert type specified!";

  # error checking
  if (&IT::App::inDemoMode()) { return; }
  foreach my $alertType (@$alertTypes) {
    if (!$VALID_ALERT_TYPES{$alertType}) { die "Invalid alert type '$alertType'!"; }
  }

  # get article category nums
  my @categoryNums;
  my $categoryFieldnames = &IT::ArtMan::CustomFields::ArticleEditor::PrimaryCategory::getArticleCategoryFieldnames('all');
  foreach my $categoryFieldname (@$categoryFieldnames) {
    my $categoryNum = $article->{ $categoryFieldname };
    if ($categoryNum) { push @categoryNums, $categoryNum; }
  }

  # send message for each recipient
  my $categories            = &IT::ArtMan::CustomMenus::Category::getHashOfCategoryRecords();
  my $template              = "admin/emails/articleNotification.txt";
  my $primaryCategory       = $categories->{ $article->{'categoryNum'} } || die "Couldn't find article category '$article->{'categoryNum'}'!";
  my $placeholders          = &IT::ArtMan::CustomMenus::Publish::createPlaceholders($primaryCategory, $article, $template);
  my $recipientsToEventName = &_getRecipientsToEventNames($alertTypes, \@categoryNums);
  foreach my $recipient (keys %$recipientsToEventName) {
    $placeholders->{'to'}    = $recipient;
    $placeholders->{'event'} = $recipientsToEventName->{$recipient};
    my $message = &template($template, $placeholders);

    eval { &IT::Email::sendMessage($message); };
    if ($@) {
      my $evalError = $@;
      $evalError =~ s/\s+$//s;  # remove trailing whitespace on error.
      &IT::App::alert("Error sending email alert to $recipient ($evalError)");
    }
  }

}

# ------------------------------------------------------------------------------
# Function    : _getRecipientsToEventNames
# Description :
# Usage       : my $recipientsToEventNames = &_getRecipientsToEventNames($alertType, $categoryNum);
# ------------------------------------------------------------------------------

sub _getRecipientsToEventNames {
  my $alertTypesArray = shift || die "no alert types specified";
  my $categoryNums    = shift || die "no categoryNums specified!";
  my %alertsHash      = map { $_ => 1 } @$alertTypesArray;

  # create rowcode
  my $recipientsToEventNames = {};
  my $rowcode = sub {
    my $record = shift;

    # check for category access
    my($accessRights, $emailRights) = &IT::ArtMan::CustomFields::AccountManager::CategoryRights::getCategoryRightsHashesFromRecordValue($record->{'categoryRights'});
    my $hasCategoryAccess = 0;
    foreach my $categoryNum (@$categoryNums) {
      unless ($emailRights->{'all'} || $emailRights->{$categoryNum}) { next; }
      $hasCategoryAccess = 1;
      last;
    }
    unless ($hasCategoryAccess) { return; }

    # get event name
    my $eventName;
    if    ($record->{'emailOnArticlePublish'} && $alertsHash{'articlePublished'}) { $eventName = 'published'; }
    elsif ($record->{'emailOnArticleCreated'} && $alertsHash{'articleCreated'})   { $eventName = 'created'; }
    elsif ($record->{'emailOnArticleModified'} && $alertsHash{'articleModified'}) { $eventName = 'modified'; }
    elsif ($record->{'emailOnArticleErased'} && $alertsHash{'articleErased'})     { $eventName = 'erased'; }

    # add to recipient list
    if ($eventName) {
      $recipientsToEventNames->{"\"$record->{'fullname'}\" <$record->{'email'}>"} = $eventName;
    }
  };

  # get list of recipients
  &IT::FileLock::getLock('shared');
  &IT::DB::list({
    'tableName'  => $TABLE_PREFIX . "accounts",
    'rowcode'    => $rowcode,
  });
  &IT::FileLock::releaseLock();

  return $recipientsToEventNames;
}

# ----------------------------------------------------------------------------
# end of file
1;

