<?php
/**
* @author:  Bunzia Alexander <nifus@mail.ru> <http://www.weblancer.net/users/nifus/>
* @copyright: Copyright (c) 2010, Bunzia Alexander
* @version: 1.0
* @license: http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @package: HiLo
*/

include_once(MAIN_SOURCE_PATH.'/ext/php_mailer/class.phpmailer.php');
class mail extends PHPMailer{

  private $tmpl;
  public $lang = 'ru';
  
    //  получаем шаблон
  static function load($v,$lang='ru'){
  global $MAIN_DB,$MAIN_PAGE;
    $sql_lang = " AND lang='".$lang."'" ;
   
    $sql = "SELECT * FROM ".$MAIN_DB -> prefix("system_mail_tmpl")." WHERE m_key='$v'".$sql_lang;
    $row = $MAIN_DB -> fetch_array( $MAIN_DB -> query($sql) );
    if ( !is_array($row) ){
      return false;
    }
   // var_dump($row);
    $m =  new mail();
    $m -> lang = $lang;
    $m -> path = $row['m_path'];
    if ( $row['m_content_type'] == 'html' ){
      $m -> IsHTML(true);
    }
    
    if ( $MAIN_PAGE -> config('sys_smtp_server') ){
      $m -> IsSMTP();
      $m -> SMTPAuth   = true;                  
	    $m -> Port       = $MAIN_PAGE -> config('sys_smtp_port');                      
	    $m -> Host       = $MAIN_PAGE -> config('sys_smtp_server') ; 
	    $m -> Username   = $MAIN_PAGE -> config('sys_smtp_login');     
	    $m -> Password   = $MAIN_PAGE -> config('sys_smtp_pass');  
	           //$m-> SMTPDebug = true;   
    }else{
      $m -> IsMail();
    }
    //$m -> SetLanguage(MAIN_LANG);
     $m -> Subject =  $row['m_subject'];
    $m-> SetFrom($row['m_from_email'], $row['m_from_name']);
	  $m -> CharSet = 'utf-8';//MAIN_ENCODING;
	  //$m -> tmpl = new PHPTAL();
	  $m -> m_body = $row['m_body'];
	  return $m;
  }
  
  public function set($k,$v){
    $this -> search[] = '{'.$k.'}';
    $this -> replace[]=$v;
  }
  
  
  public function send_mail($email){
    if ( false===sys_is_mail($email) )
    {
      return FALSE;
    }
    $s = str_replace($this -> search,$this -> replace,$this ->  m_body );
   
    $this -> MsgHTML( $s );
    
    $this -> AddAddress($email);
    //$this -> IsMail();
    $result =  $this->Send();
    $this -> ClearAddresses();
    return $result;
  }
  
  public function delivery(){
    try
    {
      include_once(MAIN_SOURCE_PATH.'/modules/delivery/inc/class.delivery.php');
      $d =  delivery::query('q');
      //$d -> set_debug(1);
      $d -> where_confirm(1); 
      $d -> where_lang($this -> lang); 
      $d -> get('`key`,email');
      while( $row = $d -> row() )
      {
        $this -> set('unsubscription_url', sys_ml_url(URL_UNDELIVERY_ACT_LINK,array($row['key']),$this -> lang ) );
        $this -> send_mail($row['email']);
      }
      return TRUE;
    }
    catch( Exception $e )
    {
      return FALSE;
    }
  }

}
?>
