<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
class Core_AdminMessageController extends Core_Controller_Action_Admin
{
  public function mailAction()
  {
    // Get navigation
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('core_admin_main_emailsettings', array(), 'core_admin_message_mail');

    $this->view->form = $form = new Core_Form_Admin_Message_Mail();

    // let the level_ids be specified in GET string
    $level_ids = $this->_getParam('level_id', false);
    if (is_array($level_ids)) {
      $form->target->setValue($level_ids);
    }

    if (!$this->getRequest()->isPost()) {
      return;
    }
		$user_admin = Zend_Registry::isRegistered('user_admin') ? Zend_Registry::get('user_admin') : null;
		if(empty($user_admin)) {
			return;
		}
    if (!$form->isValid($this->getRequest()->getPost())) {

      if ($_POST['choose_member'] == '1' && empty($_POST['member_name'])) {
        $form->addError("Member Name * Please complete this field - it is required.");
      }

      if ($_POST['choose_member'] == '5' && empty($_POST['external_emails'])) {
        $form->addError("Emails * Please complete this field - it is required.");
      }

      return;
    }

    $values = $form->getValues();

    $table = Engine_Api::_()->getItemTable('user');

    //Specific Member
    if ($values['choose_member'] == '1') {
      $user = Engine_Api::_()->getItem('user', $values['user_id']);
      $emails[] = $user->email;
    }

    //Other Members
    else if ($values['choose_member'] == '4') {

      $select = new Zend_Db_Select($table->getAdapter());
      $select
        ->from($table->info('name'), 'email')
        ->where('enabled = ?', true)
        ->where('verified = ?', true)
        ->where('disable_adminemail = ?', '0'); // Do not email disabled members

      $level_ids = $this->_getParam('member_levels');
      if (is_array($level_ids) && !empty($level_ids)) {
        $select->where('level_id IN (?)', $level_ids);
      }

      if (!empty($values['networks']) && engine_count($values['networks']) > 0) {
        $resultsN = $this->networksJoinedMembers($values['networks']);
        $networkUserIds = array();
        if (engine_count($resultsN) > 0) {
          foreach ($resultsN as $resultN) {
            $networkUserIds[] = $resultN->user_id;
          }
          $select->where('user_id IN (?)', $networkUserIds);
        }
      }

      if (!empty($values['profile_types']) && engine_count($values['profile_types']) > 0) {
        $resultsP = $this->profileTypesMembers($values['profile_types']);
        $profiletypeUserIds = array();
        if (engine_count($resultsP) > 0) {
          foreach ($resultsP as $resultP) {
            $profiletypeUserIds[] = $resultP->item_id;
          }
          $select->where('user_id IN (?)', $profiletypeUserIds);
        }
      }

      $emails = array();
      foreach ($select->query()->fetchAll(Zend_Db::FETCH_COLUMN, 0) as $email) {
        $emails[] = $email;
      }
    }
    //External Emails
    else if ($values['choose_member'] == '5') {
      $emails = explode(',', $values['external_emails']);
    }

    // temporarily enable queueing if requested
    $temporary_queueing = Engine_Api::_()->getApi('settings', 'core')->core_mail_queueing;
    if (isset($values['queueing']) && $values['queueing']) {
      Engine_Api::_()->getApi('settings', 'core')->core_mail_queueing = 1;
    }

    $view = Zend_Registry::isRegistered('Zend_View') ? Zend_Registry::get('Zend_View') : null;
    $message = $view->partial('_emailhtml.tpl', 'core', array('body' => nl2br($values['body'])));

    $dom = new DomDocument();
    $dom->loadHTML($message);
    $message = $dom->saveHTML();

    $mailApi = Engine_Api::_()->getApi('mail', 'core');

    $mail = $mailApi->create();
    $mail
      ->setFrom($values['from_address'], $values['from_name'])
      ->setSubject($values['subject'])
      ->setBodyHtml($message)
    ;

    if (!empty($values['body_text'])) {
      $mail->setBodyText($values['body_text']);
    } else {
      $mail->setBodyText(strip_tags($values['body']));
    }

    foreach ($emails as $email) {
      $mail->addTo($email);
    }

    $mailApi->send($mail);

    $mailComplete = $mailApi->create();
    $mailComplete
      ->addTo(Engine_Api::_()->user()->getViewer()->email)
      ->setFrom($values['from_address'], $values['from_name'])
      ->setSubject('Mailing Complete: ' . $values['subject'])
      ->setBodyHtml('Your email blast to your members has completed.  Please note that, while the emails have been
        sent to the recipients\' mail server, there may be a delay in them actually receiving the email due to
        spam filtering systems, incoming mail throttling features, and other systems beyond SocialEngine\'s control.')
    ;
    $mailApi->send($mailComplete);

    // emails have been queued (or sent); re-set queueing value to original if changed
    if (isset($values['queueing']) && $values['queueing']) {
      Engine_Api::_()->getApi('settings', 'core')->core_mail_queueing = $temporary_queueing;
    }

    $this->view->form = null;
    $this->view->status = true;
  }

  public function networksJoinedMembers($networks)
  {
    $userNetworkTable = Engine_Api::_()->getDbtable('membership', 'network');
    $select = $userNetworkTable->select()->where('resource_id IN (?)', $networks);
    return $userNetworkTable->fetchAll($select);
  }

  public function profileTypesMembers($profileTypes)
  {
    $valuesTable = Engine_Api::_()->fields()->getTable('user', 'values');
    $valuesTableName = $valuesTable->info('name');
    $select = $valuesTable->select()
      ->from($valuesTableName)
      ->where($valuesTableName . '.value IN (?)', $profileTypes)
      ->where($valuesTableName . '.field_id = ?', 1);
    return $valuesTable->fetchAll($select);
  }
}