<?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\module\social
 * @copyright Copyright (c) 2013 - 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * socialBackendTwitterAction Class
 *
 * Backend controller for editing & managing store categories.
 *
 * @package clearFusionCMS\module\social
 */
class socialBackendTwitterAction extends cfBackendControllerAction {

	/**
	 * Render the page.
	 *
	 * @param string $nodeId The node.
	 * @param string $content The page content.
	 */
	function renderStorePage($nodeId, $content) {

		$rootTree = new flWidgetTreeView();

		// Build tree of albums
		$tree = new flWidgetTreeView();
		$results = $this->db->query('SELECT feedid,screenname FROM cf_socialtwitter_' . clearFusionCMS::getSite() . ' ORDER BY screenname');
		while($row = $results->fetch()) {
			$tree->addNode(new flWidgetTreeLinkNode("$row[screenname] [$row[feedid]]", $this->assemble('social', 'twitter', array('edit', $row['feedid'])), flWidgetTreeNode::NODE))
				->setLastNodeActive($nodeId == $row['feedid']);
		}

		$rootTree->addNode($results->numRows() ? new flWidgetTreeChildNode(__('Twitter Feeds', 'socialBackend'), $tree, null) : new flWidgetTreeNode(__('Twitter Feeds', 'socialBackend'), flWidgetTreeNode::CONTAINER));

		// Create the toolbar
		$fam = new flWidgetFloatingActionMenu();
		$fam->addAction('add', __('Add Feed', 'socialBackend'), $this->assemble('social', 'twitter', array('add')));

		$this->tpl->registerChunk('fam', $fam->render());

		// Render the page
		$this->renderPage(__('Twitter', 'socialBackend'), $content, $this->renderBlock('', $rootTree->render($this->tpl->getCodeBuffer())));
	}

	/**
	 * Process the request
	 */
	function process() {
		$this->testPermission('cfSocial.twitter');
		$this->breadcrumbTrail->addCrumb(__('Twitter Feeds', 'socialBackend'), $this->assemble('social', 'twitter'));

		$content = '';
		$active = null;
		$msg = $this->session->flashGet('cfManagerOpSuccess') ? $this->session->flashGet('cfManagerOpSuccess') : '';

		$addRoute = new flRouterRoute('add');
		$editRoute = new flRouterRoute('edit/:id', array(), array('id' => '\d+'));
		$delRoute = new flRouterRoute('delete/:id', array(), array('id' => '\d+'));

		// If adding
		if($params = $addRoute->match($this->request->getParam('*', array()))) {
			$this->breadcrumbTrail->addCrumb(__('Add Feed', 'socialBackend'), $this->assemble('social', 'twitter', array('add')));

			$form = new flForm($this->request, 'feedform', $this->assemble('social', 'twitter', array('add')), true);
			$form->setCSS('metaSSubmit');

			// Capture ctrl+s for save
			$this->tpl->getCodeBuffer()->bufferHeadJS('system/app/js/cfMetaS.js');
			$this->confirmLeavePage();

			$name = new flFormElementText($form, 'accname');
			$name->setLabel(__('Twitter Account Name', 'socialBackend'))
				->setRequired()
				->addValidator(new flFormValidatorRequired())
				->addValidator(new flFormValidatorMaxLength(16));

			$count = new flFormElementNumber($form, 'count', 0, 200, 20);
			$count->setLabel(__('Number of Tweets to Fetch', 'socialBackend'))
				->setRequired()
				->addValidator(new flFormValidatorRequired())
				->addValidator(new flFormValidatorMax(200));

			$exreplies = new flFormElementCheckbox($form, 'exreplies', 0);
			$exreplies->setLabel(__('Exclude replies from fetched tweets', 'socialBackend'));

			$panel = new flFormElementPane($form, 'note', $this->alertMessage('Info', __('It may take 5 minutes or more for a new feed to show.', 'socialBackend')));

			$submit = new flFormElementSubmit($form, 'create');
			$submit->setCaption(__('Add Feed', 'socialBackend'))->setCSS('primary');

			$form->focusElement($name);

			$form->groupElements('info', array($name, $count, $exreplies, $panel))
				->setGroupLabel('info', __('Feed Information', 'socialBackend'))
				->groupElements('submit', array($submit), new flFormDecoratorList(new flFormDecoratorDl()));

			$msg = '';
			if($form->isSubmitted() && $form->isValid()) {
				if($this->db->insert('cf_socialtwitter_' . clearFusionCMS::getSite(), array(
					'screenname' => $name->getValue(),
					'tweetcount' => $count->getValue(),
					'exreplies' => $exreplies->getValue(),
					'feedcache' => ''
				))) {
					$id = $this->db->insertID();
					$this->cache->flush();
					socialAudit::create($id, $name->getValue());

					// Enable the cron
					$em = clearFusionCMS::getEventManager();
					$em->addListener('system.cron5m', 'socialEvents', 'onCron');

					$this->session->flashSet('cfManagerOpSuccess', $this->alertMessage('Success', __('The new feed has been added.', 'socialBackend')));
					$this->response->redirectTo($this->assemble('social', 'twitter', array('edit', $id), true));
				}
				else
					$msg = $this->alertMessage('Error', __('Unable to add the new feed, please try again.', 'socialBackend'));
			}

			$content = $this->renderBlock(__('Add Twitter Feed', 'socialBackend'), $form->render($this->tpl->getCodeBuffer()), '', $msg);
		}
		// If editing
		else if($params = $editRoute->match($this->request->getParam('*', array()))) {
			$this->breadcrumbTrail->addCrumb(__('Edit Feed', 'socialBackend'), $this->assemble('social', 'twitter', array('edit', $params['id'])));
			$active = $params['id'];

			if(($content = $this->lockObject('social.twitter.', $params['id'])) === true) {
				if($data = $this->db->fetchRow('SELECT screenname,tweetcount,exreplies FROM cf_socialtwitter_' . clearFusionCMS::getSite() . ' WHERE feedid=?', $params['id'])) {

					$form = new flForm($this->request, 'feedform', $this->assemble('social', 'twitter', array('edit', $params['id'])), true);
					$form->setCSS('metaSSubmit');

					// Capture ctrl+s for save
					$this->tpl->getCodeBuffer()->bufferHeadJS('system/app/js/cfMetaS.js');
					$this->confirmLeavePage();

					$name = new flFormElementText($form, 'accname', $data['screenname']);
					$name->setLabel(__('Twitter Account Name', 'socialBackend'))
						->setRequired()
						->addValidator(new flFormValidatorRequired())
						->addValidator(new flFormValidatorMaxLength(16));

					$count = new flFormElementNumber($form, 'count', 0, 200, $data['tweetcount']);
					$count->setLabel(__('Number of Tweets to Fetch', 'socialBackend'))
						->setRequired()
						->addValidator(new flFormValidatorRequired())
						->addValidator(new flFormValidatorMax(200));

					$exreplies = new flFormElementCheckbox($form, 'exreplies', $data['exreplies']);
					$exreplies->setLabel(__('Exclude replies from fetched tweets', 'socialBackend'));

					$panel = new flFormElementPane($form, 'note', $this->alertMessage('Info', __('It may take 5 minutes or more for changes to take effect.', 'socialBackend')));

					$submit = new flFormElementSubmit($form, 'update');
					$submit->setCaption(__('Update Feed', 'socialBackend'))->setCSS('primary');

					$del = new flFormElementSubmit($form, 'delete');
					$del->setCaption(__('Delete Feed', 'socialBackend'))
						->setCSS('danger');

					$form->groupElements('info', array($name, $count, $exreplies, $panel))
						->setGroupLabel('info', __('Feed Information', 'socialBackend'))
						->groupElements('submit', array($submit, $del), new flFormDecoratorList(new flFormDecoratorDl()))
						->focusElement($name);

					if($form->isSubmitted() && $form->isValid()) {
						if($del->getValue())
							$this->response->redirectTo($this->assemble('social', 'twitter', array('delete', $params['id']), true));

						if($this->db->update('cf_socialtwitter_' . clearFusionCMS::getSite(), array(
							'screenname' => $name->getValue(),
							'tweetcount' => $count->getValue(),
							'exreplies' => $exreplies->getValue()
						), 'feedid=?', $params['id'])) {
							socialAudit::update($params['id'], $name->getValue(), $data);

							$this->cache->flush();
							$this->session->flashSet('cfManagerOpSuccess', $this->alertMessage('Success', __('The feed has been updated.', 'socialBackend')));
							$this->response->redirectTo($this->assemble('social', 'twitter', array('edit', $params['id']), true));
						}
						else
							$msg = $this->alertMessage('Error', __('Unable to update the feed, please try again.', 'socialBackend'));
					}

					$content = $this->renderBlock(__('Edit Twitter Feed', 'socialBackend'), $form->render($this->tpl->getCodeBuffer()), '', $msg);
				}
				else
					$this->response->redirectTo($this->assemble('social', 'twitter', array(), true));
			}
		}
		// If deleting
		else if($params = $delRoute->match($this->request->getParam('*', array()))) {
			$this->breadcrumbTrail->addCrumb(__('Delete Feed', 'socialBackend'), $this->assemble('social', 'twitter', array('delete', $params['id'])));
			$active = $params['id'];

			if(($content = $this->lockObject('social.twitter.', $params['id'])) === true) {
				if($data = $this->db->fetchRow('SELECT * FROM cf_socialtwitter_' . clearFusionCMS::getSite() . ' WHERE feedid=?', $params['id'])) {

					$form = new flForm($this->request, 'deletecatform', $this->assemble('social', 'twitter', array('delete', $params['id'])), true);

					$name = new flFormElementText($form, 'name', $data['screenname']);
					$name->setLabel(__('Delete Feed', 'socialBackend'))
						->setDisabled()
						->setReadonly();

					$delSubmit = new flFormElementSubmit($form, 'deletesubmit');
					$delSubmit->setCaption(__('Permanently Delete The Feed', 'socialBackend'))
						->setCSS('danger')
						->setDescription($this->alertMessage('Warning', __('This operation cannot be undone and will permanently delete feed!', 'socialBackend')));

					if($form->isSubmitted() && $form->isValid()) {
						socialAudit::delete($params['id'], $data);

						$this->db->delete('cf_socialtwitter_' . clearFusionCMS::getSite(), 'feedid=?', $params['id']);

						// Enable / disable the cron as required
						$feeds = $this->db->fetchOne('SELECT COUNT(*) AS c FROM cf_socialtwitter_' . clearFusionCMS::getSite());
						if(!$feeds) {
							$em = clearFusionCMS::getEventManager();
							$em->removeListener('system.cron5m', 'socialEvents', 'onCron');
						}

						$this->cache->flush();
						$this->response->redirectTo($this->assemble('social', 'twitter', array(), true));
					}

					$content = $this->renderBlock(__('Delete Feed', 'socialBackend'), $form->render($this->tpl->getCodeBuffer()), '', $msg);
				}
				else
					$this->response->redirectTo($this->assemble('social', 'twitter', array(), true));
			}
		}

		$this->renderStorePage($active, $content);
	}
}
