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

  protected $_enabledModuleNames;
  
  public function init()
  {
    // Get list of menus
    $menusTable = Engine_Api::_()->getDbtable('menus', 'core');
    $menusSelect = $menusTable->select();
    $this->view->menus = $this->_menus = $menusTable->fetchAll($menusSelect);

    $this->_enabledModuleNames = Engine_Api::_()->getDbtable('modules', 'core')->getEnabledModuleNames();
  }
  
  public function indexAction()
  {
    $this->view->name = $name = $this->_getParam('name', 'core_main');

    // Get list of menus
    $menus = $this->_menus;

    // Check if selected menu is in list
    $selectedMenu = $menus->getRowMatching('name', $name);
    if( null === $selectedMenu ) {
      throw new Core_Model_Exception('Invalid menu name');
    }
    $this->view->selectedMenu = $selectedMenu;

    // Make select options
    $menuList = array();
    foreach( $menus as $menu ) {
      $menuList[$menu->name] = $this->view->translate($menu->title);
    }
    $this->view->menuList = $menuList;
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');

    $menuItemsSelect = $menuItemsTable->select()
    ->where('menu = ?', $name)
    ->order('order');
    if( !empty($this->_enabledModuleNames) ) {
      $menuItemsSelect->where('module IN(?)',  $this->_enabledModuleNames);
    }
    $this->view->menuItems = $menuItems = $menuItemsTable->fetchAll($menuItemsSelect);


    $subMenus = array();
    $subMenuDisabled = array();
    $menusTable = Engine_Api::_()->getDbtable('menus', 'core');
    if($name == "core_main"){
      foreach( $menuItems as $menu ) {
        if($menu->name == "core_main_invite" || $menu->name == "core_main_home" ||  $menu->name == "core_main_chat" || $menu->name == "core_main_invite"){
          $subMenuDisabled[$menu->name] = $menu->name;
          continue;
        }
        if($menu->custom){
          $menuName = $menu->name;
        }else{
          $menuName = $menu->module.'_main';
        }        
        $menuItemsSelect = $menusTable->select()
          ->where('name = ?', $menuName)
          ->limit(1);
          $count = engine_count($menusTable->fetchAll($menuItemsSelect));
        $subMenus[$menu->name]['count'] = $count ? $menuName : false;
        $subMenus[$menu->name]['name'] =  $menuName;
      }
    }
    $this->view->subMenuDisabled = $subMenuDisabled;
    $this->view->subMenus = $subMenus;
    // Get menu items
    
  }
  public function submenuAction()
  {
    // Get form
    $this->view->form = $form = new Core_Form_Admin_Menu_SubmenuCreate();
    $menuName = $this->_getParam("name");


  

    // Check stuff
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }
    // Save
    $values = $form->getValues();

    $menusTable = Engine_Api::_()->getDbtable('menus', 'core');
    
    $menu = $menusTable->createRow();
    $menu->type = 'custom';
    $menu->name = $menuName;
    $menu->title = $values['title'];
    $menu->order = 999;
    $menu->save();


    $label = $values['label'];
    unset($values['label']);
    unset($values['title']);

    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');

    $menuItem = $menuItemsTable->createRow();
    $menuItem->label = $label;
    $menuItem->params = $values;
    $menuItem->menu = $menuName;
    $menuItem->module = 'core'; // Need to do this to prevent it from being hidden
    $menuItem->plugin = '';
    $menuItem->submenu = '';
    $menuItem->custom = 1;
    $menuItem->name = "temrorary";
    $menuItem->save();

    $menuItem->name = 'custom_' . sprintf('%d', $menuItem->id);
    $menuItem->save();

      $this->view->selectedMenu = $menu;


    $this->view->menu = $menu;
    $this->view->status = true;
    $this->view->form = null;
  }

  public function createAction()
  {
    $this->view->name = $name = $this->_getParam('name');

    // Get list of menus
    $menus = $this->_menus;

    // Check if selected menu is in list
    $selectedMenu = $menus->getRowMatching('name', $name);
    if( null === $selectedMenu ) {
      throw new Core_Model_Exception('Invalid menu name');
    }
    $this->view->selectedMenu = $selectedMenu;

    // Get form
    $this->view->form = $form = new Core_Form_Admin_Menu_ItemCreate();

    // Check stuff
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    // Save
    $values = $form->getValues();
    $label = $values['label'];
    unset($values['label']);

    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');

    $menuItem = $menuItemsTable->createRow();
    $menuItem->label = $label;
    $menuItem->params = $values;
    $menuItem->menu = $name;
    $menuItem->module = 'core'; // Need to do this to prevent it from being hidden
    $menuItem->plugin = '';
    $menuItem->submenu = '';
    $menuItem->custom = 1;
    $menuItem->save();

    $menuItem->name = 'custom_' . sprintf('%d', $menuItem->id);
    $menuItem->save();

		
		$menuItem->description = $values['description'] ? $values['description'] : '';
		if (isset($_FILES['photo']) && !empty($_FILES['photo']['name'])) {
			$photoFile = $this->setPhoto($form->photo, $menuItem->id);
			if (!empty($photoFile->file_id)) {
				$previous_file_id = $menuItem->file_id;
				$menuItem->file_id = $photoFile->file_id;
				$file = Engine_Api::_()->getItem('storage_file', $previous_file_id);
				if (!empty($file))
					$file->delete();
			}
		}
		$menuItem->save();

    $this->view->status = true;
    $this->view->form = null;
  }

  public function createMenuAction()
  {
    // Get form
    $this->view->form = $form = new Core_Form_Admin_Menu_MenuCreate();

    // Check stuff
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    // Save
    $values = $form->getValues();

    $menusTable = Engine_Api::_()->getDbtable('menus', 'core');
    
    $menu = $menusTable->createRow();
    $menu->type = 'custom';
    $menu->name = 'custom_temp';
    $menu->title = $values['title'];
    $menu->order = 999;
    $menu->save();

    $menu->name = 'custom_' . sprintf('%d', $menu->id);
    $menu->save();

    $this->view->menu = $menu;
    $this->view->status = true;
    $this->view->form = null;
  }

  public function editAction()
  {
    $this->view->name = $name = $this->_getParam('name');

    // Get menu item
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');
    $menuItemsSelect = $menuItemsTable->select()
      ->where('name = ?', $name);
    if( !empty($this->_enabledModuleNames) ) {
      $menuItemsSelect->where('module IN(?)',  $this->_enabledModuleNames);
    }
    $this->view->menuItem = $menuItem = $menuItemsTable->fetchRow($menuItemsSelect);

    if( !$menuItem ) {
      throw new Core_Model_Exception('missing menu item');
    }

    // Get form
    $this->view->form = $form = new Core_Form_Admin_Menu_ItemEdit();

    // Make safe
    $menuItemData = $menuItem->toArray();
    if( isset($menuItemData['params']) && is_array($menuItemData['params']) ) {
      $menuItemData = array_merge($menuItemData, $menuItemData['params']);
    }
    if( !$menuItem->custom ) {
      $form->removeElement('uri');
    }
    unset($menuItemData['params']);

    // Check stuff
    if( !$this->getRequest()->isPost() ) {
      $form->populate($menuItemData);
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    // Save
    $values = $form->getValues();

    $menuItem->label = $values['label'];
    $menuItem->enabled = !empty($values['enabled']);
    unset($values['label']);
    unset($values['enabled']);


		$menuItem->description = $values['description'] ? $values['description'] : '';
		if (isset($_FILES['photo']) && !empty($_FILES['photo']['name'])) {
			$photoFile = $this->setPhoto($form->photo, $menuItem->id);
			if (!empty($photoFile->file_id)) {
				$previous_file_id = $menuItem->file_id;
				$menuItem->file_id = $photoFile->file_id;
				$file = Engine_Api::_()->getItem('storage_file', $previous_file_id);
				if (!empty($file))
					$file->delete();
			}
		}

		if (isset($values['remove_menu_icon']) && !empty($values['remove_menu_icon'])) {
			$storage = Engine_Api::_()->getItem('storage_file', $menuItem->file_id);
			$menuItem->file_id = 0;
			$menuItem->save();
			if ($storage)
				$storage->delete();
		}

    if( $menuItem->custom ) {
      $menuItem->params = $values;
    }

    $menuItem->params = $this->updateParam($values, 'icon', $menuItem->params);
    $menuItem->params = $this->updateParam($values, 'target', $menuItem->params);

    if( empty($menuItem->params) ) {
      $menuItem->params = '';
    }
    $menuItem->save();

    $this->view->status = true;
    $this->view->form = null;
  }

  public function deleteAction()
  {
    $this->view->name = $name = $this->_getParam('name');

    // Get menu item
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');
    $menuItemsSelect = $menuItemsTable->select()
      ->where('name = ?', $name)
      ->order('order ASC');
    if( !empty($this->_enabledModuleNames) ) {
      $menuItemsSelect->where('module IN(?)',  $this->_enabledModuleNames);
    }
    $this->view->menuItem = $menuItem = $menuItemsTable->fetchRow($menuItemsSelect);

    if( !$menuItem || !$menuItem->custom ) {
      throw new Core_Model_Exception('missing menu item');
    }

    // Get form
    $this->view->form = $form = new Core_Form_Admin_Menu_ItemDelete();
    
    // Check stuff
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    $menuItem->delete();

    $this->view->form = null;
    $this->view->status = true;
  }

  public function deleteMenuAction()
  {
    $menusTable = Engine_Api::_()->getDbtable('menus', 'core');
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');

    if( ($menu_id = $this->_getParam('menu_id')) ) {
      $menu = $menusTable->fetchRow($menusTable->select()
          ->where('menu_id = ?', $menu_id)
          ->where('type = ?', 'custom'));
    } else if( ($menu_name = $this->_getParam('name')) ) {
      $menu = $menusTable->fetchRow($menusTable->select()
          ->where('name = ?', $menu_name)
          ->where('type = ?', 'custom'));
    } else {
      $menu = null;
    }

    if( !$menu ) {
      throw new Core_Model_Exception('missing menu');
    }

    // Make form
    $this->view->form = $form = new Core_Form_Confirm(array(
      'title' => 'Delete Menu?',
      'description' => 'Are you sure you want to delete this menu? Please ' . 
          'make sure you have removed it from any widgets that you have ' .
          'added it to in the layout editor.',
      'submitLabel' => 'Delete Menu',
      'cancelHref' => 'parent.Smoothbox.close()',
    ));

    // Check stuff
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }


    
    // Process
    $menuItemsTable->delete(array(
      'menu = ?' => $menu->name
    ));

    $menu->delete();


    
    $this->view->form = null;
    $this->view->status = true;
  }

  public function orderAction()
  {
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    
    $table = Engine_Api::_()->getDbtable('menuItems', 'core');
    $menuitems = $table->fetchAll($table->select()->where('menu = ?', $this->getRequest()->getParam('menu')));
    foreach( $menuitems as $menuitem ) {
      $order = $this->getRequest()->getParam('admin_menus_item_'.$menuitem->name);
      if( !$order ){
        $order = 999;
      }
      $menuitem->order = $order;
      $menuitem->save();
    }
    return;
  }

  public function updateParam($formValues, $paramName, $params)
  {
    if( !empty($formValues[$paramName]) ) {
      if( !empty($params) ) {
        return $params = array_merge($params, array($paramName => $formValues[$paramName]));
      }
      return array($paramName => $formValues[$paramName]);
    } elseif( isset($params[$paramName]) ) {
      // Remove the $paramName
      $tempParams = array();
      foreach( $params as $key => $item ) {
        if( $key != $paramName ) {
          $tempParams[$key] = $item;
        }
      }
      return $tempParams;
    }
    return $params;
  }

  public function setPhoto($photo, $menuitem_id)
  {
    if ($photo instanceof Zend_Form_Element_File)
      $icon = $photo->getFileName();
    else if (is_array($photo) && !empty($photo['tmp_name']))
      $icon = $photo['tmp_name'];
    else if (is_string($photo) && file_exists($photo))
      $icon = $photo;
    else
      return;

    if (empty($icon))
      return;

    $mainName = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary' . '/' . basename($icon);

    $photo_params = array(
      'parent_id' => $menuitem_id,
      'parent_type' => "core_icons",
    );

    //Resize category icon
    $image = Engine_Image::factory();
    $image->open($icon);

    $size = min($image->height, $image->width);
    $x = ($image->width - $size) / 2;
    $y = ($image->height - $size) / 2;
    $image->open($icon)
      ->resample($x, $y, $size, $size, 48, 48)
      ->write($mainName)
      ->destroy();
    try {
      $photoFile = Engine_Api::_()->storage()->create($mainName, $photo_params);
    } catch (Exception $e) {
      if ($e->getCode() == Storage_Api_Storage::SPACE_LIMIT_REACHED_CODE) {
        echo $e->getMessage();
        exit();
      }
    }
    //Delete temp file.
    @unlink($mainName);
    return $photoFile;
  }

	public function uploadIconsAction() {

		$type = $this->_getParam('type', 'sync');
		$menuname = $this->_getParam('name', 'core_main');

		$PathFile = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . "externals" . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . "dashboard" . DIRECTORY_SEPARATOR;

		if($menuname == 'core_main') {
			$name = 'core_main_';
		} else if($menuname == 'core_footer') {
			$name = 'core_footer_';
			$PathFile .= "footer" . DIRECTORY_SEPARATOR;
		} else if($menuname == 'core_helpsupport_mobile') {
			$name = 'core_helpsupport_mobile_';
			$PathFile .= "footer" . DIRECTORY_SEPARATOR;
		}

		$form = $this->view->form = new Core_Form_Admin_Menu_UploadIcon();
		$title = $type == 'sync' ? 'Restore Missing Menu Images' : 'Restore All Menu Images';
		$button_label = $type == 'sync' ? 'Yes, Restore Images' : 'Yes, Restore Images';
		$description = $type == 'sync' ? 'Are you sure you want to restore missing menu images to default? If Yes, then images will be restored for all menu items which do not have their menu images.' : 'Are you sure you want to restore all the menu images to default? If Yes, then your previously uploaded images will be deleted permanently and cannot be recovered.';
		$form->setTitle($title)->setDescription($description);
		$form->submit->setLabel($button_label);

		if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
			try {
				//Icon work
				if($type == 'sync') {
					$menuItems = Engine_Api::_()->getDbTable('menuItems', 'core')->fetchAll(array('menu = ?' => $menuname, 'file_id = ?' => 0, 'name LIKE ?' => $name . '%'));
				} else {
					$menuItems = Engine_Api::_()->getDbTable('menuItems', 'core')->fetchAll(array('menu = ?' => $menuname, 'name LIKE ?' => $name . '%'));
				}
		
				if (engine_count($menuItems) > 0) {
					foreach($menuItems as $menuItem) {

						if ($type == 'default' && !empty($menuItem->file_id)) {
							$file = Engine_Api::_()->getItem('storage_file', $menuItem->file_id);
							if (!empty($file))
								$file->delete();
							$menuItem->file_id = 0;
							$menuItem->save();
						}

						if($menuname == 'core_main') {
							$file = $PathFile . $menuItem->module . '.png';
						} else if($menuname == 'core_footer') {
							$explode = explode($name, $menuItem->name);
							$file = $PathFile . end($explode) . '.png';
						} else if($menuname == 'core_helpsupport_mobile') {
							$explode = explode($name, $menuItem->name);
							$file = $PathFile . end($explode) . '.png';
						}

						if (file_exists($file)) {
							$file_ext = pathinfo($file);
							$file_ext = $file_ext['extension'];
							$storage = Engine_Api::_()->getItemTable('storage_file');
							$storageObject = $storage->createFile($file, array(
								'parent_id' => $menuItem->id,
								'parent_type' => 'core_menuitem',
								'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
							));
							$menuItem->file_id = $storageObject->file_id;
							$menuItem->save();
						}
					}
				}
				
				$success_message = $type == 'sync' ? 'Missing menu images restored successfully.' : 'All menu images restored successfully.';
				$this->_forward('success', 'utility', 'core', array(
					'smoothboxClose' => 2000,
					'parentRefresh' => 2000,
					'format' => 'smoothbox',
					'messages' => array(Zend_Registry::get('Zend_Translate')->_($success_message)),
				));
			} catch (Exception $e) {
			}
		}
	}
}
