<?php // Newsletter Builder CMS Plugin Menu Functions

//
function nlb_pluginMenu_redirectToCodeGenerator() {
  redirectBrowserToURL("?menu=_codeGenerator&_generator=nlb_codeGenerator");
}

//
function nlb_pluginMenu_importEmails() {
  global $TABLE_PREFIX;
  $errorsAndAlerts = '';

  // error checking
  // if not submitted from plugin form (no emails field) and listNum sent but blank, assume user is trying to add emails to a mailinst list they haven't saved yet
  if (!array_key_exists('emails', $_REQUEST) && array_key_exists('listNum', $_REQUEST) && !$_REQUEST['listNum']) { 
    die("Please save the mailing list first before adding users.");
  }
  
  // importEmails
  if (@$_REQUEST['submitForm'] && @$_REQUEST['emails']) {
    list($accepted, $rejected) = _nlb_emailListParser(@$_REQUEST['emails']);

    // get list of duplicates (emails that are already in database)
    $subscriberTable = $TABLE_PREFIX . nlb_subscriber_table();
    $emailField      = $GLOBALS['NLB_ALT_ENABLED'] ? $GLOBALS['NLB_ALT_FIELD_EMAIL']     : 'email';

    $emailsAsCSV     = mysql_escapeCSV($accepted);
    $duplicates      = array_pluck(mysql_select_query("SELECT `$emailField` FROM `$subscriberTable` WHERE `$emailField` IN ($emailsAsCSV)", true), 0);
    $accepted        = array_diff($accepted, $duplicates);

    // confirm unconfirmed duplicates (if they didn't confirm but we're importing them it means they previously confirmed)
    $duplicatesAsCSV = mysql_escapeCSV($duplicates);
    $where           = "`" .nlb_subscriber_confirmedField(). "` != 1 AND `$emailField` IN ($duplicatesAsCSV)";
    mysql_update($subscriberTable, null, $where, array(nlb_subscriber_confirmedField() => 1));

    // import emails
    foreach ($accepted as $email) {
      $newRecordNum = nlb_subscriber_create($email, 1);
      nlb_log(0, $newRecordNum, '8');
    }

    // add to specified list
    $listNum = intval(@$_REQUEST['listNum']);
    $listSubscribersAdded = 0;
    if ($listNum) {
      $subscribers2Lists   = $GLOBALS['TABLE_PREFIX'] . '_nlb_subscribers2lists';
      $subscriberTable     = $GLOBALS['TABLE_PREFIX'] . nlb_subscriber_table();
      $subscriberNumsAsCSV = mysql_escapeCSV(array_pluck(mysql_select_query("SELECT `num` FROM `$subscriberTable` WHERE `$emailField` IN ($emailsAsCSV)", true), 0));
      
      // delete old subscriptions to list
      mysql_delete($subscribers2Lists, null, "subscriberNum IN ($subscriberNumsAsCSV) AND `listNum` = $listNum");
      $listSubscribersDeleted = mysqli()->affected_rows;

      // add new subscriptions to list
      $addListQuery  = " INSERT INTO `$subscribers2Lists` (subscriberNum, listNum) ";
      $addListQuery .= " SELECT `num`, $listNum FROM $subscriberTable ";
      $addListQuery .= "  WHERE `num` IN ($subscriberNumsAsCSV) AND `" .nlb_subscriber_confirmedField(). "` = 1\n";
      mysqli()->query($addListQuery) or dieAsCaller("MySQL Error: ". mysqli()->error. "\n");
      $listSubscribersAdded = mysqli()->affected_rows - $listSubscribersDeleted;
    }
    
    // update list counts
    nls_lists_updateCount($listNum);
    
    // show alerts and rejected emails
    $acceptedCount  = count($accepted);
    $duplicateCount = count($duplicates);
    $rejectedCount  = count($rejected);
    $errorsAndAlerts .= "Email Import Complete: ";
    $errorsAndAlerts .= "$acceptedCount imported";
    $errorsAndAlerts .= ", $duplicateCount duplicate (already imported)";
    $errorsAndAlerts .= ", $rejectedCount invalid emails skipped (listed below)";
    if ($listNum) { $errorsAndAlerts .= ", $listSubscribersAdded added to mailing list"; }
    $errorsAndAlerts .= ".";
    
    $_REQUEST['emails'] = implode("\n", $rejected);
  }

  // show page content
  echo plugin_header($GLOBALS['NEWSLETTER_BUILDER_PLUGIN'] . " - Import Emails");
?>

  <?php if ($errorsAndAlerts): ?>
    <div style="color: #C00; font-weight: bold; font-size: 13px;"><?php echo $errorsAndAlerts; ?><br/><br/></div>
  <?php endif ?>

  <?php et("Copy and paste emails below to import (one per line):"); ?><br/>

    <input type="hidden" name="submitForm"    value="1" />
    <input type="hidden" name="_pluginAction" value="<?php echo htmlencode(__FUNCTION__) ?>" />

    <textarea name="emails" style="width: 400px !important; height: 400px" class="setAttr-spellcheck-false setAttr-wrap-off" rows="5" cols="50"><?php echo htmlencode(@$_REQUEST['emails']); ?></textarea><br/>
    
    <br/>The following actions will be taken for each email:<br/>
    <ul>
    <li>Invalid emails will be skipped.</li>
    <li>New emails will be added to subscriber table (<a href="?menu=<?php echo @nlb_subscriber_table() ?>"><?php echo @nlb_subscriber_table() ?></a>).</li>
    <li>"Newsletter Confirmed" will be set to true for each email.</li>
    <li>Emails will be added to this mailing list:
    <?php
      $records = mysql_select('_nlb_lists', "database_query != 1");
      $values  = array_pluck($records, 'num');
      $labels  = array_pluck($records, 'name');
      $htmlOptions = getSelectOptions(@$_REQUEST['listNum'], $values, $labels);
    ?>
    <select name="listNum" style="padding: 0; margin: 0">
      <option value=""><?php et('none'); ?></a>
      <?php echo $htmlOptions; ?>
    </select>
    </li>
    </ul>
    
    <?php echo adminUI_button(['name' => '_null_', 'type' => 'submit', 'btn-type' => 'default', 'label' => t('Import Emails >>'), 'value' => '1']); ?>

<?php
  // show footer
  echo plugin_footer();
  exit;
}


//
function nlb_pluginMenu_removeEmails() {
  global $TABLE_PREFIX;
  $errorsAndAlerts = '';
  
  // importEmails
  if (@$_REQUEST['submitForm'] && @$_REQUEST['emails']) {
    list($validEmails, $invalidEmails) = _nlb_emailListParser(@$_REQUEST['emails']);
    
    // get subscriber nums
    $emailsAsCSV         = mysql_escapeCSV($validEmails);
    $subscriberTable     = $GLOBALS['TABLE_PREFIX'] . nlb_subscriber_table();
    $emailField          = $GLOBALS['NLB_ALT_ENABLED'] ? $GLOBALS['NLB_ALT_FIELD_EMAIL'] : 'email';
    $subscriberNumsAsCSV = mysql_escapeCSV(array_pluck(mysql_select_query("SELECT `num` FROM `$subscriberTable` WHERE `$emailField` IN ($emailsAsCSV)", true), 0));

    // get list nums
    $subscribers2Lists   = $GLOBALS['TABLE_PREFIX'] . '_nlb_subscribers2lists';
    $result              = mysql_select_query("SELECT DISTINCT(`listNum`) FROM `$subscribers2Lists` WHERE `subscriberNum` IN ($subscriberNumsAsCSV)");
    $listNums            = array_pluck($result, 'listNum');
    
    // remove from all lists
    mysql_delete($subscribers2Lists, null, "subscriberNum IN ($subscriberNumsAsCSV)");
    
    // remove/unsubscribe emails
    foreach ($validEmails as $sEmail) {
      list($sNum, $sEmail, $sAuthkey, $sConfirmed, $sRecord) = nlb_subscriber_unsubscribe(null, $sEmail);
    }
    
    // update list counts
    foreach ($listNums as $listNum) { 
      nls_lists_updateCount($listNum);
    }
    
    // show alerts and rejected emails
    $acceptedCount  = count($validEmails);
    $rejectedCount  = count($invalidEmails);
    $errorsAndAlerts .= "Email Removal Complete: $acceptedCount valid emails processed, $rejectedCount invalid emails skipped (listed below).";
    $_REQUEST['emails'] = implode("\n", $invalidEmails);
  }

  // show page content
  echo plugin_header($GLOBALS['NEWSLETTER_BUILDER_PLUGIN'] . " - Remove Emails");
?>

  <?php if ($errorsAndAlerts): ?>
    <div style="color: #C00; font-weight: bold; font-size: 13px;"><?php echo $errorsAndAlerts; ?><br/><br/></div>
  <?php endif ?>

  <?php et("Copy and paste emails below to remove (one per line):"); ?><br/>

    <input type="hidden" name="submitForm"    value="1" />
    <input type="hidden" name="_pluginAction" value="<?php echo htmlencode(__FUNCTION__) ?>" />

    <textarea name="emails" style="width: 400px !important; height: 400px" class="setAttr-spellcheck-false setAttr-wrap-off" rows="5" cols="50"><?php echo htmlencode(@$_REQUEST['emails']); ?></textarea><br/>

    <br/>The following actions will be taken for each email:<br/>
<?php
  $mainTableStyle = $GLOBALS['NLB_ALT_ENABLED'] ? 'text-decoration: line-through'  : 'color: #C00; font-weight: bold';
  $altTableStyle  = $GLOBALS['NLB_ALT_ENABLED'] ? 'color: #C00; font-weight: bold' : 'text-decoration: line-through';
?>

    <ul>
    <li>Invalid emails will be skipped.</li>
    <?php if (nlb_subscriber_table() == '_nlb_subscribers'): ?><?php endif ?>
    <li>Emails will be removed from all <a href="?menu=_nlb_lists">mailing lists</a>.</li>
    <li style="<?php echo $mainTableStyle ?>">Emails will be removed from subscriber table (<a href="?menu=<?php echo @nlb_subscriber_table() ?>"><?php echo @nlb_subscriber_table() ?></a>), if using default subscriber table.</li>
    <li style="<?php echo $altTableStyle ?>">Emails will have "Newsletter Confirmed" unchecked in subscriber table (<a href="?menu=<?php echo @nlb_subscriber_table() ?>"><?php echo @nlb_subscriber_table() ?></a>), if using alternate subscriber table.</li>
    </ul>

    <?php echo adminUI_button(['name' => '_null_', 'type' => 'submit', 'btn-type' => 'default', 'label' => t('Remove Emails >>'), 'value' => '1']); ?>

<?php
  // show footer
  echo plugin_footer();
  exit;
}

// parse email list and return a list of accepted (valid) emails and rejected (invalid) emails
// list($validEmails, $invalidEmails) = _nlb_emailListParser($emailList);
function _nlb_emailListParser($emailList) {
  $lines    = array_filter(preg_split("/\r?\n/", $emailList));

  // process lines
  $accepted = array();
  $rejected = array();
  foreach ($lines as $line) {
    $matches = isValidEmail($line);
    if ($matches) {
      foreach ($matches as $match) { $accepted[] = strtolower($match[0]); }
    }
    else    { $rejected[] = $line; }
  }
  $accepted = array_unique($accepted);
  $rejected = array_unique($rejected);
  
  //
  return array($accepted, $rejected);  
}


?>