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

class Inspira_AdminSettingsController extends Core_Controller_Action_Admin {

  public function indexAction() {
  
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('inspira_admin_main', array(), 'inspira_admin_main_settings');

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

    if ($this->getRequest()->isPost() && $form->isValid($this->_getAllParams())) {
    
      $values = $form->getValues();
      
      $changelanding = Engine_Api::_()->getApi('settings', 'core')->getSetting('inspira.changelanding', 0);
      if (isset($values['inspira_changelanding']) && !empty($values['inspira_changelanding']) && $changelanding != $values['inspira_changelanding']) {
        $this->landingpageSet($values['inspira_changelanding']);
      }
      
      if (isset($values['inspira_headernonloggedinoptions']))
        $values['inspira_headernonloggedinoptions'] = serialize($values['inspira_headernonloggedinoptions']);
      else
        $values['inspira_headernonloggedinoptions'] = serialize(array());

      if (isset($values['inspira_headerloggedinoptions']))
        $values['inspira_headerloggedinoptions'] = serialize($values['inspira_headerloggedinoptions']);
      else
        $values['inspira_headerloggedinoptions'] = serialize(array());

      

      foreach ($values as $key => $value) {
        Engine_Api::_()->getApi('settings', 'core')->setSetting($key, $value);
      }
      $form->addNotice('Your changes have been saved.');
    }
  }

  public function stylingAction() {
  
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('inspira_admin_main', array(), 'inspira_admin_main_styling');

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

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

    $this->view->form = $form = new Inspira_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::_()->inspira()->themeConstants($values);
        Engine_Api::_()->core()->saveThemeVariables($themeConstants, $form, 'inspira');
        Engine_Api::_()->getApi('settings', 'core')->setSetting('inspira.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_inspira_customthemes` SET `value` = '".$value."' WHERE `engine4_inspira_customthemes`.`theme_id` = '".$theme_id."' AND  `engine4_inspira_customthemes`.`column_key` = '".$key."';");
          }
        }
      }

      $form->addNotice('Your changes have been saved.');
      $this->_helper->redirector->gotoRoute(array('module' => 'inspira', 'controller' => 'settings', 'action' => 'styling', 'customtheme_id' => $values['theme_color']),'admin_default',true);
    }
    $this->view->activatedTheme = $settings->getSetting('inspira.theme.color', 1);
  }
  
  public function footerAction() {

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

    $this->view->form = $form = new Inspira_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('Your changes have been saved.');
    }
  }
  
  public function addAction() {

    $this->_helper->layout->setLayout('admin-simple');
    
    $customtheme_id = $this->_getParam('customtheme_id', 0);
    
    $this->view->form = $form = new Inspira_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('inspira_customthemes', $customtheme_id);
      $form->populate($customtheme->toArray());
    }
    
    if ($this->getRequest()->isPost()) {
    
      if (!$form->isValid($this->getRequest()->getPost()))
        return;
      
      $table = Engine_Api::_()->getDbtable('customthemes', 'inspira');
      
      $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_inspira_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_inspira_customthemes` SET `value` = '" . $theme_id . "' WHERE theme_id = " . $theme_id . " AND column_key = 'custom_theme_color';");
                $db->query('DELETE FROM `engine4_inspira_customthemes` WHERE `engine4_inspira_customthemes`.`theme_id` = "0";');
            }
        } else if(!empty($customtheme_id)) {
          $theme_id = $customtheme_id = $customtheme_id - 1;
          $db->query("UPDATE `engine4_inspira_customthemes` SET `name` = '" . $values['name'] . "' WHERE theme_id = " . $customtheme_id);
        }
        $db->commit();
        if(!$customtheme_id) {
          $message = array('New Custom theme created successfully.');
        } else {
          $message = array('New Custom theme edited successfully.');
        }
        return $this->_forward('success', 'utility', 'core', array(
          'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('module' => 'inspira', '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_inspira_customthemes WHERE theme_id = ".$customtheme_id);
        $db->commit();
        $activatedTheme = Engine_Api::_()->getApi('settings', 'core')->getSetting('inspira.theme.color', 1);
        $this->_forward('success', 'utility', 'core', array(
          'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('module' => 'inspira', 'controller' => 'settings', 'action' => 'styling', 'customtheme_id' => $activatedTheme),'admin_default',true),
          'messages' => array('You have successfully delete 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', 'inspira')->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 = "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";');

    
    // Insert top
    $db->insert('engine4_core_content', array(
        'type' => 'container',
        'name' => 'top',
        'page_id' => 3,
        'order' => 1,
    ));
    $topId = $db->lastInsertId();
            
    $db->insert('engine4_core_content', array(
        'type' => 'container',
        'name' => 'main',
        'page_id' => 3,
        'order' => 2,
    ));
    $mainId = $db->lastInsertId();
    // Insert top-middle
    $db->insert('engine4_core_content', array(
        'type' => 'container',
        'name' => 'middle',
        'page_id' => 3,
        'parent_content_id' => $topId,
    ));
    $topMiddleId = $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' => 'inspira.landing-page-header',
        'page_id' => 3,
        'parent_content_id' => $topMiddleId,
        'order' => $widgetOrder++,
      ));
      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-banner',
        'page_id' => 3,
        'parent_content_id' => $topMiddleId,
        'order' => $widgetOrder++,
        'params' => '{"heading":"Explore the world with us","description1":"Share your Photos and let them talk for you.","description2":"Music & Videos in the Community.","description3":"Create and join interesting events.","description4":"Write new Blogs and share your thoughts.","title":"","nomobile":"0","name":"inspira.landing-page-banner", "backgroundcolor":"1790bd"}',
      ));

      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-features',
        'page_id' => 3,
        'parent_content_id' => $mainMiddleId,
        'order' => $widgetOrder++,
        'params' => '{"description":"Without a proper sense of caring, there can be no sense of community. We treasure the relationships here & not the possessions.","dummy1":null,"heading1":"Photos & Albums","description1":"Share your stories with photos & let your photos do the talking for you.","icon1":"far fa-image","dummy2":null,"heading2":"Forum","description2":"Have in-depth discussions and debates to increase interaction in your community.","icon2":"fas fa-comments","dummy3":null,"heading3":"Music Albums & Songs","description3":"What do you want to listen to? Find some awesome collections.","icon3":"fas fa-music","dummy4":null,"heading4":"Video Sharing","description4":"We make videos worth watching. Upload videos & share with the whole world.","icon4":"fas fa-video","dummy5":null,"heading5":"Events","description5":"Create, promote and host your meetings, conferences, special events and more!","icon5":"fas fa-calendar-alt","dummy6":null,"heading6":"Discover New Groups","description6":"Join groups based on your interest and get connected with the world.","icon6":"fas fa-users","rightsideimage":"","rightsideurl":"","title":"Why Choose Us?","nomobile":"0","name":"inspira.landing-page-features"}', 
      ));
      
      if(Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('album')) {
        $db->insert('engine4_core_content', array(
          'type' => 'widget',
          'name' => 'inspira.landing-page-albums',
          'page_id' => 3,
          'parent_content_id' => $mainMiddleId,
          'order' => $widgetOrder++, 
          'params' => '{"title":"Popular Albums","popularType":"comment","description":"These amazing photos are generating the most interest in our community.","nomobile":"0","name":"inspira.landing-page-albums"}',
        ));
      }
      if(Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('group')) {
        $db->insert('engine4_core_content', array(
          'type' => 'widget',
          'name' => 'inspira.landing-page-groups',
          'page_id' => 3,
          'parent_content_id' => $mainMiddleId,
          'order' => $widgetOrder++, 
          'params' => '{"title":"Popular Groups","popularType":"view","description":"The most active groups that inspire our community. Join or create one today!","nomobile":"0","name":"inspira.landing-page-groups"}',
        ));
      }
      if(Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('event')) {
        $db->insert('engine4_core_content', array(
          'type' => 'widget',
          'name' => 'inspira.landing-page-events',
          'page_id' => 3,
          'parent_content_id' => $mainMiddleId,
          'order' => $widgetOrder++, 
          'params' => '{"title":"Popular Events","description":"Events that have the most community members joining them. Find one that interests you!","popularType":"member","nomobile":"0","name":"inspira.landing-page-events"}',
        ));
      }
      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-service',
        'page_id' => 3,
        'parent_content_id' => $mainMiddleId,
        'order' => $widgetOrder++, 
        'params' => '{"description":"Here are some of the wonderful features of our community. Join today to be a part of something great!","dummy1":null,"heading1":"Flexible","description1":"Our community is available 24x7. This allows you to use it per your own schedule. Holidays, weekdays, weekends - any time, any place!\r\n","icon1":"fas fa-recycle","dummy2":null,"heading2":"Lifetime Free","description2":"Our general membership is free for life. We also have paid memberships that have more features and can be subscribed to at any time.","icon2":"fas fa-coins","dummy3":null,"heading3":"Responsive","description3":"Our community is 100% responsive. Use it anywhere, and anytime from your laptop, mobile or any other device.\r\n","icon3":"fas fa-mobile-alt","dummy4":null,"heading4":"Directories","description4":"If you are a business owner, or have any directory to highlight you can easily do so in the Business Listings.\r\n","icon4":"fas fa-sitemap","dummy5":null,"heading5":"Groups","description5":"Create your own groups or join existing groups to connect with people who share your interests.\r\n","icon5":"fas fa-users","dummy6":null,"heading6":"Secure","description6":"Our website is secure and provides secure passwords and privacy settings to keep you safe.\r\n","icon6":"fas fa-shield-alt","dummy7":null,"heading7":"Online Store","description7":"We have a store where you can list your own products for sale, list services you offer, or even list items you want to donate to others.\r\n","icon7":"fas fa-cart-arrow-down","dummy8":null,"heading8":"Easy to Use","description8":"Our community is user friendly and easy to use. We have FAQs, tutorials, and a forum for questions should you need any help.\r\n","icon8":"fas fa-thumbs-up","title":"Our Features","nomobile":"0","name":"inspira.landing-page-service"}',
      ));
      
      if(Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('music')) {
        $db->insert('engine4_core_content', array(
          'type' => 'widget',
          'name' => 'inspira.landing-page-music',
          'page_id' => 3,
          'parent_content_id' => $mainMiddleId,
          'order' => $widgetOrder++, 
          'params' => '{"title":"Popular Music","description":"Our members\' favorite music! You can add these songs to your playlist too!","popularType":"view","nomobile":"0","name":"inspira.landing-page-music"}',
        ));
      }
      
      if(Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('video')) {
        $db->insert('engine4_core_content', array(
          'type' => 'widget',
          'name' => 'inspira.landing-page-videos',
          'page_id' => 3,
          'parent_content_id' => $mainMiddleId,
          'order' => $widgetOrder++, 
          'params' => '{"title":"Popular Videos","description":"The most popular videos that our members are watching today. Enjoy!","popularType":"view","nomobile":"0","name":"inspira.landing-page-videos"}',
        ));
      }
      if(Engine_Api::_()->getDbTable('modules', 'core')->isModuleEnabled('blog')) {
        $db->insert('engine4_core_content', array(
          'type' => 'widget',
          'name' => 'inspira.landing-page-blogs',
          'page_id' => 3,
          'parent_content_id' => $mainMiddleId,
          'order' => $widgetOrder++,
          'params' => '{"title":"Explore Popular Blogs","description":"Read the blogs that our members find inspiring!","popularType":"view","nomobile":"0","name":"inspira.landing-page-blogs"}', 
        ));
      }
      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-counter',
        'page_id' => 3,
        'parent_content_id' => $mainMiddleId,
        'order' => $widgetOrder++,
        'params' => '{"heading":"You\'ll Find Many Reasons to Join Us","description":"We\'ve worked hard to make our community a safe, fun and secure place for you to spend your time. ","backgroundimage":"","rightmage":"","counter1":"800","counter1text":"Members","counter2":"650","counter2text":"Groups","counter3":"350","counter3text":"Blogs","counter4":"200","counter4text":"Videos","title":"","nomobile":"0","name":"inspira.landing-page-counter"}',
      ));
      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-members',
        'page_id' => 3,
        'parent_content_id' => $mainMiddleId,
        'order' => $widgetOrder++,
        'params' => '{"popularType":"view","title":"Popular Members","nomobile":"0","name":"inspira.landing-page-members"}',
      ));
      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-app',
        'page_id' => 3,
        'parent_content_id' => $mainMiddleId,
        'order' => $widgetOrder++,
        'params' => '{"heading":"Download Our Free Mobile App today!","description":"Our free Google or Apple mobile apps give you an easy way to connect to our community from your iOS or Android device.","androidapplink":"https://play.google.com/store/apps/details?id=com.snscore.app","iosapplink":"https://apps.apple.com/us/app/socialengine-basic-app-sns/id1495756498?ls=1","title":"","nomobile":"0","name":"inspira.landing-page-app"}',
      ));
    } else if($value == 2) {
      $db->insert('engine4_core_content', array(
        'type' => 'widget',
        'name' => 'inspira.landing-page-main',
        'page_id' => 3,
        'parent_content_id' => $mainMiddleId,
        'order' => $widgetOrder++,
        'params' => '{"title":"","name":"inspira.landing-page-main","description":"Explore what\'s going on in the world!","image":"","nomobile":"0"}',
      ));
    }
  }

  public function manageFontsAction() {

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

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

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

      $values = $form->getValues();
      
      $fontArray = array();

      if($values['inspira_googlefonts']) {

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

        $fontArray['inspira_body_fontfamily'] = $values['inspira_googlebody_fontfamily'];
        $fontArray['inspira_heading_fontfamily'] = $values['inspira_googleheading_fontfamily'];
        $fontArray['inspira_mainmenu_fontfamily'] = $values['inspira_googlemainmenu_fontfamily'];
        $fontArray['inspira_tab_fontfamily'] = $values['inspira_googletab_fontfamily'];

        $values['inspira_googlebody_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['inspira_googlebody_fontfamily']]);
        $values['inspira_googleheading_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['inspira_googleheading_fontfamily']]);
        $values['inspira_googlemainmenu_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['inspira_googlemainmenu_fontfamily']]);
        $values['inspira_googletab_fontfamilyvariants'] = implode(",", $googleFontVariants[$values['inspira_googletab_fontfamily']]);
      } else {
        $fontArray['inspira_body_fontfamily'] = $values['inspira_body_fontfamily'];
        $fontArray['inspira_heading_fontfamily'] = $values['inspira_heading_fontfamily'];
        $fontArray['inspira_mainmenu_fontfamily'] = $values['inspira_mainmenu_fontfamily'];
        $fontArray['inspira_tab_fontfamily'] = $values['inspira_tab_fontfamily'];
      }

      foreach ($values as $key => $value) {
        Engine_Api::_()->getApi('settings', 'core')->setSetting($key, $value);
      }
      
      //Save constant
      $themeConstants = Engine_Api::_()->inspira()->themeConstants(array(), $fontArray);
      Engine_Api::_()->core()->saveThemeVariables($themeConstants, $form, 'inspira');

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