<?php

/**
 * Ahead WebSoft Technologies Pvt Ltd.
 * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
 * @license    https://www.socialengine.com/policies
 */

class Pulse_AdminSettingsController extends Core_Controller_Action_Admin
{

	public function indexAction()
	{

		$db = Engine_Db_Table::getDefaultAdapter();

		$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('pulse_admin_main', array(), 'pulse_admin_main_settings');

		$this->view->form = $form = new Pulse_Form_Admin_Settings_Global();

		if ($this->getRequest()->isPost() && $form->isValid($this->_getAllParams())) {

			$values = $form->getValues();

			$changelanding = Engine_Api::_()->getApi('settings', 'core')->getSetting('pulse.changelanding', 0);
			if (isset($values['pulse_changelanding']) && !empty($values['pulse_changelanding']) && $changelanding != $values['pulse_changelanding']) {
				$this->landingpageSet($values['pulse_changelanding']);
			}

			if (isset($values['pulse_headernonloggedinoptions'])) {
				if (!empty($values['pulse_headernonloggedinoptions']))
					$values['pulse_headernonloggedinoptions'] = serialize($values['pulse_headernonloggedinoptions']);
				else
					$values['pulse_headernonloggedinoptions'] = serialize(array());
			}

			if (isset($values['pulse_headerloggedinoptions'])) {
				if (!empty($values['pulse_headerloggedinoptions']))
					$values['pulse_headerloggedinoptions'] = serialize($values['pulse_headerloggedinoptions']);
				else
					$values['pulse_headerloggedinoptions'] = serialize(array());
			}

			foreach ($values as $key => $value) {
				Engine_Api::_()->getApi('settings', 'core')->setSetting($key, $value);
			}

			//Save constant
			$themeConstants = Engine_Api::_()->pulse()->themeConstants();
			Engine_Api::_()->core()->saveThemeVariables($themeConstants, $form, 'pulse');

			$form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved.'));
		}
	}

	public function footerAction()
	{

		$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('pulse_admin_main', array(), 'pulse_admin_main_footer');

		$this->view->form = $form = new Pulse_Form_Admin_Settings_Footer();

		if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
			$values = $form->getValues();
			foreach ($values as $key => $value) {
				Engine_Api::_()->getApi('settings', 'core')->setSetting($key, $value);
			}
			$form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved.'));
		}
	}

	public function stylingAction()
	{

		$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('pulse_admin_main', array(), 'pulse_admin_main_styling');

		$settings = Engine_Api::_()->getApi('settings', 'core');

		$this->view->customtheme_id = $this->_getParam('customtheme_id', 1);

		$this->view->form = $form = new Pulse_Form_Admin_Settings_Styling();

		if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {

			$db = Engine_Db_Table::getDefaultAdapter();

			$values = $form->getValues();
			unset($values['header_settings']);
			unset($values['footer_settings']);
			unset($values['body_settings']);
			unset($values['custom_themes']);
			$theme_id = $values['theme_color'];

			if (isset($_POST['save'])) {
				$themeConstants = Engine_Api::_()->pulse()->themeConstants($values);
				Engine_Api::_()->core()->saveThemeVariables($themeConstants, $form, 'pulse');
				Engine_Api::_()->getApi('settings', 'core')->setSetting('pulse.theme.color', $theme_id);
				Engine_Api::_()->getApi('settings', 'core')->setSetting('contrast.mode', $values['contrast_mode']);
			}

			foreach ($values as $key => $value) {
				if ((isset($_POST['submit']) || isset($_POST['save'])) && $values['theme_color'] > '3') {
					foreach ($values as $key => $value) {
						$db->query("UPDATE `engine4_pulse_customthemes` SET `value` = '" . $value . "' WHERE `engine4_pulse_customthemes`.`theme_id` = '" . $theme_id . "' AND  `engine4_pulse_customthemes`.`column_key` = '" . $key . "';");
					}
				}
			}

			$form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved.'));
			$this->_helper->redirector->gotoRoute(array('module' => 'pulse', 'controller' => 'settings', 'action' => 'styling', 'customtheme_id' => $values['theme_color']), 'admin_default', true);
		}
		$this->view->activatedTheme = $settings->getSetting('pulse.theme.color', 1);
	}

	public function addAction()
	{

		$this->_helper->layout->setLayout('admin-simple');

		$customtheme_id = $this->_getParam('customtheme_id', 0);

		$this->view->form = $form = new Pulse_Form_Admin_Settings_CustomTheme();
		if ($customtheme_id) {
			$form->setTitle("Edit Custom Theme Name");
			$form->submit->setLabel('Save Changes');
			$customtheme_id = $customtheme_id + 1;
			$customtheme = Engine_Api::_()->getItem('pulse_customthemes', $customtheme_id);
			$form->populate($customtheme->toArray());
		}

		if ($this->getRequest()->isPost()) {

			if (!$form->isValid($this->getRequest()->getPost()))
				return;

			$table = Engine_Api::_()->getDbtable('customthemes', 'pulse');

			$db = $table->getAdapter();
			$db->beginTransaction();
			try {

				$values = $form->getValues();

				if (!$customtheme_id) {
					$customtheme = $table->createRow();
					$customtheme->setFromArray($values);
					$customtheme->save();

					$theme_id = $customtheme->customtheme_id;

					if (!empty($values['customthemeid'])) {

						$dbInsert = Engine_Db_Table::getDefaultAdapter();

						$getThemeValues = $table->getThemeValues(array('customtheme_id' => $values['customthemeid']));
						foreach ($getThemeValues as $key => $value) {
							$dbInsert->query("INSERT INTO `engine4_pulse_customthemes` (`name`, `value`, `column_key`,`default`,`theme_id`) VALUES ('" . $values['name'] . "','" . $value->value . "','" . $value->column_key . "','1','" . $theme_id . "') ON DUPLICATE KEY UPDATE `value`='" . $value->value . "';");
						}
						$db->query("UPDATE `engine4_pulse_customthemes` SET `value` = '" . $theme_id . "' WHERE theme_id = " . $theme_id . " AND column_key = 'custom_theme_color';");
						$db->query('DELETE FROM `engine4_pulse_customthemes` WHERE `engine4_pulse_customthemes`.`theme_id` = "0";');
					}
				} else if (!empty($customtheme_id)) {
					$theme_id = $customtheme_id = $customtheme_id - 1;
					$db->query("UPDATE `engine4_pulse_customthemes` SET `name` = '" . $values['name'] . "' WHERE theme_id = " . $customtheme_id);
				}
				$db->commit();
				if (!$customtheme_id) {
					$message = array(Zend_Registry::get('Zend_Translate')->_('New Custom theme created successfully.'));
				} else {
					$message = array(Zend_Registry::get('Zend_Translate')->_('New Custom theme edited successfully.'));
				}
				return $this->_forward('success', 'utility', 'core', array(
					'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('module' => 'pulse', 'controller' => 'settings', 'action' => 'styling', 'customtheme_id' => $theme_id), 'admin_default', true),
					'messages' => $message,
				));
			} catch (Exception $e) {
				$db->rollBack();
				throw $e;
			}
		}
	}

	public function deleteAction()
	{

		$this->_helper->layout->setLayout('admin-simple');
		$this->view->customtheme_id = $customtheme_id = $this->_getParam('customtheme_id', 0);

		if ($this->getRequest()->isPost()) {
			$db = Engine_Db_Table::getDefaultAdapter();
			$db->beginTransaction();
			try {
				$dbQuery = Zend_Db_Table_Abstract::getDefaultAdapter();
				$dbQuery->query("DELETE FROM engine4_pulse_customthemes WHERE theme_id = " . $customtheme_id);
				$db->commit();
				$activatedTheme = Engine_Api::_()->getApi('settings', 'core')->getSetting('pulse.theme.color', 1);
				$this->_forward('success', 'utility', 'core', array(
					'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('module' => 'pulse', 'controller' => 'settings', 'action' => 'styling', 'customtheme_id' => $activatedTheme), 'admin_default', true),
					'messages' => array(Zend_Registry::get('Zend_Translate')->_('You have successfully deleted the custom theme.'))
				));
			} catch (Exception $e) {
				$db->rollBack();
				throw $e;
			}
		} else {
			$this->renderScript('admin-settings/delete.tpl');
		}
	}

	public function getcustomthemecolorsAction()
	{

		$customtheme_id = $this->_getParam('customtheme_id', null);
		if (empty($customtheme_id))
			return;

		if (engine_in_array($customtheme_id, array(1, 2, 3)))
			$default = 0;
		else
			$default = 1;

		$themecustom = Engine_Api::_()->getDbTable('customthemes', 'pulse')->getThemeKey(array('theme_id' => $customtheme_id, 'default' => $default));
		$customthecolorArray = array();
		foreach ($themecustom as $value) {
			$customthecolorArray[] = $value['column_key'] . '||' . $value['value'];
		}
		echo json_encode($customthecolorArray);
		die;
	}

	public function landingpageSet($value)
	{

		$db = Zend_Db_Table_Abstract::getDefaultAdapter();

		// Get page param
		$pageTable = Engine_Api::_()->getDbtable('pages', 'core');
		$contentTable = Engine_Api::_()->getDbtable('content', 'core');

		// Make new page
		$pageObject = $pageTable->createRow();
		$pageObject->displayname = Zend_Registry::get('Zend_Translate')->_("Backup - Landing Page");
		$pageObject->provides = 'no-subject';
		$pageObject->save();
		$new_page_id = $pageObject->page_id;

		$old_page_content = $db->select()
			->from('engine4_core_content')
			->where('`page_id` = ?', 3)
			->order(array('type', 'content_id'))
			->query()
			->fetchAll();

		$content_count = engine_count($old_page_content);
		for ($i = 0; $i < $content_count; $i++) {
			$contentRow = $contentTable->createRow();
			$contentRow->page_id = $new_page_id;
			$contentRow->type = $old_page_content[$i]['type'];
			$contentRow->name = $old_page_content[$i]['name'];
			if ($old_page_content[$i]['parent_content_id'] != null) {
				$contentRow->parent_content_id = $content_id_array[$old_page_content[$i]['parent_content_id']];
			} else {
				$contentRow->parent_content_id = $old_page_content[$i]['parent_content_id'];
			}
			$contentRow->order = $old_page_content[$i]['order'];
			$contentRow->params = $old_page_content[$i]['params'];
			$contentRow->attribs = $old_page_content[$i]['attribs'];
			$contentRow->save();
			$content_id_array[$old_page_content[$i]['content_id']] = $contentRow->content_id;
		}

		$widgetOrder = 1;
		$db->query('DELETE FROM `engine4_core_content` WHERE `engine4_core_content`.`page_id` = "3";');

		$db->insert('engine4_core_content', array(
			'type' => 'container',
			'name' => 'main',
			'page_id' => 3,
			'order' => 1,
		));
		$mainId = $db->lastInsertId();

		$db->insert('engine4_core_content', array(
			'type' => 'container',
			'name' => 'middle',
			'page_id' => 3,
			'parent_content_id' => $mainId,
			'order' => 2,
		));
		$mainMiddleId = $db->lastInsertId();

		if ($value == 1) {

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-banner',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Where Connections Thrive!","description":"Join our network for endless opportunities, innovation, and collective growth. We are a one-stop solution where Innovation meets collaboration.","btntext":"Join Us","btntextlink":"signup","dummy1":null,"count1":"100","text1":"Posts","dummy2":null,"count2":"1500","text2":"Members","dummy3":null,"count3":"1000","text3":"Blogs","dummy4":null,"count4":"500","text4":"Forums","photo5":"","nomobile":"0","name":"pulse.landing-page-banner"}',
			));

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-features',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Explore What Makes the Experience Special","dummy1":null,"photo1":"","featuresheading1":"User-Friendly Experience","description1":"Enjoy a straightforward and easy-to-use platform for smooth navigation & responsiveness.","link1":"","dummy2":null,"photo2":"","featuresheading2":"Interactive Feeds","description2":"Get the latest updates and activities from your network through a dynamic content feed, keeping your experience vibrant and ever-evolving.","link2":"","dummy3":null,"photo3":"","featuresheading3":"Mobile Apps","description3":"Stay connected on the go with fast, native iOS and Android apps designed to access anytime, anywhere.","link3":"","nomobile":"0","name":"pulse.landing-page-features"}',
			));

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-counter-section',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Explore What Awaits You Inside!","btntext":"Signup","btntextlink":"signup","dummy1":null,"icon1":"fas fa-pager","count1":"100","text1":"Posts","dummy2":null,"icon2":"fas fa-user-friends","count2":"1500","text2":"Members","dummy3":null,"icon3":"fas fa-blog","count3":"1000","text3":"Blogs","dummy4":null,"icon4":"fas fa-table","count4":"500","text4":"Forums","dummy5":null,"icon5":"fas fa-newspaper","count5":"20000","text5":"Classifieds","nomobile":"0","name":"pulse.landing-page-counter-section"}',
			));

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-cta-section',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"How Our Community Works?","dummy1":null,"icon1":"fa-solid fa-key","heading1":"Effortless Access","description1":"Embark on your journey with us by signing up and logging in to connect with our vibrant community.","link1":"","dummy2":null,"icon2":"fa-solid fa-clapperboard","heading2":"Share your story","description2":"Dive in and share your updates, stories, live streaming, create groups, organize events, participate in polls, and much more, all within one platform.","link2":"","dummy3":null,"icon3":"fa-solid fa-tower-broadcast","heading3":"Go Live with Your Content","description3":"Start broadcasting your content live with your members and share the recording in the feeds or stories to catch up.","link3":"","dummy4":null,"icon4":"fa-solid fa-coins","heading4":"Monetize Your Community","description4":"Turn engagement into revenue with memberships, Verification subscriptions, ads, and built-in monetization tools.","link4":"","nomobile":"0","name":"pulse.landing-page-cta-section"}',
			));

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-service',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Discover Our Features","description":"See what type of features we offer to make launching and managing your SocialEngine community seamless from day one","dummy1":null,"photo1":"","servicesheading1":"Profile Creation","servicesdescription1":"Set up a personalized profile types and member level to showcase your interests and personality ","link1":"","dummy2":null,"photo2":"","servicesheading2":"Messaging","servicesdescription2":"Send instant messages to friends, family & colleagues, encouraging real-time communication","link2":"","dummy3":null,"photo3":"","servicesheading3":"Groups and Communities","servicesdescription3":"Find or create groups by interests. Participate in discussions, events and activities together","link3":"","dummy4":null,"photo4":"","servicesheading4":"Events and Calendar","servicesdescription4":"Stay informed about upcoming events within your network and plan your schedule ahead of time","link4":"","dummy5":null,"photo5":"","servicesheading5":"News And Feed","servicesdescription5":"Receive updates from real-time notifications in a dynamic feed, keeping you connected with the latest activities and content","link5":"","dummy6":null,"photo6":"","servicesheading6":"Classifieds","servicesdescription6":"Buy, sell, or trade goods and services within the community to build a virtual marketplace for members within your community. ","link6":"","nomobile":"0","name":"pulse.landing-page-service"}',
			));

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-blogs',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Our Latest Blogs","nomobile":"0","name":"pulse.landing-page-blogs"}',
			));

			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-app-section',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Stay Connected Anywhere & Everywhere!","description":"Access your community easily on the go with our simple and user-friendly mobile apps.","androidapplink":"#","iosapplink":"#","apprightimage":"","nomobile":"0","name":"pulse.landing-page-app-section"}',
			));
		} else if ($value == 2) {
			$db->insert('engine4_core_content', array(
				'type' => 'widget',
				'name' => 'pulse.landing-page-main',
				'page_id' => 3,
				'parent_content_id' => $mainMiddleId,
				'order' => $widgetOrder++,
				'params' => '{"title":"Welcome to Socialengine","heading":"Share Your World Effortlessly","description":"Experience a modern timeline, powerful groups, expressive profiles, and everything you need to stay connected.","androidapplink":"#","iosapplink":"#","leftphoto":"","logoimage":"","nomobile":"0","name":"pulse.landing-page-main"}',
			));
		}
	}

	public function manageFontsAction()
	{

		$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('pulse_admin_main', array(), 'pulse_admin_main_managefonts');

		$this->view->form = $form = new Pulse_Form_Admin_Settings_Fonts();

		if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {

			$values = $form->getValues();

			$fontArray = array();

			if ($values['pulse_googlefonts']) {

				$googleFontVariants = Engine_Api::_()->core()->getGoogleFonts('variants');

				$fontArray['pulse_body_fontfamily'] = $values['pulse_googlebody_fontfamily'];
				$fontArray['pulse_heading_fontfamily'] = $values['pulse_googleheading_fontfamily'];
				$fontArray['pulse_tab_fontfamily'] = $values['pulse_googletab_fontfamily'];

				$fontArray['pulse_body_fontsize'] = $values['pulse_googlebody_fontsize'];
				$fontArray['pulse_heading_fontsize'] = $values['pulse_googleheading_fontsize'];
				$fontArray['pulse_tab_fontsize'] = $values['pulse_googletab_fontsize'];

				$values['pulse_googlebody_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['pulse_googlebody_fontfamily']]);
				$values['pulse_googleheading_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['pulse_googleheading_fontfamily']]);
				$values['pulse_googletab_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['pulse_googletab_fontfamily']]);
			} else {
				$fontArray['pulse_body_fontfamily'] = $values['pulse_body_fontfamily'];
				$fontArray['pulse_heading_fontfamily'] = $values['pulse_heading_fontfamily'];
				$fontArray['pulse_tab_fontfamily'] = $values['pulse_tab_fontfamily'];

				$fontArray['pulse_body_fontsize'] = $values['pulse_body_fontsize'];
				$fontArray['pulse_heading_fontsize'] = $values['pulse_heading_fontsize'];
				$fontArray['pulse_tab_fontsize'] = $values['pulse_tab_fontsize'];
			}

			foreach ($values as $key => $value) {
				Engine_Api::_()->getApi('settings', 'core')->setSetting($key, $value);
			}

			//Save constant
			$themeConstants = Engine_Api::_()->pulse()->themeConstants(array(), $fontArray);
			Engine_Api::_()->core()->saveThemeVariables($themeConstants, $form, 'pulse');

			$form->addNotice(Zend_Registry::get('Zend_Translate')->_('Your changes have been saved.'));
			$this->_helper->redirector->gotoRoute(array());
		}
	}
}
