<?php

namespace Modules\Menu\Controllers;

use App\Controllers\Auth\AuthController;
use Modules\Posts\Models\PostsCategoryModel;
use Modules\Posts\Models\PostsModel;
use Modules\Menu\Models\MenusCategoryModel;
use Modules\Menu\Models\MenusModel;


class Menus extends AuthController
{

  public function initController($request, $response, $logger)
  {
    parent::initController($request, $response, $logger);
  }

  public function index()
  {

  }

/**========================================================================
 * MENU TYPES /ADD/EDIT/DELETE
 ==========================================================================*/
 public function menuTypes()
 {

   // display header information
   $this->data['title'] = "Menu Groups";
   $this->data['bcrumb'] = "Menus";

   $this->data['menu_types'] = $this->menuscategoryModel->getAll();

   return view('Modules\Menu\Views\category', $this->data);
 }
 public function addType()
 {
  $this->data['menu_types'] = $this->menuscategoryModel->getAll();
   
    if($this->request->getMethod() == 'POST'){
        $rules = [
          'name' => ['label'=>'Group Name', 'rules'=>'required'],
      ];

      if($this->validate($rules))
      {
          $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('name'))));
          $menuData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
          ];
          
          if($this->menuscategoryModel->save($menuData))
          {
              session()->setTempdata('success', 'Menu Group added successfully', 3);
              return redirect()->to('administrator/menu/groups');
          }else{
              session()->setTempdata('error', 'Menu Group NOT added', 3);
              return redirect()->to('administrator/menu/groups');
          }
      }else{
        session()->setTempdata('error', 'Group Name can not be empty', 3);
        return redirect()->to('Menu Group');
      }
    }
    return view('Modules\Menu\Views\category', $this->data);
 }
 public function editType($id = null)
  {
    $this->data['title'] = "Edit Group";
    $this->data['bcrumb'] = "Edit Group Menu";

    $this->data['menu_types'] = $this->menuscategoryModel->getAll();
    $this->data['singleGroup'] = $this->menuscategoryModel->where('id', $id)->first($id);

    return view('Modules\Menu\Views\category', $this->data);
  }
  public function updateType()
 {
  $this->data['menu_types'] = $this->menuscategoryModel->getAll();
   
    if($this->request->getMethod() == 'POST'){
        $rules = [
          'name' => ['label'=>'Group Name', 'rules'=>'required'],
      ];

      if($this->validate($rules))
      {
          $id = $this->request->getVar("id");
          $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('name'))));
          $menuData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
          ];
          
          if($this->menuscategoryModel->update($id, $menuData))
          {
              session()->setTempdata('success', 'Menu Group updated successfully', 3);
              return redirect()->to('administrator/menu/groups');
          }else{
              session()->setTempdata('error', 'Menu Group NOT updated', 3);
              return redirect()->to('administrator/menu/groups');
          }
      }else{
        session()->setTempdata('error', 'Group Name can not be empty', 3);
        return redirect()->to('Menu Group');
      }
    }
    return view('Modules\Menu\Views\category', $this->data);
 }
 public function delType($id)
  {
    $this->menuscategoryModel->where('id', $id)->delete($id);
    if($this->request->isAJAX())
    {
      $response = [
        'error' => true,
        'msg' =>'Menu Group deleted successfully',	   
      ];
      return $this->response->setJSON($response);
    }else{
      session()->setFlashdata('success', 'Menu Group deleted successfully', 3);
			return redirect()->to('menus');
    }
  }
/**========================================================================
 * MENU ITEMS /ADD/EDIT/DELETE
 ==========================================================================*/
public function viewMenu($id)
{
  $menuGroup = $this->menuscategoryModel->getSingleGroup($id);
  $this->data['title'] =   $menuGroup->name." Items";
  $this->data['bcrumb'] = $menuGroup->name." Items";

  $this->data['post_categories'] = $this->postscategoryModel->getAll();
  $this->data['singleGroup'] = $this->menuscategoryModel->getSingleGroup($id);
  $this->data['menu_items'] = $this->menusModel->getGroupMenu($id);
 
  return view('Modules\Menu\Views\all_menus', $this->data);
}

public function addMenu()
{
  $this->data['title'] = "Add Menu Item";
  $this->data['bcrumb'] = "Add Menu Item";

  // Initialize post_cat & post_id as null
  $post_id = null;
  $post_cat = null;

  $this->data['menuGroups'] = $this->menuscategoryModel->getAll();
  $this->data['menus'] = $this->menusModel->getAll();
  //Get Pages / Categories / Posts
  $this->data['getPages'] = $this->postsModel->getAllPages();
  $this->data['getPosts'] = $this->postsModel->getAllPosts();
  $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();

  if($this->request->getMethod() == 'POST')
  {
    $postId = $this->request->getVar('post_id');
    $pageId = $this->request->getVar('page_id');
    $catId  = $this->request->getVar('post_category');

    //Find the  Page link
    if($pageId){
    $getPage = $this->postsModel->where('id', $pageId)->first($pageId);
    $page_link = $getPage['menu_link'];
    $post_id = $pageId;
    }

    //Find the Post link
    if($postId){
    $getPost = $this->postsModel->where('id', $postId)->first($postId);
    $post_link = $getPost['menu_link'];
    $post_id = $postId;
    }

    // Generate Parent category alias for Menu Link
    if($catId){
      $parent_catId = $this->postscategoryModel->getParentCategory($catId);
      if($parent_catId){
      $parent_catAlias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($parent_catId->name)));
      }

      // Generate Category alias for Menu Link
      $categoryName = $this->postscategoryModel->getSingleCategory($catId); 
      $category_alias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($categoryName->name)));

      //Determining the link for the Category with or without Parent Category
      if(empty($parent_catId)){
        $catLink = $category_alias;
      }else{
        $catLink = $parent_catAlias.'/'.$category_alias;
      }
    }

    //Basing on the menu_type, can determine right menu link to save with Menu.
    $menuType = $this->request->getVar('menu_type');
    if($menuType == "page")
    {
      $link = $page_link;
    }elseif($menuType == "post"){
      $link = $post_link;
    }elseif($menuType == "category"){
      $link = $catLink;
    }else{
      $link = $this->request->getVar('custom');
    }

    //Get Menu Alias
    $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));

    $rules = [
      'title'         => ['label'=>'Menu Title', 'rules'=>'required'],
      'category_id'   => ['label'=>'Menu Category', 'rules'=>'required'],
    ];

    if($this->validate($rules))
    {
      
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        $menuData = [
            'title'         => $this->request->getVar("title"),
            'alias'         => $slug,
            'category_id'   => $this->request->getVar("category_id"),
            'menu_type'     => $this->request->getVar("menu_type"),
            'parent_id'     => $this->request->getVar("parent_id"),
            'ordering'      => $this->request->getVar("ordering"),
            'level'         => $this->request->getVar("level"),
            'access'         => $this->request->getVar("access"),
            'status'         => $this->request->getVar("status"),
            'link'          => $link,
            'post_id'       => $post_id,
            'post_cat'      => $catId,
            'created_by'    => $this->userdata->user_id,
        ];
        
        if($this->menusModel->save($menuData))
        {
            $menuId = $this->menusModel->getInsertID();
            session()->setTempdata('success', 'Menu Item added successfully', 3);
            return redirect()->to('administrator/menu/item/edit/'.$menuId.'-'.$slug);
        }else{
            session()->setTempdata('error', 'Menu Item NOT added', 3);
            return redirect()->to('administrator/menu/item/add');
        }
    }else{
      session()->setTempdata('error', 'Group Name & Category can not be empty', 3);
      return redirect()->to('administrator/menu//item/add');
    }
  }
  
  return view('Modules\Menu\Views\add_menu', $this->data);
}

public function editMenu($item = null)
{
  $menuItem = $this->menusModel->singleMenuItem($item);
  $this->data['title'] = "Edit ".$menuItem->title." Item";
  $this->data['bcrumb'] = "Edit ".$menuItem->title;

  $this->data['menuGroups'] = $this->menuscategoryModel->getAll();
  $this->data['menus'] = $this->menusModel->getAll();
  $this->data['menuItem'] = $this->menusModel->singleMenuItem($item);
  //Get Pages / Categories / Posts
  $this->data['getPages'] = $this->postsModel->getAllPages();
  $this->data['getPosts'] = $this->postsModel->getAllPosts();
  $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();

  return view('Modules\Menu\Views\edit_menu', $this->data);
}
public function updateMenu()
{
  $this->data['title'] = "Add Menu Item";
  $this->data['bcrumb'] = "Add Menu Item";

  // Initialize post_cat & post_id as null
  $post_id = null;
  $post_cat = null;

  $this->data['menuGroups'] = $this->menuscategoryModel->getAll();
  $this->data['menus'] = $this->menusModel->getAll();
  //Get Pages / Categories / Posts
  $this->data['getPages'] = $this->postsModel->getAllPages();
  $this->data['getPosts'] = $this->postsModel->getAllPosts();
  $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();

  if($this->request->getMethod() == 'POST')
  {
    $id = $this->request->getVar('id');
    $postId = $this->request->getVar('post_id');
    $pageId = $this->request->getVar('page_id');
    $catId  = $this->request->getVar('post_category');

    //Find the  Page link
    if($pageId){
      $getPage = $this->postsModel->where('id', $pageId)->first($pageId);
      $page_link = $getPage['menu_link'];
      $post_id = $pageId;
    }
  
    //Find the Post link
    if($postId){
      $getPost = $this->postsModel->where('id', $postId)->first($postId);
      $post_link = $getPost['menu_link'];
      $post_id = $postId;
    }

    // Generate Parent category alias for Menu Link
    if($catId){
      $parent_catId = $this->postscategoryModel->getParentCategory($catId);
      $parent_catAlias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($parent_catId->name)));

      // Generate Category alias for Menu Link
      $categoryName = $this->postscategoryModel->getSingleCategory($catId); 
      $category_alias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($categoryName->name)));

      //Determining the link for the Category with or without Parent Category
      if(empty($parent_catId)){
        $catLink = $category_alias;
      }else{
        $catLink = $parent_catAlias.'/'.$category_alias;
      }
    }

    //Basing on the menu_type, can determine right menu link to save with Menu.
    $menuType = $this->request->getVar('menu_type');
    if($menuType == "page")
    {
      $link = $page_link;
    }elseif($menuType == "post"){
      $link = $post_link;
    }elseif($menuType == "category"){
      $link = $catLink;
    }else{
      $link = $this->request->getVar('custom');
    }

    //Get Menu Alias
    $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));

    $rules = [
      'title'         => ['label'=>'Menu Title', 'rules'=>'required'],
      'category_id'   => ['label'=>'Menu Category', 'rules'=>'required'],
    ];

    if($this->validate($rules))
    {
      
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        $menuData = [
            'title'         => $this->request->getVar("title"),
            'alias'         => $slug,
            'category_id'   => $this->request->getVar("category_id"),
            'menu_type'     => $this->request->getVar("menu_type"),
            'parent_id'     => $this->request->getVar("parent_id"),
            'ordering'      => $this->request->getVar("ordering"),
            'level'         => $this->request->getVar("level"),
            'access'         => $this->request->getVar("access"),
            'status'         => $this->request->getVar("status"),
            'link'          => $link,
            'post_id'       => $post_id,
            'post_cat'      => $catId,
            'created_by'    => $this->userdata->user_id,
        ];
        
        if($this->menusModel->update($id, $menuData))
        {
            $menuId = $this->menusModel->getInsertID();
            session()->setTempdata('success', 'Menu Item Updated successfully', 3);
            return redirect()->to('administrator/menu/item/edit/'.$id.'-'.$slug);
        }else{
            session()->setTempdata('error', 'Menu Item NOT added', 3);
            return redirect()->to('administrator/menu/item/add');
        }
    }else{
      session()->setTempdata('error', 'Group Name & Category can not be empty', 3);
      return redirect()->to('administrator/menu//item/add');
    }
  }
  return view('Modules\Menu\Views\edit_menu', $this->data);
}

public function delMenu($id)
{
    $group = $this->menusModel->singleMenuItem($id);
    $this->menusModel->where('id', $id)->delete($id);
    if($this->request->isAJAX())
    {
      $response = [
        'error' => true,
        'msg' =>'Menu Item deleted successfully',	   
      ];
      return $this->response->setJSON($response);
    }else{
      session()->setTempdata('error', 'Menu Item deleted successfully', 3);
			return redirect()->to('administrator/menu/group/'.$group->category_alias);
    }
}

}
