<?php
class MailingCron {
	private $db;
	public $groups;
	public $contacts;
	public $accounts;
	public $template;
	public $primary;
	public $replaceStrings;
	public function replaceStringsDefine() {
		$this->replaceStrings = array ();
		$this->replaceStrings ['Account'] ['$account_name'] = 'name';
		$this->replaceStrings ['Account'] ['$account_description'] = 'description';
		$this->replaceStrings ['Account'] ['$account_billing_address_street'] = 'billing_address_street';
		$this->replaceStrings ['Account'] ['$account_billing_address_city'] = 'billing_address_city';
		$this->replaceStrings ['Account'] ['$account_billing_address_state'] = 'billing_address_state';
		$this->replaceStrings ['Account'] ['$account_billing_address_postalcode'] = 'billing_address_postalcode';
		$this->replaceStrings ['Account'] ['$account_billing_address_country'] = 'billing_address_country';
		
		$this->replaceStrings ['Account'] ['$account_shipping_address_street'] = 'shipping_address_street';
		$this->replaceStrings ['Account'] ['$account_shipping_address_city'] = 'shipping_address_city';
		$this->replaceStrings ['Account'] ['$account_shipping_address_state'] = 'shipping_address_state';
		$this->replaceStrings ['Account'] ['$account_shipping_address_postalcode'] = 'shipping_address_postalcode';
		$this->replaceStrings ['Account'] ['$account_shipping_address_country'] = 'shipping_address_country';
		
		$this->replaceStrings ['Account'] ['$account_krs'] = 'krs';
		$this->replaceStrings ['Account'] ['$account_regon'] = 'regon';
		$this->replaceStrings ['Account'] ['$account_to_vatid'] = 'to_vatid';
		
		$this->replaceStrings ['Contact'] ['$contact_salutation'] = 'salutation';
		$this->replaceStrings ['Contact'] ['$contact_first_name'] = 'first_name';
		$this->replaceStrings ['Contact'] ['$contact_last_name'] = 'last_name';
		$this->replaceStrings ['Contact'] ['$contact_full_name'] = 'full_name';
		
		$this->replaceStrings ['Contact'] ['$contact_primary_address_street'] = 'primary_address_street';
		$this->replaceStrings ['Contact'] ['$contact_primary_address_city'] = 'primary_address_city';
		$this->replaceStrings ['Contact'] ['$contact_primary_address_state'] = 'primary_address_state';
		$this->replaceStrings ['Contact'] ['$contact_primary_address_postalcode'] = 'primary_address_postalcode';
		$this->replaceStrings ['Contact'] ['$contact_primary_address_country'] = 'primary_address_country';
		
		$this->replaceStrings ['Contact'] ['$contact_second_address_street'] = 'alt_address_street';
		$this->replaceStrings ['Contact'] ['$contact_second_address_city'] = 'alt_address_city';
		$this->replaceStrings ['Contact'] ['$contact_second_address_state'] = 'alt_address_state';
		$this->replaceStrings ['Contact'] ['$contact_second_address_postalcode'] = 'alt_address_postalcode';
		$this->replaceStrings ['Contact'] ['$contact_second_address_country'] = 'alt_address_country';
	}
	public function replaceText($type, $account) {
		
		// Account or Leads
		if ($type == 'Account') {
			$this->template->body_html = str_replace ( '$account_name', $account->{$this->replaceStrings [$type] ['$account_name']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_description', $account->{$this->replaceStrings [$type] ['$account_description']}, $this->template->body_html );
			
			$this->template->body_html = str_replace ( '$account_billing_address_street', $account->{$this->replaceStrings [$type] ['$account_billing_address_street']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_billing_address_city', $account->{$this->replaceStrings [$type] ['$account_billing_address_city']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_billing_address_state', $account->{$this->replaceStrings [$type] ['$account_billing_address_state']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_billing_address_postalcode', $account->{$this->replaceStrings [$type] ['$account_billing_address_postalcode']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_billing_address_country', $account->{$this->replaceStrings [$type] ['$account_billing_address_country']}, $this->template->body_html );
			
			$this->template->body_html = str_replace ( '$account_shipping_address_street', $account->{$this->replaceStrings [$type] ['$account_shipping_address_street']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_shipping_address_city', $account->{$this->replaceStrings [$type] ['$account_shipping_address_city']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_shipping_address_state', $account->{$this->replaceStrings [$type] ['$account_shipping_address_state']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_shipping_address_postalcode', $account->{$this->replaceStrings [$type] ['$account_shipping_address_postalcode']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_shipping_address_country', $account->{$this->replaceStrings [$type] ['$account_shipping_address_country']}, $this->template->body_html );
			
			$this->template->body_html = str_replace ( '$account_krs', $account->{$this->replaceStrings [$type] ['$account_krs']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_regon', $account->{$this->replaceStrings [$type] ['$account_regon']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$account_to_vatid', $account->{$this->replaceStrings [$type] ['$account_to_vatid']}, $this->template->body_html );
		}
		// Contact and Contact Leads
		$salution = array (
				'' => '',
				'Mr.' => 'Sz. Pan',
				'Ms.' => 'Sz. Pani',
				'Mrs.' => 'Sz. Pani',
				'Dr.' => 'Dr.',
				'Prof.' => 'Prof.' 
		);
		if ($type == 'Contact') {
			$this->template->body_html = str_replace ( '$contact_salutation', $salution [$account->{$this->replaceStrings [$type] ['$contact_salutation']}], $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_first_name', $account->{$this->replaceStrings [$type] ['$contact_first_name']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_last_name', $account->{$this->replaceStrings [$type] ['$contact_last_name']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_full_name', $account->{$this->replaceStrings [$type] ['$contact_first_name']} . ' ' . $account->{$this->replaceStrings [$type] ['$contact_last_name']}, $this->template->body_html );
			
			$this->template->body_html = str_replace ( '$contact_primary_address_street', $account->{$this->replaceStrings [$type] ['$contact_primary_address_street']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_primary_address_city', $account->{$this->replaceStrings [$type] ['$contact_primary_address_city']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_primary_address_state', $account->{$this->replaceStrings [$type] ['$contact_primary_address_state']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_primary_address_postalcode', $account->{$this->replaceStrings [$type] ['$contact_primary_address_postalcode']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_primary_address_country', $account->{$this->replaceStrings [$type] ['$contact_primary_address_country']}, $this->template->body_html );
			
			$this->template->body_html = str_replace ( '$contact_second_address_street', $account->{$this->replaceStrings [$type] ['$contact_second_address_street']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_second_address_city', $account->{$this->replaceStrings [$type] ['$contact_second_address_city']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_second_address_state', $account->{$this->replaceStrings [$type] ['$contact_second_address_state']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_second_address_postalcode', $account->{$this->replaceStrings [$type] ['$contact_second_address_postalcode']}, $this->template->body_html );
			$this->template->body_html = str_replace ( '$contact_second_address_country', $account->{$this->replaceStrings [$type] ['$contact_second_address_country']}, $this->template->body_html );
		}
		
		//return $this->template->body_html;
	}
	public function __construct() {
		$this->db = $GLOBALS ['superGlobalDb'];
		$this->replaceStringsDefine ();
	}
	
	public function reparseContacts(){
		$con=array();
		foreach ( $this->contacts as $group ) {
			$con[]=$group['cat_id'];
		}
		
		$this->contacts=$con;
	}
	public function getMalingToSend() {
		$z = $this->db->query ( "select * from ecmmailingmessages where deleted=0 and send!=1 and parent_id is not null and date_end<='" . date ( "Y-m-d H:i:s", time() - 7200). "'" );
	
		while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
			
			$eMM = new EcmMailingMessage ();
			
			$eMM->retrieve ( $dane ['id'] );
			
			$this->template = new EmailTemplate ();
			$this->template->retrieve ( $dane ['parent_id'] );
			$this->primary=$this->template->body_html;
			$this->accounts = array ();
			
			$this->groups = $eMM->getPositionList55 ( true );
			$this->contacts = $eMM->getPositionList56 ( true );
			$this->reparseContacts();
			echo "wysylam!";
			$this->getAddressesToSend ();
			$this->searchContactsForAccount ();
		//	$this->searchContactsForLeads ();
			//$this->sendMailingForContact();
		
			$this->db->query("update ecmmailingmessages set send=1 where id='".$dane['id']."'");
		}
	}
	public function getAddressesToSend() {
		foreach ( $this->groups as $group ) {
	
			$z = $this->db->query ( "SELECT * FROM ecmaccountcategories_bean WHERE ecmaccountcategory_id='" . $group ['cat_id'] . "' and deleted='0'" );
			while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
				$this->accounts [$dane ['bean_name']] [] = $dane ['bean_id'];
			}
		}

	}
	public function searchContactsForLeads() {
		foreach ( $this->accounts ['Leads'] as $id ) {
	
			$this->template->body_html=$this->primary;
			$account = new Lead ();
			$account->retrieve ( $id );
			$this->replaceText ( 'Account', $account );
				
			$z = $this->db->query("SELECT * FROM leads_contactleads where lead_id='".$account->id."' and deleted=0");
			while($dane=$this->db->fetchByAssoc($z)){
				$this->sendMailingForContactLead($dane['contactlead_id']);
			}
		}
	}
	
	public function sendMailingForContactLead($id) {
	
		$cats=array();
		$z=$this->db->query("SELECT ecmmailingcategoriy_id FROM ecmmailingcategories_relation where parent_id='".$id."' and available=1");
		while($dane=$this->db->fetchByAssoc($z)){
			$cats=$dane['ecmmailingcategoriy_id'];
		}
		
		if(in_array($cats,$this->contacts)){
		$account = new ContactLead ();
		$account->retrieve ( $id );
		if ($account->id != "") {
			$sea = new SugarEmailAddress ();
			// Grab the array of addresses
	
			$addresses = $sea->getAddressesByGUID ( $id, "ContactLeads" );
			foreach ( $addresses as $address ) {
				if ($address ['email_address'] != "") {
					$this->replaceText ( 'Contact', $account );
			
					$this->sendEmail ( 'Contact', $account, $address ['email_address'] );
				}
			}
		}
		}
	}
	
	public function searchContactsForAccount() {
		foreach ( $this->accounts ['Accounts'] as $id ) {
		
			$this->template->body_html=$this->primary;
			$account = new Account ();
			$account->retrieve ( $id );
			$this->replaceText ( 'Account', $account );

			$z = $this->db->query("SELECT * FROM contacts where account_id='".$account->id."' and deleted=0");
			while($dane=$this->db->fetchByAssoc($z)){
				
				$this->sendMailingForContact($dane['id']);
			}
		}
	}
	
	public function sendMailingForContact($id) {
		$cats=array();
			$z=$this->db->query("SELECT ecmmailingcategoriy_id FROM ecmmailingcategories_relation where parent_id='".$id."' and available=1");

			while($dane=$this->db->fetchByAssoc($z)){
				$cats=$dane['ecmmailingcategoriy_id'];
			}

			if(in_array($cats,$this->contacts)){
				$account = new Contact ();
				$account->retrieve ( $id );
				if ($account->id != "") {
					$sea = new SugarEmailAddress ();
					// Grab the array of addresses
				
					$addresses = $sea->getAddressesByGUID ( $id, "Contacts" );
					foreach ( $addresses as $address ) {
						if ($address ['email_address'] != "") {
							$this->replaceText ( 'Contact', $account );
				
							$this->sendEmail ( 'Contact', $account, $address ['email_address'] );
						}
					}
				}
			}
			
		
	}
	
	public function getAttachments(&$mail) {
		$z = $this->db->query ( "select * from notes where parent_id='" . $this->template->id . "' and deleted=0" );
		while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
			
			$mail->addAttachment ( 'upload/' . $dane ['id'], $dane ['filename'] );
		}
	}
	public function sendEmail($type, $object, $addresses) {
		require_once ("include/phpmailer/class.phpmailer.php");
		require_once ("include/phpmailer/class.smtp.php");

		$mail = new PHPMailer ();
		
		// $mail->SMTPDebug = 3; // Enable verbose debug output
		
		require_once('modules/EcmSysInfos/EcmSysInfo.php');
		$EcmSysInfo = new EcmSysInfo();
		$email=$EcmSysInfo->getEmailSettings();
		$cc=explode(':',$email['value1']);
		if($email['value1']!='' && $email['value2']!='' && $email['value3']!=''){
			global $sugar_config,$current_user;
			$mail->isSMTP (); // Set mailer to use SMTP
			$mail->Host = $cc[0]; // Specify main and backup server
			$mail->SMTPAuth = true; // Enable SMTP authentication
			$mail->Username = $email['value2'];
			$mail->Password = $email['value3'];
			$mail->SMTPSecure = $email['value5']; // Enable encryption, 'ssl' also accepted
			
			
			$EcmSysInfo = new EcmSysInfo();
			
			$mail->Port = $cc[1]; // Set the SMTP port number - 587 for
			if($email['value4']!=''){
				$mail->Sender=$email['value4'];
				$mail->From =$email['value4'];
				if(!empty($email['value6'])){
					$mail->AddReplyTo($email['value6'],$EcmSysInfo->getName());
				}
			} else {
				$mail->Sender=$email['value2'];
				$mail->From =$email['value2'];
				if(!empty($email['value6'])){
					$mail->AddReplyTo($email['value6'], $EcmSysInfo->getName());
				}
			}
			
			$mail->FromName =$EcmSysInfo->getName();
			$mail->WordWrap = 50; // Set word wrap to 50 characters
			
		} else {
			global $sugar_config,$current_user;
			$mail->isSMTP (); // Set mailer to use SMTP
			$mail->Host = $sugar_config['sendMail_host']; // Specify main and backup server
			$mail->SMTPAuth = true; // Enable SMTP authentication
			$mail->Username = $sugar_config['sendMail_username'];
			$mail->Password = $sugar_config['sendMail_password'];
			$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
			$mail->Port = 587; // Set the SMTP port number - 587 for
			$mail->Sender=$sugar_config['sendMail_from'];
			$mail->From =$sugar_config['sendMail_from'];
			$mail->FromName =$EcmSysInfo->getName();
			$mail->WordWrap = 50; // Set word wrap to 50 characters
		}
		
		$mail->addAddress ( $addresses );
		//$mail->addBCC('Marketing@e5.pl');
		$mail->isHTML ( true );
		
		$this->getAttachments ( $mail );
		
		$mail->Subject = $this->template->subject;
	
		$mail->Body = html_entity_decode ( $this->template->body_html );
		
		if (! $mail->send ()) {
			echo 'Message could not be sent.';
			echo 'Mailer Error: ' . $mail->ErrorInfo;
		} else {
			echo 'Message has been sent';
		}
	}
}

?>