<?php
require_once('api/Simpla.php');

class MailingMethodsAdmin extends Simpla
{
  public function fetch()
  {
   	// Одиночное удаление
	if($this->request->method('get') && $this->request->get('remove'))
	{
		if(is_numeric($this->request->get('remove')) && $this->request->get('remove')>0)
		{
			$query = $this->db->placehold('delete from __mailing where id=?', $this->request->get('remove'));
			$this->db->query($query);
		}
	}
	// Множественное удаление
  	if($this->request->method('post') && $this->request->post('remove'))
  	{
		print_r($this->request->post('remove'));
 	}

	// Список адресатов
  	$query = $this->db->placehold('select * from __mailing');
	$this->db->query($query);
	$mails = array();
	foreach($this->db->results() as $tmp){$mails[$tmp->id] = $tmp->email;}

	// Обработчик рассылки
	if($this->request->method('post') && $this->request->post('letter'))
	{
		$mail_header = (trim($this->request->post('header'))==''?$this->config->site_name:$this->request->post('header'));
		$mail_headers  = 'MIME-Version: 1.0' . "\r\n";
		$mail_headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		$mail_headers .= 'From: '.iconv("utf-8","windows-1251",$this->settings->site_name).' <'.$this->settings->notify_from_email.'>' . "\r\n";

		ignore_user_abort(true);
		foreach($mails as $mail)
		{
			$hash = md5($this->settings->license.$mail);
			$unsubscribe = '<p style="text-align:center; margin-top:100px; background-color:#343434; color:#cccccc;">Чтобы отписаться от рассылки, перейдите по <a style="color:#ffffff;" href="'.$this->config->root_url.'/user/?page=mailing_settings&unsubscribe='.$hash.'&mail='.$mail.'" target="_blank">ссылке</a>.</p>';
			mail($mail, $mail_header, $this->request->post('letter').$unsubscribe, $mail_headers);
			usleep(rand(1000000,2000000));
		}
		exit();
	}

 	$this->design->assign('mailing_email', $mails);
	return $this->design->fetch('mailing_methods.tpl');
  }
}
?>