<?php
/**
 * FW Food menu 5.1.1
 * @copyright (C) 2020 Fastw3b
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * @link http://www.fastw3b.net/ Official website
 **/

defined('_JEXEC') or die('Restricted access');

class MenuModelData extends JModelLegacy {
	function getPlugins() {
		$app = JFactory::getApplication();
		JPluginHelper::importPlugin('fwfoodmenu');
		return $app->triggerEvent('onFwGetAdminForm');
	}
	function getPlugin() {
		$input = JFactory::getApplication()->input;
		if ($plugin = $input->getString('plugin'))
			return JPluginHelper::getPlugin('fwfoodmenu', $plugin);
	}
	function processPlugin(&$plugin) {
		if (JPluginHelper::importPlugin('fwfoodmenu', $plugin->name)) {
			$app = JFactory::getApplication();
			$app->triggerEvent('onFwProcess', array($plugin->name));
		}
	}
	function exportData() {
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');

		$db = JFactory::getDBO();
		$app = JFactory::getApplication();
		$folder = '';
		$path = JPATH_SITE.'/tmp/';
		do {
			$folder = rand();
		} while (file_exists($path.$folder));
		JFolder::create($path.$folder);

		$tables = array(
			'category',
			'menu',
			'menu_price',
			'menu_modificator',
			'menu_modificator_group',
			'menu_image',
			'menu_badge',
			'badge',
			'translations'
		);

		$query = '';
		$input = $app->input;
		$cids = $input->getVar('cids');

		if (empty($cids)) {
			$tables = array_merge($tables, array(
				'cart',
				'order',
				'order_items',
				'order_statuschage'
			));
		}

		foreach ($tables as $suffix) {
			$table_name = '#__fwfoodmenu_'.$suffix;
			$table = $db->getPrefix().'fwfoodmenu_'.$suffix;
			$db->setQuery('SHOW CREATE TABLE `'.$table_name.'`');
			if ($obj = $db->loadAssoc()) {
				$query .= 'DROP TABLE IF EXISTS `'.$table_name."`;\n";
				$query .= str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ', str_replace($table, $table_name, $obj['Create Table'])).";\n\n";
			}

			$db->setQuery('SHOW COLUMNS FROM `'.$table_name.'`');
			if ($cols = $db->loadAssocList()) {
				foreach ($cols as $i=>$col) $cols[$i]['is_numeric'] = preg_match("/^(\w*int|year)/", $col['Type'])?true:false;
				$where = array();
				if (!empty($cids)) {
					switch ($suffix) {
						case 'category' :
							$where[] = 'a.id IN ('.implode(',', $cids).')';
							break;
						case 'menu' :
							$where[] = 'a.category_id IN ('.implode(',', $cids).')';
							break;
						case 'menu_price' :
						case 'menu_image' :
						case 'menu_badge' :
							$where[] = 'a.menu_id IN (SELECT b.id FROM `#__fwfoodmenu_menu` AS b WHERE b.category_id IN ('.implode(',', $cids).'))';
							break;
					}
				}
				$db->setQuery('SELECT * FROM `'.$table_name.'` AS a'.($where?(' WHERE '.implode(' AND ', $where)):''));
				if ($list = $db->loadAssocList()) {
					$fh_csv = fopen($path.$folder.'/fwfm_'.$suffix.'.csv', 'w');
					foreach ($list as $j=>$row) {
						if ($fh_csv) {
							if (!$j) {
								fputcsv($fh_csv, array_keys($row));
							}
							fputcsv($fh_csv, $row);
						}
						$query .= 'INSERT INTO `'.$table_name.'` VALUES (';
						foreach ($cols as $i=>$col) {
							if ($i) $query .= ',';
							if ($col['Field'] and $col['is_numeric']) $query .= (int)$row[$col['Field']];
							elseif (is_null($row[$col['Field']])) $query .= 'NULL';
							else $query .= $db->quote($row[$col['Field']]);
						}
						$query .= ");\n";
					}
					if ($fh_csv) {
						fclose($fh_csv);
					}
				}
			}
			$query .= "\n";
		}
		JFile::write($path.$folder.'/dbdump.sql', $query);

		$db->setQuery('SELECT `params` FROM `#__extensions` WHERE `type` = \'component\' AND `element` = \'com_fwfoodmenu\'');
		if ($params = $db->loadResult()) {
			/* remove google map key from demo backups */
			if (strpos(JURI::root(true), 'foodmenu') !== false) {
				$obj = new JRegistry($params);
				$obj->set('map_key', '');
				$params = $obj->toString();
			}
			JFile::write($path.$folder.'/settings.txt', $params);
		}

		return $folder;
	}
	function storeExportData() {
		$app = JFactory::getApplication();
		$input = $app->input;
		if ($folder = $input->getString('folder')) {
			$src_path = str_replace('\\', '/', JPATH_SITE).'/tmp/'.$folder.'/';
			if (!is_dir($src_path)) {
				$this->setError(JText::_('FWFM_NO_DATA_FOLDER'));
				return;
			}
			$trg_path = str_replace('\\', '/', JPATH_SITE).'/media/com_fwfoodmenu/backups/';
			if (!file_exists($trg_path)) {
				JFolder::create($trg_path);
			}
			if (!file_exists($trg_path)) {
				$this->setError(JText::_('FWFM_CANT_CREATE_EXPORT_FOLDER'));
				return;
			}

			$images = $input->getInt('images');
			$pdf = $input->getInt('pdf');
			$cids = $input->getVar('cids');

			jimport('joomla.filesystem.folder');
			jimport('joomla.filesystem.file');

			$src_files = JFolder::files($src_path, '.*', true, true);
			if ($src_files) {
				$buff = array('FWFM_data_');
				if ($images) {
					$buff[] = 'images_';
				}
				if ($pdf) {
					$buff[] = 'pdf_';
				}

				$filename = implode('', $buff).date('d_M_Y_His').'.zip';
				$zip = new ZipArchive;
				if ($zip->open($trg_path.$filename, ZipArchive::CREATE) === TRUE) {
					if ($images || $pdf) {
						$images_src_path = str_replace('\\', '/', JPATH_SITE).'/media/com_fwfoodmenu';
						$image_files = JFolder::files($images_src_path, '.*', true, true);
						if ($image_files) {
							foreach ($image_files as $file) {
								$loc_path = str_replace($images_src_path.'/', '', str_replace('\\', '/', $file));
								if (preg_match('#FWFM_data.*zip$#', $loc_path)) {
									continue;
								}
								$add_file = ($images and $pdf and empty($cids));
								if (!$add_file) {
									$app->triggerEvent('onCheckFileNameExport', array('com_fwfoodmenu', $loc_path, &$add_file));
								}
								if ($add_file) {
									$zip->addFile($file, $loc_path);
								}
							}
						}
						$images_src_path = str_replace('\\', '/', JPATH_SITE).'/images';
						$image_files = JFolder::files($images_src_path, '.*', true, true);
						if ($image_files) {
							$cat_images = array();
							$db = JFactory::getDBO();
							$db->setQuery('SELECT `description` FROM `#__fwfoodmenu_category` WHERE `description` IS NOT NULL AND `description` <> \'\''.(empty($cids)?'':(' AND id IN ('.implode(',', $cids).')')));
							if ($list = $db->loadColumn()) {
								foreach ($list as $row) {
									if (preg_match_all('#src\="([^"]+)"#i', $row, $matches, PREG_SET_ORDER)) {
										foreach ($matches as $match) {
											$cat_images[] = $match[1];
										}
									}
								}
							}
							foreach ($image_files as $file) {
								$loc_path = 'images/'.str_replace($images_src_path.'/', '', str_replace('\\', '/', $file));
								$add_file = in_array($loc_path, $cat_images);
								if (!$add_file) {
									$app->triggerEvent('onCheckFileNameExport', array('com_fwfoodmenu', $loc_path, &$add_file));
								}
								if ($add_file) {
									$zip->addFile($file, $loc_path);
								}
							}
						}
					}
					foreach ($src_files as $file) {
						$loc_path = str_replace($src_path, '', str_replace('\\', '/', $file));
						$zip->addFile($file, $loc_path);
					}
					$zip->close();
					JFolder::delete(JPATH_SITE.'/tmp/'.$folder);
					return $filename;
				}
			} else {
				$this->setError(JText::_('FWFM_NO_DATA_EXPORT'));
			}
		} else {
			$this->setError(JText::_('FWFM_NO_FOLDER_TO_EXPORT'));
		}
	}
	function getBackupsList() {
		jimport('joomla.filesystem.folder');
		$src_path = str_replace('\\', '/', JPATH_SITE).'/media/com_fwfoodmenu/backups';
		return is_dir($src_path)?JFolder::files($src_path, '\.zip$'):array();
	}
	function backupRestore() {
		$input = JFactory::getApplication()->input;
		if ($filename = str_replace(array('/', '\\'), '', $input->getString('filename'))) {
			$path = JPATH_SITE.'/media/com_fwfoodmenu/backups/';
			if (file_exists($path.$filename)) {
				jimport('joomla.filesystem.folder');
				jimport('joomla.filesystem.file');
				$trg_path = JPATH_SITE.'/media/com_fwfoodmenu/';
				if (strpos('_data_images_', $filename) !== false) {
					$dirs = JFolder::folders($trg_path);
					foreach ($dirs as $dir) {
						if (is_dir($trg_path.$dir)) {
							JFolder::delete($trg_path.$dir);
						}
					}
				}
				$zip = new ZipArchive;
				if ($zip->open($path.$filename) === TRUE) {
					$zip->extractTo($trg_path);
					$zip->close();

					if (is_dir($trg_path.'images')) {
						if (!file_exists(JPATH_SITE.'/images')) {
							JFile::write(JPATH_SITE.'/images/index.html', $body='<html><body></body></html>');
						}
						if (is_dir(JPATH_SITE.'/images')) {
							JFolder::copy($trg_path.'images', JPATH_SITE.'/images', '', true);
						}
						JFolder::delete($trg_path.'images');
					}

					$db = JFactory::getDBO();
					if (file_exists($trg_path.'dbdump.sql')) {
						$buff = file_get_contents($trg_path.'dbdump.sql');
						$queries = fwFoodMenuHelper::splitSql($buff);

						$err = $total = 0;
						foreach ($queries as $query) {
							if (trim($query)) {
								$db->setQuery($query);
								if (!$db->execute()) {
									$err++;
								}
								$total++;
							}
						}

						JFile::delete($trg_path.'dbdump.sql');
					}
					if (file_exists($trg_path.'settings.txt')) {
						$params = JComponentHelper::getParams('com_fwfoodmenu');
						$params->loadFile($trg_path.'settings.txt');
						$db->setQuery('UPDATE #__extensions SET params = '.$db->quote($params->toString()).' WHERE `element` = \'com_fwfoodmenu\' AND `type` = \'component\'');
						$db->execute();
						JFile::delete($trg_path.'settings.txt');
					}
					if ($files = JFolder::files($trg_path, '\.csv$', false, false)) {
						foreach ($files as $file) {
							JFile::delete($trg_path.$file);
						}
					}
					fwFoodMenuHelper::addMessage(JText::_('FWFM_BACKUP_SUCCESFULLY_INSTALLED'), 'success');
					return true;
				}
			} else {
				$this->setError(JText::_('FWFM_FILE_NOT_FOUND_TO_RESTORE'));
			}
		} else {
			$this->setError(JText::_('FWFM_NO_FILENAME_TO_RESTORE'));
		}
	}
	function backupDelete() {
		$input = JFactory::getApplication()->input;
		if ($filename = str_replace(array('/', '\\'), '', $input->getString('filename'))) {
			$path = JPATH_SITE.'/media/com_fwfoodmenu/backups/';
			if (file_exists($path.$filename)) {
				jimport('joomla.filesystem.file');
				if (JFile::delete($path.$filename)) {
					return true;
				} else {
					$this->setError(JText::_('FWFM_CANT_DELETE_FILE'));
				}
			} else {
				$this->setError(JText::_('FWFM_FILE_NOT_FOUND_TO_DELETE'));
			}
		} else {
			$this->setError(JText::_('FWFM_NO_FILENAME_TO_DELETE'));
		}
	}
	function backupUpload() {
		$input = JFactory::getApplication()->input;
		if ($file = $input->files->get('upload', array(), 'raw') and !empty($file['name']) and empty($file['error'])) {
			jimport('joomla.filesystem.folder');
			jimport('joomla.filesystem.file');
			$path = JPATH_SITE.'/media/com_fwfoodmenu/backups/';
			if (!file_exists($path)) {
				JFolder::create($path);
			}
			$filename = JFile::makeSafe($file['name']);
			if (JFile::copy($file['tmp_name'], $path.$filename)) {
				return $filename;
			} else {
				$this->setError(JText::_('FWFM_CANT_COPY_UPLOADED_FILE'));
			}
		} else {
			$this->setError(JText::_('FWFM_NO_FILE_TO_UPLOAD'));
		}
	}
}
