<?php

define("debug_MYSQL",false);
chdir("/home/******/htdocs/");

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');

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

echo('<pre>');
if (isset($filesCSV) && count($filesCSV)>0){
	foreach ($filesCSV as $CSV){
		
		$filename = basename($CSV);
		$chk = is_int(strpos($filename,"statuses"));
		if ($chk) {
			
			$ycsv = new ycsvParser($CSV,false);
			if (!$ycsv)
				die("Cannot start a parser");
				
			while ($record = $ycsv->getRecord()) {
			$res = $ycsv->parseRecord($record);
			
				$number = $res[0];
				$status = @iconv("windows-1251","utf-8",$res[1]);
				
				$scSID = findscSIDbyNumber($number);
				$statusID = findIDByStatus($status);
				
				if ($scSID && $statusID){
					$db->post("UPDATE ".DB_PREFIX."cart SET status='".(int)$statusID."' WHERE scSID='".(int)$scSID."';");
				}
			}
			$ycsv->close();
			@unlink($CSV);
		}
	}
}
else {
	$msg .= "<h3>No files for import</h3>";
	echo($msg);
}
echo('</pre>');
exit();

function findIDByStatus($name=''){
	global $db;
	if ($name){
		$sql = "SELECT * FROM ".DB_PREFIX."dic_statuses WHERE name LIKE '".DB::escape($name)."';";
		$res = $db->get($sql);
		return $res['id'];
	}
	else 
		return 0;
}
function findscSIDbyNumber($number){
	global $db;
	if ($number){
		$sql = "SELECT * FROM ".DB_PREFIX."cart_bills WHERE number LIKE '".DB::escape($number)."';";
		$res = $db->get($sql);
		return $res['scSID'];
	}
	else 
		return 0;
}
?>