<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/private/invoice_postprocessing.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
$was_not_set = ($former_values['IDdoc'] == '');

if (
	($was_not_set && $former_values['Status'] != 'draft' && $values['Status'] != 'draft') ||
	($was_not_set && $former_values['Status'] == 'draft' && (isset($values['Status']) && $values['Status'] == 'sent'))
	)
{
	$year = date("Y");

	$type = $values['Type'];
	if (!isset($type))
	 	$type = $former_values['Type'];

	$countSQL = "
		SELECT count(ID) AS 'total'
		FROM invoices
		WHERE 
			SUBSTRING(IssueDate,1,4) = '".$year."' AND
			Activity != '0' AND
			IDdoc != '' AND
			Type = '".$type."'";

	$row = $db_conn->getRow($countSQL);

	$count = $row['total'] + 1;
	$countPow = $count; 
	$countString = '';

	while($countPow < 1000)
	{
		$countString .= '0';
		$countPow *= 10;
	};

	$count = $countString.$count;	
	$IDdoc = $type.$year.$count;
	
	debug_log('$IDdoc : '.$IDdoc);
	
	$db_conn->Execute('UPDATE `invoices` SET `IDdoc`="'.$IDdoc.'" WHERE ID=\''.$IDs_array[0].'\';');
}

return TRUE;
?>
