<?php

require('../core/classes/register.class.php');
require('../application/config/db.cfg.php');
require('../core/classes/db.class.php');
require('../core/classes/collection.class.php');
require('../xreaders/readers/ycsvparser.class.php');

Register::add('db',new Db());
$db = Register::get('db');
$basic = new BasicFunctions();

$filesCSV = array();
foreach (glob("1C/price/*.csv") as $filename) {
    $filesCSV []= $filename;
}

if (isset($filesCSV) && count($filesCSV)>0)
{
	foreach ($filesCSV as $CSV)
	{
		$CSV_content = file_get_contents($CSV);
		$CSV_content = str_replace('"','',$CSV_content);
		file_put_contents($CSV,$CSV_content);
		
		$importerCODE = str_replace(".csv","",basename($CSV));
		$importer = findImporter($importerCODE);
		
		if ($importer)
		{
			clearDBImporterPrices($importer['id']);
			
			$ycsv = new ycsvParser($CSV,false);
			if (!$ycsv)
				die("Cannot start a parser");
				
			// ПИН;Бренд;Название;Наличие;Цена;Срок поставки
			
			$imp_id = (int)$importer['id'];
			$for = 0; 
			$compare = array();
			while ($record = $ycsv->getRecord()) 
			{
				$for++;
				
				$res = $ycsv->parseRecord($record);
				
				$ARTICLE 	= stringfilter(trim($res[0]));
				$BRAND 		= trim($res[1]);
				$DESCR 		= trim(iconv("windows-1251", "utf-8", $res[2]));
				$BOX 		= trim($res[3]);
				$PRICE 		= trim(str_replace(" ", "", $res[4]));
				$DELIVERY 	= trim($res[5]);
				
				$findBRND = $basic->findBrand($BRAND);
				
				$compare []= "(	
					'".$imp_id."',
					'".addslashes($findBRND['BRA_ID_GET'])."',
					'".addslashes($BRAND)."',
					'".addslashes($ARTICLE)."',
					'".addslashes($DESCR)."',
					'".addslashes($PRICE)."',
					'".addslashes($BOX)."',
					'".addslashes($DELIVERY)."',
					'1'
				)";
				
				if ($for == 500)
				{
					$db->post("INSERT INTO ".DB_PREFIX."details (`IMPORT_ID`,`BRAND_ID`,`BRAND_NAME`,`ARTICLE`,`DESCR`,`PRICE`,`BOX`,`DELIVERY`,`MIN`) VALUES ".join(",", $compare).";");
					$for = 0;
					unset($compare);
				}
			}
			
			// ОСТАТОК
			if (count($compare)>0)
			{
				$db->post("INSERT INTO ".DB_PREFIX."details (`IMPORT_ID`,`BRAND_ID`,`BRAND_NAME`,`ARTICLE`,`DESCR`,`PRICE`,`BOX`,`DELIVERY`,`MIN`) VALUES ".join(",", $compare).";");
				unset($compare);
			}
			
			$ycsv->close();
			
			echo("File imported ".$CSV."\n");
			
			@unlink($CSV);
			
			exit;
		}
		else 
		{
			echo("Not found importer: ".$importer."\n");
		}
	}
}
else 
{
	echo("No files for import\n");
}
exit();

function findImporter($code='')
{
	global $db;
	$sql = "SELECT * FROM ".DB_PREFIX."importers WHERE code LIKE '".mysql_escape_string($code)."';";
	$res = $db->get($sql);
	return $res;
}

function clearDBImporterPrices($id)
{
	global $db;
	$db->post("DELETE FROM ".DB_PREFIX."details WHERE IMPORT_ID='".(int)$id."';");
}

function stringfilter($str) 
{
	return str_replace(array('!','@','#','$','%','^','&','*','(',')','_','+','=','-','~','`','"',"'",' ','№','%',';',':','[',']','{','}','*','?','/','\'','|','.',',','<','>'),'',$str);
}

class BasicFunctions 
{
	var $brands = array();
	
	function findBrand($BRAND)
	{
		if (isset($this->brands[$BRAND]) && $this->brands[$BRAND])
			return $this->brands[$BRAND];
		
		global $db;
		
		$sql = "SELECT * FROM ".DB_PREFIX."brands WHERE BRA_BRAND LIKE '".addslashes($BRAND)."';";
		$res = $db->get($sql);
		
		$this->brand[$BRAND]=$res;
		
		return $res;
	}
	
	function stringfilter($str) 
	{
		return str_replace(array('!','@','#','$','%','^','&','*','(',')','_','+','=','-','~','`','"',"'",' ','№','%',';',':','[',']','{','}','*','?','/','\'','|','.',',','<','>'),'',$str);
	}
}

?>