<?php

/**
 * 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
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfSocialImagesMgr Class
 *
 * Static class for accessing and manipulating social images.
 *
 * @package clearFusionCMS
 */
abstract class cfSocialImagesMgr {

	/**
	 * Get the images in the system.
	 *
	 * @param string $noImageLabel The label to use for no image, defaults to [None]
	 * @return array Array of image ID's and titles.
	 * @throws flDbException
	 */
	static public function getImages($noImageLabel = null) {

		// Get the list of social images
		$socialImages = array(
			0 => $noImageLabel != null ? $noImageLabel : __('[None]', 'cfBackend')
		);

		$result = clearFusionCMS::getDb()->query('SELECT imageid,title FROM cf_socialimages_' . clearFusionCMS::getSite() . ' ORDER BY title ASC');
		while($row = $result->fetch()) {
			$socialImages[$row['imageid']] = $row['title'];
		}

		return $socialImages;
	}

	/**
	 * Get the filename of a social media image.
	 *
	 *
	 * @param int $id The ID of the story.
	 * @param bool $withFileTime true to include the file modified time on the end of the file name.
	 * @return string The filename to use.
	 */
	static public function getFilename($id, $withFileTime = false) {
		// Calculate the storage path and file name
		$cfg = clearFusionCMS::getSiteConfig('cfSystemFileStore');
		$idHash = md5($id);
		$ext = clearFusionCMS::getDb()->fetchOne('SELECT ext FROM cf_socialimages_' . clearFusionCMS::getSite() . ' WHERE imageid=?', $id);

		$file = $cfg->publicStorage . '/content_social/' . clearFusionCMS::getSite() . '/' . $idHash[0] . '/' . $idHash[1] . '/' . $id . $ext;

		if($withFileTime)
			$file .= '?ft=' . filemtime($file);

		return $file;
	}

	/**
	 * Handle AJAX requests for social image files. Never returns if processing a social media image request.
	 *
	 * @param flRequest $request The request object.
	 * @param flResponse $response The response object.
	 */
	static public function handleAJAXRequest($request, $response) {
		// If looking up social media image
		if ($request->isXmlHttpRequest() && $request->isPost() && $request->hasPost('socialimageid')) {
			$response->setContentType('application/json')
				->noCache()
				->setBody(json_encode(array(
					'path' => self::getFilename($request->getPost('socialimageid'), true)
				)))
				->sendResponse();
			die;
		}
	}

	/**
	 * @param flBufferCode $codeBuffer The code buffer.
	 * @param flForm $form The form object.
	 * @param array $data The current values.
	 * @param string $noImageLabel The label to use for no image, defaults to [None], or false to disable images
	 * @return array The elements.
	 */
	static public function buildFormElement($codeBuffer, $form, $data = array(), $noImageLabel = null) {
		$ogtitle = new flFormElementText($form, 'ogtitle', isset($data['ogtitle']) ? $data['ogtitle'] : '');
		$ogtitle->setLabel(__('Open Graph Title', 'cfBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		$ogdesc = new flFormElementTextArea($form, 'ogdesc', isset($data['ogdesc']) ? $data['ogdesc'] : '');
		$ogdesc->setLabel(__('Open Graph Description', 'cfBackend'))
			->addValidator(new flFormValidatorMaxLength(4096))
			->setRows(2);

		$twittertitle = new flFormElementText($form, 'twittertitle', isset($data['twittertitle']) ? $data['twittertitle'] : '');
		$twittertitle->setLabel(__('Twitter Card Title', 'cfBackend'))
			->addValidator(new flFormValidatorMaxLength(255));

		$twitterdesc = new flFormElementTextArea($form, 'twitterdesc', isset($data['twitterdesc']) ? $data['twitterdesc'] : '');
		$twitterdesc->setLabel(__('Twitter Card Description', 'cfBackend'))
			->addValidator(new flFormValidatorMaxLength(4096))
			->setRows(2);

		// Get the list of social images
		if($noImageLabel !== false) {
			$socialImages = self::getImages($noImageLabel);

			$ogImage = new flFormElementSelect($form, 'ogimageid', isset($data['ogimageid']) ? $data['ogimageid'] : '', $socialImages);
			$ogImage->setLabel(__('Open Graph Image', 'cfBackend'));

			$ogImagePane = new flFormElementPane($form, 'ogimagepane', isset($data['ogimageid']) && $data['ogimageid'] ? '<img src="' . cfSocialImagesMgr::getFilename($data['ogimageid']) . '?cb=' . time() . '" />' : '');

			$twitterImage = new flFormElementSelect($form, 'twitterimageid', isset($data['twitterimageid']) ? $data['twitterimageid'] : '', $socialImages);
			$twitterImage->setLabel(__('Twitter Card Image', 'cfBackend'));

			$twitterImagePane = new flFormElementPane($form, 'twitterimagepane', isset($data['twitterimageid']) && $data['twitterimageid'] ? '<img src="' . cfSocialImagesMgr::getFilename($data['twitterimageid']) . '?cb=' . time() . '" />' : '');

			$codeBuffer->bufferBodyJS("
	\$fl('#ogimageid').bind('change', function(e) {
		var id = \$fl(e.target).val();
		if(id == 0) {
			\$fl('#ogimagepane-container').html('');
		}
		else {
			\$fl.post(document.location, { socialimageid: id }, function(d) {
				\$fl('#ogimagepane-container').html('<img src=\"' + d.path + '\" />');
			});
		}
	});

	\$fl('#twitterimageid').bind('change', function(e) {
		var id = \$fl(e.target).val();
		if(id == 0) {
			\$fl('#twitterimagepane-container').html('');
		}
		else {
			\$fl.post(document.location, { socialimageid: id }, function(d) {
				\$fl('#twitterimagepane-container').html('<img src=\"' + d.path + '\" />');
			});
		}
	});
");

			return array(
				$ogtitle, $ogdesc, $ogImage, $ogImagePane,
				$twittertitle, $twitterdesc, $twitterImage, $twitterImagePane
			);
		}
		else {
			return array(
				$ogtitle, $ogdesc, $twittertitle, $twitterdesc
			);
		}
	}
}
