<?php

class Update extends Vn\Lib\Method
{
	function run ($db)
	{
		$db->selectDb ('edi');
		//$db->options (MYSQLI_OPT_LOCAL_INFILE, TRUE);

		$tmpDir = '/tmp/floricode';

		// Establece una conexi�n FTP

		$ftpConf = $db->getRow ('SELECT host, user, password FROM ftp_config');

		echo "Openning FTP connection to {$ftpConf['host']}\n";
		$ftpConn = ftp_connect ($ftpConf['host']);

		if (!$ftpConn)
			throw new Exception ('Can not connect to '. $ftpConf['host']);

		if (!ftp_login ($ftpConn, $ftpConf['user'], $ftpConf['password']))
			throw new Exception ('Can not login to '. $ftpConf['user'] .'@'. $ftpConf['host']);

		// Obtiene el listado de tablas a actualizar

		set_time_limit (0);

		$res = $db->query (
			'SELECT file_name, to_table, file, updated FROM file_config');

		$dwFiles = [];

		if (!file_exists ($tmpDir))
			mkdir ($tmpDir);

		while ($row = $res->fetch_assoc ())
		try {
			$file = $row['file'];
			$table = $row['to_table'];
			$baseName = $row['file_name'];
			
			if ($row['updated'])
				$updated = DateTime::createFromFormat ('Y-m-d', $row['updated']);
			else
				$updated = NULL;

			$remoteFile = "codes/$file.ZIP";
			$zipFile = "$tmpDir/$file.zip";
			$ucDir = "$tmpDir/$file";

			// Intenta descargar y descomprimir el fichero con los datos
			
			if (!isset ($dwFiles[$file]))
			{
				$dwFiles[$file] = TRUE;
			
				echo "Downloading $remoteFile\n";
				if (!ftp_get ($ftpConn, $zipFile, $remoteFile, FTP_BINARY))
					throw new Exception ("Error downloading $remoteFile to $zipFile");

				$zip = new ZipArchive;

				if ($zip->open ($zipFile) !== TRUE)
					throw new Exception ("Can not open $zipFile");

				@mkdir ($ucDir, 0774, TRUE);

				if (!$zip->extractTo ($ucDir))
					throw new Exception ("Can not uncompress file $zipFile");

				$zip->close();
				unlink ($zipFile);
			}

			foreach (glob ("$ucDir/$baseName*.txt") as $fileName)
				break;
				
			if (!$fileName)
				throw new Exception ("Import file for table $table does not exist");

			// Si los datos están actualizados omite la tabla

			$lastUpdated = substr ($fileName, -10, 6);
			$lastUpdated = DateTime::createFromFormat ('dmy', $lastUpdated);

			if ($updated && $lastUpdated <= $updated)
				continue;

			// Actualiza los datos de la tabla

			echo "Dumping data to table $table\n";
			$importQuery = $db->loadFromFile (__DIR__."/sql/$table", ['file' => $fileName]);

			$db->multiQuery (
				"START TRANSACTION;
				DELETE FROM $table;
				$importQuery;
				UPDATE file_config SET updated = # WHERE file_name = #;
				COMMIT;",
				[$lastUpdated, $baseName]
			);
			
			do {
				$db->storeResult ();
			}
			while ($db->moreResults () && $db->nextResult ());
		}
		catch (Exception $e)
		{
			$db->query ('ROLLBACK');
			error_log ($e->getMessage ());
		}
		
		shell_exec ("rm -R $tmpDir");
		ftp_close ($ftpConn);

		echo "Update completed\n";
	}
}


