<?php

if ($_REQUEST['fromEdit']==1) generateEAN();

function generateEAN($validate = 0) {
$country_code = '590';
$company_code = '0488';

$res = $GLOBALS['db']->query("SELECT ean, ean2 FROM ecmproducts;");
$used_ean = array();
while ($r = $GLOBALS['db']->fetchByAssoc($res)) {
	if ((strlen($r['ean'])==13) && (intval($r['ean'])!=0)) $used_ean[] = substr($r['ean'],7,5);
	if ((strlen($r['ean2'])==13) && (intval($r['ean'])!=0)) $used_ean[] = SUBSTR($r['ean2'],7,5);
}

//if validate !=0 don't add current values to $used_ean
if ($validate==0) {
	if (strlen($_REQUEST['ean'])==13) $used_ean[] = substr($_REQUEST['ean'],7,5);
	if (strlen($_REQUEST['ean2'])==13) $used_ean[] = substr($_REQUEST['ean2'],7,5);
}

if ($validate==2)
	if (strlen($_REQUEST['ean'])==13) $used_ean[] = substr($_REQUEST['ean'],7,5);
//find max of last eans
$max=0;
foreach ($used_ean as $ue) 
	if ($ue>$max) $max=$ue;

	//echo $max;
	
$new=$max+1;
//new_ean
$ne = array();
//country code
$ne[0]=5;
$ne[1]=9;
$ne[2]=0;
//company code
$ne[3]=0;
$ne[4]=4;
$ne[5]=8;
$ne[6]=8;
//new product code
$ne[7]=intval(substr($new,0,1));
$ne[8]=intval(substr($new,1,1));
$ne[9]=intval(substr($new,2,1));
$ne[10]=intval(substr($new,3,1));
$ne[11]=intval(substr($new,4,1));

//calculate check sum value
$h1 = $ne[11]+$ne[9]+$ne[7]+$ne[5]+$ne[3]+$ne[1];
$h2 = $h1*3;
$h3 = $ne[10]+$ne[8]+$ne[6]+$ne[4]+$ne[2]+$ne[0];
$h4 = $h2+$h3;
$h5=$h4;
//ZAOKR.GÓRA :)
if ($h5 % 10 != 0)
	while ($h5 % 10 != 0) {
		$h5++;
		}
$ne[12]=$h5-$h4;

$ean ='';
foreach ($ne as $v)	
	$ean.=$v;
echo $ean;
return $ean;
}
?>