<?php
$input = "http://www.cebiella.it/pagine/download/sind.zip";
$handle = fopen($input, "rb");
$contents = stream_get_contents($handle);
fclose($handle);

$fp = fopen('sind.zip', 'w');
fwrite($fp, $contents);
fclose($fp);

system("unzip -j -P progetto sind.zip CEAZI00P.txt -d tmp",$ret_val);

include("../../db.php");

if (($handle = fopen("tmp/CEAZI00P.txt", "r")) !== FALSE) {
	while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
		$line++;
		$num = count($data);
			
		//PIVA
		$codfisc = trim($data[7]);
		$piva = trim($data[8]);
		
		if(!empty($piva))
			$piva = str_pad($piva,11,'0',STR_PAD_LEFT);

		if(!empty($codfisc) || !empty($piva)){
			

			//sontrollo se appartiene a CNA o CONFARTIGIANATO
			$cod_ass = trim($data[11]);
			$collegio = trim($data[34]);
			if($cod_ass == "010" || $cod_ass == "011")
				$associata = "CNA";
			elseif($cod_ass == "015")
				$associata = "CON";
			elseif($collegio == "1")
				$associata = "COL";
			else
				$associata = "";
			
			//esterna o iscritta a cassa
			trim($data[9]) == "E" ? $esterna = 1 : $esterna = 2;


			//controllo se c'è già e quindi fare solo un update o inserirla come nuova
			$result = mysql_query("SELECT * FROM imprese WHERE piva = '".$piva."' AND piva <> '' OR codfisc = '".$codfisc."' AND codfisc <> ''");
			if(mysql_num_rows($result) > 0){
				mysql_query("
				UPDATE imprese SET associata = '".$associata."', esterna = ".intval($esterna)."
				WHERE piva = '".$piva."' AND piva <> '' OR codfisc = '".$codfisc."' AND codfisc <> ''
				");
			}else{
				$dtcessaz = trim($data[27]);
				$dtcessaz == '' ? $dtcessaz = '0000-00-00' : $dtcessaz = substr($dtcessaz,6,4).'-'.substr($dtcessaz,3,2).'-'.substr($dtcessaz,0,2);
				
				mysql_query("INSERT INTO imprese (anagrafica,indirizzo,cap,comune,prov,codfisc,piva,telefono,fax,email,sez_reg_imp,dt_cessaz,associata,esterna) VALUES (
				'".trim(addslashes($data[2]))."','".trim(addslashes($data[3]))."','".trim(addslashes($data[4]))."','".trim(addslashes($data[5]))."','".trim(addslashes($data[6]))."',
				'".trim(addslashes($data[7]))."','".trim(addslashes($data[8]))."','".trim(addslashes($data[14]))."','".trim(addslashes($data[16]))."','".trim(addslashes($data[18]))."',
				'','".$dtcessaz."','".$associata."',".intval($esterna)."
				)");
			}
			
		}
	}
	fclose($handle);
}

@unlink("tmp/CEAZI00P.txt");
@unlink("sind.zip");
?>