<?php



require_once 'vendor/autoload.php';

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


$result = $db->db()->from('lote')
	->where('lote_status')->is(0)
	->limit(50)
	->select()
	->all();


if($result){
	foreach($result as $r){
		
		$resultExists = $db->db()->from('xml')
			->where('xml_status')->is(0)
			->andWhere('xml_id_lote')->is($r->xml_id_lote)
			->limit(1)
			->select()
			->all();
			
		if(!$resultExists){
			$folder = 'shared/xml/lote'.$r->lote_id.'/';
			$folderFile = 'shared/zip/lote'.$r->lote_id.'.zip';
			$folderFileRar = 'shared/zip/lote'.$r->lote_id.'.rar';
			
			$zip = new \ZipArchive();
			
			$resultExistsDownload = $db->db()->from('xml')
					->where('xml_status')->is(1)
					->andWhere('xml_download')->is(1)
					->select()
					->all();
					
			if($resultExistsDownload){
				if($zip->open($folderFile, ZIPARCHIVE::CREATE) == TRUE){
					foreach($resultExistsDownload as $rExistsDownload){
						$zip->addFile($folder.$rExistsDownload->xml_arquivo,$rExistsDownload->xml_arquivo);
					}					
					$zip->close();
				}
				
				if(rename($folderFile, $folderFileRar)){
					$up['lote_status'] = '1';
					$up['lote_date_hour_end'] = date('Y-m-d H:i:s');
					$db->db()->update('lote')->where('lote_id')->is($r->lote_id)->set($up);
				}
			}
		}
	}
}	
?>
