<?php
echo "<meta HTTP-EQUIV='refresh' CONTENT='5;URL=cron_xml.php'>";
ini_set('max_execution_time', 0);


require_once 'vendor/autoload.php';

$db = new Source\Conn\DataLayer();

$result = $db->db()->from('xml')
	->where('xml_verifica')->isNull()
	->andWhere('xml_status')->is(0)
	->andWhere('xml_download')->is(0)
	->andWhere('xml_id_lote')->is(13)
	->limit(100)
	->select()
	->all();
	
if($result){
	foreach($result as $r){
		$resultExists = $db->db()->from('xml')
			->where('xml_status')->is(1)
			->andWhere('xml_download')->is(1)
			->andWhere('xml_chave')->is($r->xml_chave)
			->limit(1)
			->select()
			->all();
		if($resultExists){
			foreach($resultExists as $rExists){
				$folder = 'shared/xml/lote'.$r->xml_id_lote.'/';
				if(!is_dir($folder)){
					mkdir($folder, 0777, true);
				}
				
				$fileExists = 'shared/xml/lote'.$rExists->xml_id_lote.'/'.$rExists->xml_arquivo;
				$fileNew = 'shared/xml/lote'.$r->xml_id_lote.'/'.$rExists->xml_arquivo;
				
				if(copy($fileExists, $fileNew)){
					$up['xml_verifica'] = '1';
					$up['xml_download'] = '1';	
					$up['xml_status'] = '1';
					$up['xml_arquivo'] = $rExists->xml_arquivo;
					$up['xml_manifesta'] = '1';
					$db->db()->update('xml')->where('xml_id')->is($r->xml_id)->set($up);
				}else{
					$up['xml_verifica'] = '1';
					$db->db()->update('xml')->where('xml_id')->is($r->xml_id)->set($up);
				}	
			}
		}else{
			$up['xml_verifica'] = '1';		
			$db->db()->update('xml')->where('xml_id')->is($r->xml_id)->set($up);
		}	
	}
}	
