<?php

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

		$tmpDir = '/tmp/floricode';

		// Establish the FTP connection

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

		// Gets the list with the tables to update

		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']);
				$updated->setTime(0, 0, 0, 0);
			} else
				$updated = NULL;

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

			// Downloads and decompress the file with the data
			
			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");

			// If data is updated, omits the table

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

			if (isset($updated) && $lastUpdated <= $updated) {
				echo "Table $table is updated, omitted\n";
				continue;
			}

			// Updates the table
			
			echo "Dumping data to table $table\n";

			$db->query("START TRANSACTION");
			$db->query("DELETE FROM {$db->quote($table)}");
			$db->queryFromFile(__DIR__."/sql/$table", ['file' => $fileName]);
			$db->query("UPDATE file_config SET updated = # WHERE file_name = #",
				[$lastUpdated, $baseName]
			);
			$db->query("COMMIT");
		} catch (Exception $e) {
			$db->query('ROLLBACK');
			error_log($e->getMessage());
		}
		
		shell_exec("rm -R $tmpDir");
		ftp_close($ftpConn);

		echo "Update completed\n";
	}
}