<?php

/**
 * Snippet to implement Facebook comment boxes.
 *
 * 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\module\social
 * @copyright Copyright (c) 2012 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 * @see https://developers.facebook.com/docs/reference/plugins/comments/
 */

/** @var $tplEngine cfTemplateEngine */

// Get parameters
$numPosts = isset($numPosts) ? $numPosts : 10;
$width = isset($width) ? $width : 470;

$request = $tplEngine->controller->getRequest();
$self = $request->getSelf(true);
echo '<div class="cfSocialFBComments"><div class="fb-comments" data-href="' . $self . "\" data-num-posts=\"$numPosts\" data-width=\"$width\" data-notify=\"true\"></div></div>";
$tplEngine->getCodeBuffer()->requireCore()->bufferHeadJS('system/modules/social/js/social.js');

// If AJAX call
if($request->isXmlHttpRequest() &&
	$request->isPost() &&
	$request->getPost('href', '') == $self &&
	($request->getPost('op', '') == 'fbCommentAdd' || $request->getPost('op', '') == 'fbCommentRemove')) {

	// Get notification email address if any
	$cfg = clearFusionCMS::getSiteConfig('cfSocial');
	$notify = $cfg->get('fbCommentNotify', '');
	$href = $request->getParam('href');

	if(!empty($notify)) {
		$mailer = clearFusionCMS::getMailer();
		$mailer->addRecipient($notify);
		if($request->getParam('op') == 'fbCommentAdd') {
			$mailer->setSubject(__('Notification of New Facebook Comment', 'social'));
			$mailer->setTextBody(sprintf(__("A new Facebook comment has been posted on your website at:\n\n%s\n\n", 'social'), $href));
			$mailer->setHTMLBody('<p>' . sprintf(__("A new Facebook comment has been posted on your website, <a href=\"%s\">View</a>", 'social'), $href) . '</p>');
		}
		else {
			$mailer->setSubject(__('Notification of Removal of a Facebook Comment', 'social'));
			$mailer->setTextBody(sprintf(__("A Facebook comment has been removed from your website at:\n\n%s\n\n", 'social'), $href));
			$mailer->setHTMLBody('<p>' . sprintf(__("A Facebook comment has been removed from your website <a href=\"%s\">View</a>", 'social'), $href) . '</p>');
		}

		// Send notification
		if($mailer->connect()) {
			$mailer->send();
			$mailer->close();
		}
	}

	$event = new cfEventNotify(
		$cfg->get('fbCmntSysNotify', 3),
		__('New Facebook Comment', 'social'),
		$request->getParam('op') == 'fbCommentAdd' ?
			sprintf(__('A new Facebook comment has been posted on your website at %s', 'social'), $href) :
			sprintf(__('A Facebook comment has been removed from your website at %s', 'social'), $href)
	);
	$event->mention($cfg->get('fbCmntMentions', ''))
		->trigger();
}