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

  public function indexAction() {

    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('poke_admin_main', array(), 'poke_admin_main_manageactions');
    
    $this->view->formFilter = $formFilter = new Poke_Form_Admin_Manageactions_Filter();
    
    // Process form
    $values = array();
    if ($this->getRequest()->isPost()) {
      $values = $this->getRequest()->getPost();
      foreach ($values['selectedItems'] as $value) {
				if(!empty($value)) {
					$pokeManageaction = Engine_Api::_()->getItem('poke_manageaction', $value);
					if($_POST['enable'] == 'enable') {
						$pokeManageaction->enabled = 1;
						$pokeManageaction->save();
					} else if($_POST['disable'] == 'disable') {
						$pokeManageaction->enabled = 0;
						$pokeManageaction->save();
					} else if($_POST['delete'] == 'delete') {
						$pokeManageaction->delete();
					}
				}
      }
    }
    
    // Process form
    if( $formFilter->isValid($this->_getAllParams()) ) {
      $values = $formFilter->getValues();
    }

    foreach( $values as $key => $value ) {
      if( null === $value ) {
        unset($values[$key]);
      }
    }

    $values = array_merge(array(
      'order' => 'manageaction_id',
      'order_direction' => 'DESC',
    ), $values);
    
    $this->view->assign($values);
    
    $table = Engine_Api::_()->getDbtable('manageactions', 'poke');
    $tableName = $table->info('name');

    $select = $table->select()
            ->setIntegrityCheck(false)
            ->from($tableName);
    
    if(!empty($_GET['manageactionid']))
      $select->where($tableName . ".manageaction_id = ?", $_GET['manageactionid']);
      
    if (!empty($_GET['name']))
      $select->where($tableName . ".name LIKE ?", $_GET['name'] . '%');
      
    if( isset($_GET['enabled']) && $_GET['enabled'] != -1 ) {
      $select->where($tableName.'.enabled = ?', $_GET['enabled'] );
    }
		
    $select->order($tableName.'.order ASC');

    // Filter out junk
    $valuesCopy = array_filter($values);

    // Make paginator
    $this->view->paginator = $paginator = Zend_Paginator::factory($select);
    $paginator->setItemCountPerPage(10);
    $paginator->setCurrentPageNumber( $this->_getParam('page', 1) );
    
    $this->view->page = $valuesCopy['page'] = $this->_getParam('page', 1);
    $this->view->formValues = $valuesCopy;
  }

  public function addAction() {

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

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

    $this->view->manageModules = Engine_Api::_()->getItem('poke_manageaction', $this->_getParam('manageaction_id'));

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

      $values = $form->getValues();

      if (empty($values['icon'])) {
        $error = Zend_Registry::get('Zend_Translate')->_("Icon is requried field. Please choose a icon for this.");
        $form->getDecorator('errors')->setOption('escape', false);
        $form->addError($error);
        return;
      }
      
      $manageactionsTable = Engine_Api::_()->getDbtable('manageactions', 'poke');

      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();
      try {
        $row = $manageactionsTable->createRow();

        $row->setFromArray($values);
        $row->save();
        $manageaction_id = $row->manageaction_id;
        $row->order = $manageaction_id;
        $row->save();
				$row->slug = $row->getSlug();
        $row->save();

        $name = strtolower(str_replace(' ', '_', $values['name']));
        if (isset($values)) {
          $customCSV = APPLICATION_PATH . '/application/languages/en/custom.csv';
          if (file_exists($customCSV)) {
            $name = strtoupper($name);
            $translaterWriter = new Engine_Translate_Writer_Csv($customCSV);
            $translaterWriter->setTranslations(array(
              $values['name'] => $values['name'],
            ));
            $translaterWriter->write();
            Zend_Registry::get('Zend_Cache')->clean();
          }
        }

        $db->commit();
      } catch (Exception $e) {
        $db->rollBack();
        throw $e;
      }
      return $this->_helper->redirector->gotoRoute(array('action' => 'index'));
    }
  }

  //Edit entry
  public function editAction() {

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

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

    $manageaction_id = $this->_getParam('manageaction_id');
    $this->view->manageAction = $manageAction = Engine_Api::_()->getItem('poke_manageaction', $manageaction_id);
    $previousName = strtolower($manageAction->name);

    //Populate the from
    $form->populate($manageAction->toArray());
    $form->setTitle('Edit Action');
    $form->setDescription('Below, you can edit actions to send Poke, Slap, Wink, Heart, Cake, Beer, Coffee, etc.');
    $form->execute->setLabel('Save Changes');

    if (!$this->getRequest()->isPost())
      return;

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

    $values = $form->getValues();
    if (empty($values['icon']))
      unset($values['icon']);

    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try {
      $manageAction->setFromArray($values);
      $manageAction->save();
      $db->commit();
    } catch (Exception $e) {
      $db->rollBack();
      throw $e;
    }
    return $this->_helper->redirector->gotoRoute(array('action' => 'index'));
  }

  //Delete entry
  public function deleteAction() {

    $this->_helper->layout->setLayout('admin-simple');
    $manageaction_id = $this->_getParam('manageaction_id');
    $manageAction = Engine_Api::_()->getItem('poke_manageaction', $manageaction_id);
    $name = strtolower(str_replace(' ', '_', $manageAction->name));
    if ($this->getRequest()->isPost()) {
      $db = Engine_Db_Table::getDefaultAdapter();
      $db->beginTransaction();
      try {
        $db->query("DELETE FROM `engine4_poke_pokes` WHERE `engine4_poke_pokes`.`manageaction_id` = $manageaction_id;");
        $manageAction->delete();

        $db->commit();
      } catch (Exception $e) {
        $db->rollBack();
        throw $e;
      }

      return $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => 10,
        'parentRefresh' => 10,
        'messages' => array('You have successfully delete entry.')
      ));
    }
    $this->renderScript('admin-manageactions/delete.tpl');
  }

  //Enable / Disable Action
  public function enabledAction() {

    $param = $this->_getParam('param', null);
    $manageaction_id = $this->_getParam('manageaction_id', null);

    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    $content = Engine_Api::_()->getItemTable('poke_manageaction')->fetchRow(array('manageaction_id = ?' => $manageaction_id));
    try {
      $content->enabled = !$content->enabled;
      $content->save();

      $db->commit();
    } catch (Exception $e) {
      $db->rollBack();
      throw $e;
    }

    return $this->_helper->redirector->gotoRoute(array('action' => 'index', 'page' => $this->_getParam('page', 1)));
  }
  
  public function orderAction() {
    $table = Engine_Api::_()->getDbTable('manageactions', 'poke');
    $results = $table->fetchAll($table->select());
    $orders = $this->getRequest()->getParam('order');
    foreach ($results as $result) {
      $key = array_search ('order_'.$result->getIdentity(), $orders);
      $result->order = $key+1;
      $result->save();
    }
    return;
  }
}
