<?php 
$db = $GLOBALS['db'];

//Q3
$res = $db->query("
SELECT i.parent_id, i.parent_name, i.document_no FROM ecminvoiceoutolds AS i
INNER JOIN accounts AS a 
ON a.id = i.parent_id
WHERE
YEAR(i.register_date) = '2014' AND
MONTH(i.register_date) IN ('7','8','9') AND
i.canceled='0' AND i.deleted='0' AND i.type='normal' AND
a.parent_id = '1249';
");


$inv = array();
while ($r = $db->fetchByAssoc($res)) {
	$inv[$r['parent_id']]['inv'][] = $r['document_no'];
}

foreach ($inv as $parent=>$val) {
	$i = new EcmInvoiceOutOld();
	
	$a = new Account();
	$a->retrieve($parent);
	
	$i->parent_id = $a->id;
	$i->parent_name = $a->name;
	$i->parent_address_street = $a->billing_address_street;
	$i->parent_address_city = $a->billing_address_city;
	$i->parent_address_postalcode = $a->billing_address_postalcode;
	$i->parent_address_country = $a->billing_address_country;
	$i->to_nip = $a->to_vatid;
	$i->ecmpaymentcondition_id = $a->ecmpaymentcondition_id;
	$i->supplier_code = $a->supplier_code;
	$pc = new EcmPaymentCondition();
	$pc->retrieve($a->ecmpaymentcondition_id);
	$i->ecmpaymentcondition_name = $pc->name;
	$i->payment_date=$GLOBALS['timedate']->to_display_date(date("Y-m-d",mktime()+3600*24*30));
	
	
	$i->register_date=$GLOBALS['timedate']->to_display_date(date("Y-m-d"));
	$i->sell_date=$GLOBALS['timedate']->to_display_date(date("Y-m-d"));
	$i->status="accepted";
	$i->type = "correct";
	$i->assigned_user_id='1';
	$i->created_by='1';
	$i->modified_user_id='1';
	$i->pdf_type='K';
	$i->currency_id='PLN';
	
	$i->template_id = "97700b0d-fbe9-e366-4016-4b260f058a47";
	$i->template_name = "e5 Polska Sp. z o. o.";
	
	$i->ads_text = "Faktura wystawiona w programie excel";
	$i->position_list = array();
	
	$id = $i->save();
	
	unset($i);
	
	$fvkor = new EcmInvoiceOutOld();
	$fvkor->retrieve($id);
	
	echo '<h2>'.$a->name.'</h2><br>';
	echo $a->billing_address_street.'<br>';
	echo $a->billing_address_city.'<br>';
	echo $a->billing_address_postalcode.'<br>';
	echo $a->billing_address_country.'<br>';
	echo $a->to_vatid.'<br><br>';
	
	echo $fvkor->document_no.'<br>';
	echo $fvkor->register_date.'<br>';
	echo $fvkor->payment_date.'<br><br>';
	
	echo 'Do faktur:<br>';
	
	foreach ($val['inv'] as $v) {
		echo $v.'<br>';
	}
	
	echo '-------------------------------------------<br><br><br>';
	unset($a);
	unset($fvkor);
}

echo '<br><br>Koniec!';


?>