<?php

/**
 * Snippet to import the contents of a document.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\snippet\import
 * @copyright Copyright (c) 2014 - 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/* @var $tplEngine cfTemplateEngine */

$itemTpl = isset($itemTpl) ? $tplEngine->getChunk($itemTpl) : '[[+content]]';

$children = array();

// If single document
if(isset($id)) {
	$children = clearFusionCMS::getDb()->fetchAll('SELECT c.id,c.template,c.content,c.title,c.slug,ct.snippet FROM cf_content_' . clearFusionCMS::getSite() . " AS c
	LEFT JOIN cf_contenttype AS ct ON c.contenttype=ct.id
	WHERE c.id=? && c.published", $id);
}
// If children
else if(isset($childrenOf)) {
	$ex = '';
	$params = array($childrenOf);
	if(isset($exclude)) {
		$exclude = preg_split('/[\s^]*,[\s$]*/', $exclude, 0, PREG_SPLIT_NO_EMPTY);
		if(count($exclude)) {
			$ex = '&& id NOT IN(' . str_repeat('?,', count($exclude) - 1) . '?)';
			$params = array_merge($params, $exclude);
		}
	}

	$children = clearFusionCMS::getDb()->fetchAll('SELECT c.id,c.template,c.content,c.title,c.slug,ct.snippet FROM cf_content_' . clearFusionCMS::getSite() . " AS c
	LEFT JOIN cf_contenttype AS ct ON c.contenttype=ct.id
	WHERE c.parentid=? && c.published $ex ORDER BY lft ASC", $params);
}

// Render
if(isset($customFields)) {
	// Get the fields
	$flds = explode(',', $customFields);
	$fldQ = str_repeat(',?', count($flds) - 1);
	array_unshift($flds, 0);
	array_unshift($flds, 0);
}

foreach($children as $child) {
	$d = array(
		'title'   => $child['title'],
		'content' => cfContentFilter::apply($child['snippet'], $child['content']),
		'anchor'  => $child['slug']
	);

	// Get the custom fields
	if(isset($customFields)) {
		$flds[0] = $child['id'];
		$flds[1] = $child['template'];

		$result = clearFusionCMS::getDb()->query('SELECT fc.placeholder,fc.content,cf.snippet FROM cf_customflds_ctnt_' . clearFusionCMS::getSite() . " AS fc
		 LEFT JOIN cf_customflds_templates  AS ft USING(placeholder)
		 LEFT JOIN cf_customflds AS cf USING(placeholder)
		 WHERE id=? && template=? && placeholder IN(?$fldQ)", $flds);
		while($row = $result->fetch())
			$d[$row['placeholder']] = $row['content'];
	}

	echo $tplEngine->parseString($itemTpl, $d);
}
