<?php
echo 'dupcia';
ini_set('display_errors',1);
error_reporting(E_ALL);
echo 'error!';
class Mailing {
	public $db;
	public $pdfMerge;
	public $contentTpl = 'modules/EcmAgreements/tpl/emailContent.html';
	public $accounts;
	public function __construct() {
		$this->db = $GLOBALS ['db'];
		$this->pdfMerge = new PDFMerger ();
	}
	
	public function getAccounts() {
		$r = $this->db->query ( "select parent_id from ecminvoiceouts where payment_date<='" . date ( "Y-m-t" ) . "' and payment_date>='" . date ( "Y-m-01" ) . "' group by parent_id" );
		$this->accounts = array();
		while ( $dane = $this->db->fetchByAssoc ( $r ) ) {
			$this->accounts [] = $dane;
		}
	}
	
	public function generateEmails() {
		foreach ( $this->accounts as $account ) {
			$acc = new Account ();
			$acc->retrieve ( $account );
			if ($acc->only_invoice == 1) {
				$transactions = $this->getOnlyInvoiceTransactions ( $account );
				$saldo = null;
			} else {
				$transactions = $this->getAccountTransactions ( $account );
				$saldo = $this->getPdfForAccount ( $transactions, $acc );
			}
			
			$invoiceFiles = $this->getInvoiceFiles ( $account );
			
			$endingAgreements = $this->getEndingAgreements ( $account );
			
			$this->sendMessage ( $acc, $transactions, $invoiceFiles, $endingAgreements, $saldo );
		}
	}
	public function getPdfForAccount($transactions, $acc) {
		$total_w_war = 0;
		$total_w_nieroz = 0;
		$total_w_roz = 0;
		
		foreach ( $transactions as $transaction ) {
			$total_w_war = $total_w_war + $transaction ['value'];
			$total_w_nieroz = $total_w_nieroz + ($transaction ['value'] - $transaction ['total_settled']);
			$total_w_roz = $total_w_roz + $transaction ['total_settled'];
		}
		
		$ss = new Sugar_Smarty ();
		global $mod_strings;
		$ss->assign ( "MOD", $mod_strings );
		
		global $app_strings;
		$ss->assign ( "APP", $app_strings );
		
		$ss->assign ( 'SUM', $sum );
		$ss->assign ( 'umowy', getAgreements ( $account_id ) );
		$ss->assign ( 'umowa_sel', $umowa_id );
		$ss->assign ( 'SWITCH_SHOW', $_REQUEST ['switch_show'] );
		$ss->assign ( 'PROCESS', '1' );
		$ss->assign ( 'ACCOUNT', array (
				'ID' => $acc->id,
				'NAME' => $acc->name
		) );
		
		$ss->assign ( 'total_w_war', $total_w_war );
		$ss->assign ( 'total_w_nieroz', $total_w_nieroz );
		$ss->assign ( 'total_w_roz', $total_w_roz );
		
		$ss->assign ( 'WINIEN', $transactions );
		
		ob_clean ();
		$output = $ss->fetch ( 'modules/EcmPaymentStates/tpls/PDF/AccountPaymentStatespdf.tpl' );
		include_once ("include/MPDF57/mpdf.php");
		unset ( $smarty );
		$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 25, 10, 5, 5 );
		// $p->setFooter('Strona {PAGENO} z {nbpg}');
		$p->SetHTMLHeader ( '<table style="width:100%;"><tr><td style="text-align:left;font-size: 10px;width:50%;">BILANS B. Pietras E. Pietras Spółka Jawna<br>
Rozrachunki: ' . $a->name . '<br>Data wydruku: ' . date ( "d.m.Y" ) . '<br>Strona {PAGENO}  z {nbpg}</td>
            <td style="text-align:left;font-size: 10px;width:50%;">' . $a->name . '<br>' . $a->register_address_street . '
<br>' . $a->register_address_postalcode . ',
             ' . $a->register_address_city . '<br>NIP: ' . $a->to_vatid . '</td></tr></table>' );
		// $p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
		// echo $output;
		$p->writeHTML ( $output );
		
		if (count ( $transactions ) > 0) {
			$p->Output ( 'upload/rozrachunki.pdf', 'F' );
			return 'upload/rozrachunki.pdf';
		} else {
			return null;
		}
	}
	public function getOnlyInvoiceTransactions($id) {
		$ecmInvoiceOut = new EcmInvoiceout ();
		$results = $ecmInvoiceOut->get_full_list ( null, "parent_id='" . $id . "' and payment_date>='" . date ( "Y-m-01" ) . "' and payment_date<='" . date ( "Y-m-t" ) . "'" );
		$ids = array();
		$agreement = array();
		foreach ( $results as $result ) {
			$ids [] = $result->id;
			$agreement [] = $result->agreement_id;
		}
		
		$zap = "select payment_date,ecmagreement_id from ecmagreementitems where deleted=0 and ecmagreement_id in ('" . implode ( "','", $agreement ) . "') and payment_date>='" . date ( "Y-m-01" ) . "' and payment_date<='" . date ( "Y-m-t" ) . "'";
		
		$z = $this->db->query ( $zap );
		
		$raty_kap = array();
		while ( $r = $this->db->fetchByAssoc ( $z ) ) {
			$rr = $this->db->query ( "select id from ecmtransactions where record_id='" . $r ['ecmagreement_id'] . "' and deleted=0 and name like 'Rata kapitałowa do umowy:%' and payment_date='" . $r ['payment_date'] . "'" );
			$dane = $this->db->fetchByAssoc ( $rr );
			$raty_kap [] = $dane ['id'];
		}
		
		if (count ( $raty_kap ) > 0) {
			$kap = "id in ('" . implode ( "','", $raty_kap ) . "')";
		} else {
			$kap = "";
		}
		
		$query = "select * from ecmtransactions where record_id in ('" . implode ( "','", $ids ) . "') " . $kap . " and deleted=0 group by id";
		
		$res = $this->db->query ( $query );
		$transactions = array();
		$transactions = array();
		while ( $r = $this->db->fetchByAssoc ( $res ) ) {
			$r ['total_settled'] = 0;
			$r = $this->getSettledTransactionsValue ( $r );
			$transactions [] = $r;
		}
		
		return $transactions;
	}
	public function getInvoiceFiles($id) {
		include_once "modules/EcmInvoiceOuts/createPDF.php";
		$ecmInvoiceOut = new EcmInvoiceout ();
		$results = $ecmInvoiceOut->get_full_list ( null, "parent_id='" . $id . "' and payment_date>='" . date ( "Y-m-01" ) . "' and payment_date<='" . date ( "Y-m-t" ) . "'" );
		
		$files = array();
		foreach ( $results as $result ) {
			$path = 'upload/fk_' . str_replace ( '/', '', (str_replace ( ' ', '', $result->document_no )) ) . '.pdf';
			
			$name = createEcmInvoiceOutPdf ( $result->id, 'FILE' );
			
			$files [] = $name;
		}
		
		return $files;
	}
	function dateV($format, $timestamp = null) {
		$to_convert = array (
				'l' => array (
						'dat' => 'N',
						'str' => array (
								'Poniedziałek',
								'Wtorek',
								'Środa',
								'Czwartek',
								'Piątek',
								'Sobota',
								'Niedziela'
						)
				),
				'F' => array (
						'dat' => 'n',
						'str' => array (
								'styczeń',
								'luty',
								'marzec',
								'kwiecień',
								'maj',
								'czerwiec',
								'lipiec',
								'sierpień',
								'wrzesień',
								'październik',
								'listopad',
								'grudzień'
						)
				),
				'f' => array (
						'dat' => 'n',
						'str' => array (
								'stycznia',
								'lutego',
								'marca',
								'kwietnia',
								'maja',
								'czerwca',
								'lipca',
								'sierpnia',
								'września',
								'października',
								'listopada',
								'grudnia'
						)
				)
		);
		if ($pieces = preg_split ( '#[:/.\-, ]#', $format )) {
			if ($timestamp === null) {
				$timestamp = time ();
			}
			foreach ( $pieces as $datepart ) {
				if (array_key_exists ( $datepart, $to_convert )) {
					$replace [] = $to_convert [$datepart] ['str'] [(date ( $to_convert [$datepart] ['dat'], $timestamp ) - 1)];
				} else {
					$replace [] = date ( $datepart, $timestamp );
				}
			}
			$result = strtr ( $format, array_combine ( $pieces, $replace ) );
			return $result;
		}
	}
	public function getEmailTitle($acc) {
		return $title = "Faktury za m-c " . $this->dateV ( 'F', strtotime ( date ( 'Y-m-t' ) ) ) . ' ' . $acc->parent_name . ' - BILANS B. Pietras E. Pietras Spółka Jawna';
	}
	
	public function calculateTotal($transactions){
		$total=0;
		
		foreach ($transactions as $transaction){
			$total=$total+($transaction ['value'] - $transaction ['total_settled']);
		}
		
		return $total;
	}
	public function getEmailContent($acc,$transactions) {
		$ss = new Sugar_Smarty ();
		
		$ss->assign("transactions",$transactions);
		$ss->assign("mc",$this->dateV ( 'F', strtotime ( date ( 'Y-m-t' ) ) ));
		$ss->assign("year",date('Y'));
		$ss->assign("total",$this->calculateTotal($transactions));
		
		$content = $ss->fetch($this->contentTpl);
		
		return $content;
		
	}
	public function sendMessage($acc, $transactions, $files, $endingAgreements, $saldo) {
		require_once ("mailer/PHPMailerAutoload.php");
		
		$mailClassS = new PHPMailer ();
		
		$mailClassS->isSMTP (); // Set mailer to use SMTP
		$mailClassS->Host = '77.55.64.229'; // Specify main and backup server
		$mailClassS->SMTPAuth = true; // Enable SMTP authentication
		$mailClassS->Username = 'faktury@e-bilans.info'; // SMTP username
		$mailClassS->Password = 'FakturyInfo^'; // SMTP password
		$mailClassS->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
		$mailClassS->Port = 587; // Set the SMTP port number - 587 for
		
		/*
		 * foreach ($to as $ad=>$tit){
		 *
		 * $mailClassS->addAddress ($ad,$tit); // Add a
		 *
		 * }
		 */
		
		$addressCC = "outtervision@gmail.com";
		$mailClassS->addBCC ( $addressCC, 'Dominik Brzóska' );
		
		/*
		 * $mailClassS->addCC('borkowskak@matbud-torun.pl', 'Katarzyna Borkowska');
		 * $mailClassS->addCC('bogdanpietras@matbud-torun.pl', 'Bogdan Pietras');
		 * $mailClassS->addCC('fakturywyslane@e-bilans.info', 'Faktury wysłane');
		 */
		
		$mailClassS->Sender = 'faktury@e-bilans.info';
		$mailClassS->From = 'faktury@e-bilans.info';
		$mailClassS->FromName = 'BILANS B. Pietras E. Pietras Spółka Jawna';
		$mailClassS->WordWrap = 50; // Set word wrap to 50 characters
		
		$mailClassS->isHTML ( true ); // Set email format to HTML
		
		$mailClassS->Subject = $this->getEmailTitle ( $acc );
		
		$mailClassS->Body = $this->getEmailContent($acc,$transactions);
		foreach ( $files as $path ) {
			
			if (file_exists ( '/var/www/html/crm/' . $path )) {
				
				$mailClassS->addAttachment ( '/var/www/html/crm/' . $path );
			}
		}
		
		if ($saldo != null) {
			if (file_exists ( '/var/www/html/crm/' . $saldo )) {
				
				$mailClassS->addAttachment ( '/var/www/html/crm/' . $saldo );
			}
		}
		
		if (! $mailClassS->send ()) {
			
			return false;
		}
	}
	public function getEndingAgreements($id) {
		$ecmAgreement = new EcmAgreement ();
		$results = $ecmAgreement->get_full_list ( null, "date_end>='" . date ( "Y-m-01" ) . "' and date_end<='" . date ( "Y-m-t" ) . "'" );
		
		return $results;
	}
	public function getAccountTransactions($id) {
		$query = "
                SELECT * FROM ecmtransactions
                WHERE deleted='0' AND
                parent_id='" . $id . "'
                AND type='0' AND (settled='0' or settled=null)
                AND register_date > '2011-12-31' and payment_date <= '" . date ( "Y-m-t" ) . "'
                ORDER BY payment_date desc";
		
		$res = $this->db->query ( $query );
		$transactions = array();
		while ( $r = $this->db->fetchByAssoc ( $res ) ) {
			$r ['total_settled'] = 0;
			$r = $this->getSettledTransactionsValue ( $r );
			$transactions [] = $r;
		}
		
		return $transactions;
	}
	public function getSettledTransactionsValue($record) {
		$rel = $this->db->query ( "SELECT * FROM ecmtransactions_rel WHERE ecmtransaction_a_id='" . $r ['id'] . "' OR ecmtransaction_b_id='" . $r ['id'] . "'" );
		while ( $rr = $this->db->fetchByAssoc ( $rel ) ) {
			if ($rr ['ecmtransaction_a_id'] == $r ['id'])
				$rel_id = $rr ['ecmtransaction_b_id'];
				else
					$rel_id = $rr ['ecmtransaction_a_id'];
					$t = $this->db->fetchByAssoc ( $this->db->query ( "SELECT * FROM ecmtransactions WHERE id='$rel_id' and deleted=0" ) );
					$tmp2 = array ();
					$tmp2 ['name'] = $t ['name'];
					$tmp2 ['trans_id'] = $t ['id'];
					$tmp2 ['value'] = $rr ['value'];
					if ($t ['type'] == 0 && $rel->num_rows == 1) {
						
						if (abs ( $rr ['value'] ) == abs ( $r ['value'] )) {
							if ($r ['value'] > 0) {
								$rr ['value'] = abs ( $rr ['value'] );
							} else {
								$v = - 1 * abs ( $rr ['value'] );
								$rr ['value'] = $v;
							}
						} else {
							if ($r ['value'] > 0) {
								$rr ['value'] = abs ( $rr ['value'] );
							} else {
								$v = - 1 * abs ( $rr ['value'] );
								$rr ['value'] = $v;
							}
						}
					} else {
						
						if (abs ( $rr ['value'] ) == abs ( $r ['value'] )) {
							if ($r ['value'] > 0) {
								$rr ['value'] = abs ( $rr ['value'] );
							} else {
								$v = - 1 * abs ( $rr ['value'] );
								$rr ['value'] = $v;
							}
						} else {
							if ($r ['value'] > 0) {
								$rr ['value'] = abs ( $rr ['value'] );
							}
						}
					}
					if ($t ['id'] == "")
						continue;
						$record ['total_settled'] += floatval ( $rr ['value'] );
		}
		
		return $record;
	}
}
echo 'error!';
?>