<?php

/**
 * send messenger notifications
 *
 * @author hahn
 */
class messenger {

    /**
     * config array for messengers
     * @var type 
     */
    protected $_aCfg = array();
    
    /**
     * content of messagetext to send
     * @var string
     */
    protected $_sMessage = '';

    /**
     * 
     * @example
     * $oMessenger = new messenger(array(
     *   'slack'=>array(
     *     'incomingurl'=>[WebHook url],
     *     'user'=>[visible username in slack],
     *     'icon'=>[Slack Icon], // hm, does not seem to work
     *   ),
     *   'email'=>array(
     *     'from'=>[senders e-mail]
     *     'to'=>[email-address(es)] // multiple emails must be delimited with ";"
     *   )
     * ));
     * @param array $aCfg  config array for notification targets
     * @return boolean
     */
    public function __construct($aCfg) {
        $this->_aCfg = $aCfg;
        return true;
    }

    /**
     * send an email if _aCfg['email'] exists
     */
    private function _sendEmail(){
        if (array_key_exists('email', $this->_aCfg) && array_key_exists('to', $this->_aCfg['email'])
        ) {
            preg_match('/^(.*)\n/', $this->_sMessage, $aTmp);
            $sSubject = $aTmp[0];
            return mail($this->_aCfg['email']['to'], $sSubject, $this->_sMessage, "From: " . $this->_aCfg['email']['from'] . "\r\n" .
                "Reply-To: " . $this->_aCfg['email']['from'] . "\r\n"
            );
        }
        return false;
    }
    
    /**
     * send a message to slack if _aCfg['slack'] exists
     */
    private function _sendToSlack(){
        if (array_key_exists('slack', $this->_aCfg)) {
            require_once('./../vendor/shooker/shooker.php');
            $shkr = new Shooker();
            $shkr->setupIncoming($this->_aCfg['slack']['incomingurl']);
            $sUser=(array_key_exists('user', $this->_aCfg['slack'])? $this->_aCfg['slack']['user']: false);
            $sIcon=(array_key_exists('icon', $this->_aCfg['slack'])? $this->_aCfg['slack']['icon']: false);
            return $shkr->sendMessage($this->_sMessage, $sUser, $sIcon);
        }
        return false;
    }


    /**
     * send a message to all targets
     * @param string $sMessage
     */
    public function sendMessage($sMessage) {
        $this->_sMessage=$sMessage;
        // echo '<pre>'.print_r($this->_aCfg, 1).'</pre>'.$sMessage.'<br>';
        $this->_sendEmail();
        $this->_sendToSlack();
        
    }

}
