<?php
class MailingCron {
	private $db;
	public $groups;
	public $contacts;
	public $accounts;
	public $template;
	public $primary;
	public $eMM;
	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) {
		$was=false;
		// Account or Leads
		if ($type == 'Account') {
			$this->template->{$account->id.'body'} = str_replace ( '$account_name', $account->{$this->replaceStrings [$type] ['$account_name']}, $this->template->body_html);
			$this->template->{$account->id.'body'} = str_replace ( '$account_description', $account->{$this->replaceStrings [$type] ['$account_description']},$this->template->{$account->id.'body'} );
			
			$this->template->{$account->id.'body'} = str_replace ( '$account_billing_address_street', $account->{$this->replaceStrings [$type] ['$account_billing_address_street']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_billing_address_city', $account->{$this->replaceStrings [$type] ['$account_billing_address_city']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_billing_address_state', $account->{$this->replaceStrings [$type] ['$account_billing_address_state']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_billing_address_postalcode', $account->{$this->replaceStrings [$type] ['$account_billing_address_postalcode']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_billing_address_country', $account->{$this->replaceStrings [$type] ['$account_billing_address_country']},$this->template->{$account->id.'body'} );
			
			$this->template->{$account->id.'body'} = str_replace ( '$account_shipping_address_street', $account->{$this->replaceStrings [$type] ['$account_shipping_address_street']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_shipping_address_city', $account->{$this->replaceStrings [$type] ['$account_shipping_address_city']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_shipping_address_state', $account->{$this->replaceStrings [$type] ['$account_shipping_address_state']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_shipping_address_postalcode', $account->{$this->replaceStrings [$type] ['$account_shipping_address_postalcode']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_shipping_address_country', $account->{$this->replaceStrings [$type] ['$account_shipping_address_country']},$this->template->{$account->id.'body'} );
			
			$this->template->{$account->id.'body'} = str_replace ( '$account_krs', $account->{$this->replaceStrings [$type] ['$account_krs']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_regon', $account->{$this->replaceStrings [$type] ['$account_regon']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$account_to_vatid', $account->{$this->replaceStrings [$type] ['$account_to_vatid']},$this->template->{$account->id.'body'} );
			$was=true;
		}
		// Contact and Contact Leads
		$salution = array (
				'' => '',
				'Mr.' => 'Sz. Pan',
				'Ms.' => 'Sz. Pani',
				'Mrs.' => 'Sz. Pani',
				'Dr.' => 'Dr.',
				'Prof.' => 'Prof.' 
		);
		if ($type == 'Contact') {
			if($was==true){
				$this->template->body_html=$this->template->{$account->id.'body'};
			}
			
			$this->template->{$account->id.'body'} = str_replace ( '$contact_salutation', $salution [$account->{$this->replaceStrings [$type] ['$contact_salutation']}],$this->template->body_html);
			$this->template->{$account->id.'body'} = str_replace ( '$contact_first_name', $account->{$this->replaceStrings [$type] ['$contact_first_name']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_last_name', $account->{$this->replaceStrings [$type] ['$contact_last_name']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_full_name', $account->{$this->replaceStrings [$type] ['$contact_first_name']} . ' ' . $account->{$this->replaceStrings [$type] ['$contact_last_name']},$this->template->{$account->id.'body'} );
			
			$this->template->{$account->id.'body'} = str_replace ( '$contact_primary_address_street', $account->{$this->replaceStrings [$type] ['$contact_primary_address_street']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_primary_address_city', $account->{$this->replaceStrings [$type] ['$contact_primary_address_city']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_primary_address_state', $account->{$this->replaceStrings [$type] ['$contact_primary_address_state']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_primary_address_postalcode', $account->{$this->replaceStrings [$type] ['$contact_primary_address_postalcode']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_primary_address_country', $account->{$this->replaceStrings [$type] ['$contact_primary_address_country']},$this->template->{$account->id.'body'} );
			
			$this->template->{$account->id.'body'} = str_replace ( '$contact_second_address_street', $account->{$this->replaceStrings [$type] ['$contact_second_address_street']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_second_address_city', $account->{$this->replaceStrings [$type] ['$contact_second_address_city']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_second_address_state', $account->{$this->replaceStrings [$type] ['$contact_second_address_state']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_second_address_postalcode', $account->{$this->replaceStrings [$type] ['$contact_second_address_postalcode']},$this->template->{$account->id.'body'} );
			$this->template->{$account->id.'body'} = str_replace ( '$contact_second_address_country', $account->{$this->replaceStrings [$type] ['$contact_second_address_country']},$this->template->{$account->id.'body'} );
		}
		
		// return $this->template->body_html;
	}
	public function __construct() {
		$this->db = $GLOBALS ['db'];
		$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->eMM=$eMM;
			$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 ();
			
			if (count ( $this->groups ) > 0 && count ( $this->contacts ) > 0) {
				$this->getAddressesToSend ();
				$this->searchContactsForAccount ();
				$this->searchContactsForLeads ();
			} else {
				if (count ( $this->groups ) == 0 && count ( $this->contacts ) > 0) {
				
					$this->sendMailingForContactLeadNoLead ();
					$this->sendMailingForContactNoAccounts ();
				}
			}
			
			// $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 );
			$idd=$account->id;
			$z = $this->db->query ( "SELECT * FROM leads_contactleads where lead_id='" . $idd. "' and deleted=0" );
			while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
				$account->id=$dane ['contactlead_id'];
				$this->replaceText ( 'Account', $account );
				$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 );
			$idd=$account->id;
			$z = $this->db->query ( "SELECT * FROM accounts_contacts where account_id='" . $idd. "' and deleted=0" );
			while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
				$account->id=$dane ['contactlead_id'];
				$this->replaceText ( 'Account', $account );
				$this->sendMailingForContact ( $dane ['contact_id'] );
			}
		}
	}
	public function sendMailingForContactLeadNoLead() {
		$cats = array ();
		$z = $this->db->query ( "SELECT ecmmailingcategoriy_id,parent_id FROM ecmmailingcategories_relation where available=1 and parent_type='Contact' and deleted=0" );
		while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
			if (in_array ( $dane ['ecmmailingcategoriy_id'], $this->contacts )) {
				$account = new ContactLead ();
				$account->retrieve ( $dane ['parent_id']);
				if ($account->id != "") {
					$sea = new SugarEmailAddress ();
					// Grab the array of addresses
					
					$addresses = $sea->getAddressesByGUID ( $dane ['parent_id'], "ContactLeads" );
					foreach ( $addresses as $address ) {
						if ($address ['email_address'] != "") {
							$this->replaceText ( 'Contact', $account );
							
							$this->sendEmail ( 'Contact', $account, $address ['email_address'] );
						}
					}
				}
			}
		}
	}
	public function sendMailingForContactNoAccounts() {
		$cats = array ();
		$z = $this->db->query ( "SELECT ecmmailingcategoriy_id,parent_id FROM ecmmailingcategories_relation where available=1 and parent_type='Contact' and deleted=0" );
		while ( $dane = $this->db->fetchByAssoc ( $z ) ) {
			
			if (in_array ( $dane ['ecmmailingcategoriy_id'], $this->contacts )) {
				
				$account = new Contact ();
				$account->retrieve ( $dane ['parent_id'] );
				if ($account->id != "") {
					
					$sea = new SugarEmailAddress ();
					// Grab the array of addresses
					
					$addresses = $sea->getAddressesByGUID ( $dane ['parent_id'], "Contacts" );
					foreach ( $addresses as $address ) {
						if ($address ['email_address'] != "") {
							$this->replaceText ( 'Contact', $account );
						
							$this->sendEmail ( 'Contact', $account, $address ['email_address'] );
						}
					}
				}
			}
		}
	}
	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/phpMailer2/class.phpmailer.php';
		require_once 'include/phpMailer2/class.smtp.php';
		$mail = new PHPMailer2 ();
		
		// $mail->SMTPDebug = 3; // Enable verbose debug output
		
		$mail->isSMTP (); // Set mailer to use SMTP
		$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
		$mail->SMTPAuth = true; // Enable SMTP authentication
		
		$res=$this->db->query("select id,google_login,CAST(AES_DECRYPT(google_password, 'jakistamhash123') as CHAR)
AS google_password FROM users where id='".$this->eMM->assigned_user_id."'");
		$dane2=$this->db->fetchByAssoc($res);
		
		if($dane2['google_login']!="" && $dane2['google_password']!=""){
			$mail->Username = $dane2['google_login'];
			$mail->Password = $dane2['google_password'];
	
		} else {
		$mail->Username = 'Marketing@e5.pl'; // SMTP username
		$mail->Password = '&r8TZbQy'; // SMTP password
		}
		$mail->CharSet = 'UTF-8';
		$mail ->charSet = "UTF-8"; 
		$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587; // TCP port to connect to
		
		$mail->setFrom ( 'Marketing@e5.pl' );
		
		$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->{$object->id.'body'});
		
		if (! $mail->send ()) {
			echo 'Message could not be sent.';
			echo 'Mailer Error: ' . $mail->ErrorInfo;
		} else {
			echo 'Message has been sent';
		}
	}
}



?>