<?php

namespace Modules\Posts\Controllers;

use App\Controllers\Auth\AuthController;


class Posts extends AuthController
{

  public function initController($request, $response, $logger)
  {
    parent::initController($request, $response, $logger);
    $this->data['categoryTree']         = $this->postscategoryModel->getCategoryList();
  }

  public function index()
  {		
    // display header information
		$this->data['title'] = "Posts";
    $this->data['bcrumb'] = "Posts";

    if($this->userdata->group_id == 1 || $this->userdata->group_id == 2 ){
    $this->data['posts'] = $this->postsModel->getAllPosts();
    }else{
    $this->data['posts'] = $this->postsModel->getAllEditorPosts();
    }
		return view('Modules\Posts\Views\all_posts', $this->data);
  }

  // Generate a menu link for a post
  public function generateMenuLink($categoryId, $parentCategoryId, $title)
  {
      $menuLink = $categoryId;

      if (!empty($parentCategoryId)) {
        $menuLink =  $parentCategoryId. '/' .$menuLink; // Append the parent category ID
      }

      // Append the slug to the menu link
      $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($title)));
      $menuLink .= '/' . $slug;

      return $menuLink;
  }



/**========================================================================
 * POSTS /ADD/EDIT/DELETE
 ==========================================================================*/
  public function addPost()
  {
    $this->data['title'] = "Add Post";
    $this->data['bcrumb'] = "Add Post";

    $admins = $this->usersModel->getAdminUsers();

    $this->data['tags'] = $this->tagsModel->getAll();
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->postscategoryModel->getOtherCategories();
    $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();

    if($this->request->getMethod() == 'POST'){

      //Getting Published Date for Post
      $pdate = $this->request->getVar('pdate');
      $ptime = $this->request->getVar('ptime');

      if($pdate){
        $publishedDate = $pdate.' '.$ptime;
      }else{
        $publishedDate = date('Y-m-d H:i:s');
      }

      // Generate Sub category alias for Menu Link
      $categoryId = $this->request->getVar("category_id");
      $categoryName = $this->postscategoryModel->getSingleCategory($categoryId); 
      $subCategory = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($categoryName->name)));
      $alias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar("title"))));

      $title = $this->request->getVar("title");

      // Generate Parent category alias for Menu Link
      $parentId = $this->postscategoryModel->getParentCategory($categoryId);

      if(empty($parentId)){
        $menuLink = $subCategory.'/'.$alias;
      }else{
        $parentCategoryId = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($parentId->name)));
        $menuLink = $this->generateMenuLink($subCategory, $parentCategoryId, $title);
      }
      
      $rules = [
        'title' => ['label'=>'Post Title', 'rules'=>'required'],
      ];
      $photoRules = [
        'photo' => [
            'label' => 'Image File',
            'rules' => 'uploaded[photo]'
                . '|is_image[photo]'
                . '|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                . '|max_size[photo,2024]'
        ],
    ];
      if($this->validate($rules))
      {
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));

        // Append the slug to the menu link
        $file1 = $this->request->getFile('photo');
        if($file1 != "")
        {
            if($this->validate($photoRules))
            { 
                $newName4 = $file1->getRandomName();
                $file1->move(ROOTPATH . 'media/posts', $newName4);
                $nwn1 = base_url('/media/posts/').$newName4;

                $postData = [
                  'title'           => $this->request->getVar("title"),
                  'alias'           => $slug,
                  'photo'           => $nwn1,
                  'menu_link'       => $menuLink,
                  'content'         => $this->request->getVar("content"),
                  'excerpt'         => $this->request->getVar("excerpt"), 
                  'category_id'     => $this->request->getVar("category_id"),
                  'author_id'       => $this->request->getVar("author_id"), 
                  'status'          => $this->request->getVar("status"), 
                  'access'          => $this->request->getVar("access"),
                  'published_date'  => $publishedDate, 
                  'metadesc'        => $this->request->getVar("metadesc"),
                  'metakey'         => $this->request->getVar("metakey"),
                  'created_by'      => $this->userdata->user_id,
              ];
              $results = $this->postsModel->save($postData);

            }else{
              $this->data['validation'] = $this->validator;
            }
        }else{

          $postData = [
            'title'          => $this->request->getVar("title"),
            'alias'          => $slug,
            'menu_link'       => $menuLink,
            'content'         => $this->request->getVar("content"),
            'excerpt'         => $this->request->getVar("excerpt"), 
            'category_id'     => $this->request->getVar("category_id"),
            'author_id'       => $this->request->getVar("author_id"), 
            'status'          => $this->request->getVar("status"), 
            'access'          => $this->request->getVar("access"),
            'published_date'  => $publishedDate,
            'metadesc'        => $this->request->getVar("metadesc"),
            'metakey'         => $this->request->getVar("metakey"),
            'created_by'      => $this->userdata->user_id,
            ];
          
          $results = $this->postsModel->save($postData);
        }
        
        if($results)
        {
          $postId = $this->postsModel->getInsertID();
          // Save Tags attached to the Post
          $tags = $this->request->getVar('tags');
          if($tags){
            foreach ($tags as $tag) {
              $tagPostData = [
                  'tag_id' => $tag,
                  'post_id' => $postId
              ];
              $this->posttagsModel->save($tagPostData);
            } 
          }
          
          //Save & Send Notification
          $title = $this->request->getVar("title");
          $adminmessage = 'New Post:  <strong>'.$title.'</strong> has been created successfully';
          $notificationType = 'posts';
          $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

          session()->setTempdata('success', 'Post added successfully', 3);
          return redirect()->to('administrator/posts');
      }else{
          session()->setTempdata('error', 'Post NOT added', 3);
          return redirect()->to('administrator/posts/add');
      }
          
      }else{
        session()->setTempdata('error', 'Post Title can not be empty', 3);
        return redirect()->to('administrator/posts/add');
      }
    }

    return view('Modules\Posts\Views\add_post', $this->data);
  }
  public function editPost($id = null)
  {
    $this->data['title'] = "Edit Post";
    $this->data['bcrumb'] = "Edit Post";

    $this->data['authors']      = $this->usersModel->getAll();
    $this->data['categories']   =$this->postscategoryModel->getAll();
    $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();
    $this->data['postTags'] = $this->posttagsModel->getPostTags($id);
    $singlePost   = $this->postsModel->where('id', $id)->orWhere('alias', $id)->first($id);

    $this->data['singlePost'] = $singlePost;
    return view('Modules\Posts\Views\edit_post', $this->data);
  }
  public function updatePost()
  {
    $this->data['title'] = "Edit Post";
    $this->data['bcrumb'] = "Edit Post";

    $admins = $this->usersModel->getAdminUsers();
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->postscategoryModel->getOtherCategories();

    if($this->request->getMethod() == 'POST'){
      //Getting Published Date for Post
      $pdate = $this->request->getVar('pdate');
      $ptime = $this->request->getVar('ptime');

      if($pdate){
        $publishedDate = $pdate.' '.$ptime;
        var_dump($publishedDate);
      }else{
        $publishedDate = date('Y-m-d H:i:s');
      }

      // Generate Sub category alias for Menu Link
      $categoryId = $this->request->getVar("category_id");
      $categoryName = $this->postscategoryModel->getSingleCategory($categoryId); 
      $subCategory = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($categoryName->name)));
      $alias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar("title"))));

      $title = $this->request->getVar("title");
      // Generate Parent category alias for Menu Link
      $parentId = $this->postscategoryModel->getParentCategory($categoryId);

      //$parentCategoryId = null;
      if(empty($parentId)){
        $menuLink = $subCategory.'/'.$alias;
      }else{
        
        $parentCategoryId = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($parentId->name)));
        $menuLink = $this->generateMenuLink($subCategory, $parentCategoryId, $title);
      }

      $rules = [
        'title' => ['label'=>'Post Title', 'rules'=>'required'],
      ];
      $photoRules = [
        'photo' => [
            'label' => 'Image File',
            'rules' => 'uploaded[photo]'
                . '|is_image[photo]'
                . '|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                . '|max_size[photo,2024]'
        ],
    ];
      if($this->validate($rules))
      {
        $id = $this->request->getVar('id');
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        $file1 = $this->request->getFile('photo');
        if($file1 != "")
        {
            if($this->validate($photoRules))
            { 
                $newName4 = $file1->getRandomName();
                $file1->move(ROOTPATH . 'media/posts', $newName4);
                $nwn1 = base_url('/media/posts/').$newName4;

                $postData = [
                  'title'          => $this->request->getVar("title"),
                  'alias'          => $slug,
                  'photo'           =>$nwn1,
                  'menu_link'       => $menuLink,
                  'content'         => $this->request->getVar("content"),
                  'excerpt'         => $this->request->getVar("excerpt"), 
                  'category_id'     => $this->request->getVar("category_id"),
                  'author_id'       => $this->request->getVar("author_id"), 
                  'status'          => $this->request->getVar("status"), 
                  'access'          => $this->request->getVar("access"),
                  'published_date'  => $publishedDate,
                  'metadesc'        => $this->request->getVar("metadesc"),
                  'metakey'         => $this->request->getVar("metakey"),
                  'updated_by'      => $this->userdata->user_id,
                  'updated_at'      => date('Y-m-d H:i:s'),
              ];
              $results = $this->postsModel->update($id, $postData);

            }else{
              $this->data['validation'] = $this->validator;
            }
        }else{

          $postData = [
            'title'          => $this->request->getVar("title"),
            'alias'          => $slug,
            'menu_link'       => $menuLink,
            'content'         => $this->request->getVar("content"),
            'excerpt'         => $this->request->getVar("excerpt"), 
            'category_id'     => $this->request->getVar("category_id"),
            'author_id'       => $this->request->getVar("author_id"), 
            'status'          => $this->request->getVar("status"), 
            'access'          => $this->request->getVar("access"),
            'published_date'  => $publishedDate,
            'metadesc'        => $this->request->getVar("metadesc"),
            'metakey'         => $this->request->getVar("metakey"),
            'updated_by'      => $this->userdata->user_id,
            'updated_at'      => date('Y-m-d H:i:s'),
            ];
          
          $results = $this->postsModel->update($id, $postData);
        }
        
        if($results)
        {
          
          // Save Tags attached to the Post
          $tags = $this->request->getVar('tags');
          if($tags){
            foreach ($tags as $tag) {
              $tagPostData = [
                  'tag_id' => $tag,
                  'post_id' => $id
              ];
              $this->posttagsModel->save($tagPostData);
            } 
          }

          //Save & Send Notification
          $title = $this->request->getVar("title");
          $adminmessage = 'New Post:  <strong>'.$title.'</strong> has been UPDATED successfully';
          $notificationType = 'posts';
          $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

          session()->setTempdata('success', 'Post updated successfully', 3);
          return redirect()->to('administrator/posts');
      }else{
          session()->setTempdata('error', 'Post NOT added', 3);
          return redirect()->to('administrator/posts/edit/'.$id);
      }
          
      }else{
        session()->setTempdata('error', 'Post Title can not be empty', 3);
        return redirect()->to('administrator/posts/edit/'.$id);
      }
    }
    return view('Modules\Posts\Views\edit_post', $this->data);
  }
  public function viewPost($id = null)
  {
    $page = $this->postsModel->getSinglePost($id);
    $this->data['title'] = $page->title." Page";
    $this->data['bcrumb'] = $page->title." Page";

    //Getting Hits & Saving them.
    $current_hits = $page->hits;
    $new_hits = $current_hits + 1;
    $this->postsModel->update($id, ['hits'=>$new_hits]);

    //Getting Hits & Saving them.
    $current_hits = $page->hits;
    $new_hits = $current_hits + 1;
    $this->postsModel->update($id, ['hits'=>$new_hits]);

    //Get User Unique Views/Visits - basing on session ID
    $user_ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $user_identifier = session()->get('logged_user');

    $userExists = $this->authloginModel->checkUserExists($user_ip, $user_identifier);
    $current_views = $page->views;

    if ($userExists) {
        $unique_views = $current_views + 1;
        $this->postsModel->update($id, ['views' => $unique_views]);
    }

    $this->data['comments'] = $this->postcommentsModel->getPostComments($id);
    $this->data['postTags'] = $this->posttagsModel->getPostTags($id);
    $this->data['singlePost'] = $this->postsModel->getSinglePost($id);
   

    return view('Modules\Posts\Views\view_post', $this->data);
  }
  public function delPost($id)
  {
    if($this->userdata->group_id != 1)
    {
      session()->setFlashdata('warning', 'Access denied');
      return redirect()->to(previous_url());
    }
    $admins = $this->usersModel->getAdminUsers();
    $article = $this->postsModel->where('id', $id)->first($id);

    $this->postsModel->where('id', $id)->delete($id);
    if($this->request->isAJAX())
    {
      
      $response = [
        'error' => true,
        'msg' =>'Post deleted successfully',	   
      ];
      return $this->response->setJSON($response);
    }else{
      //Save & Send Notification
      $title = $article['title'];
      $adminmessage = 'New Post:  <strong>'.$title.'</strong> has been DELETED successfully';
      $notificationType = 'posts';
      $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

      session()->setFlashdata('success', 'Post deleted successfully', 3);
			return redirect()->to('administrator/posts');
    }
  }



/**========================================================================
 * BLOCK POST /ADD/EDIT/DELETE
 ==========================================================================*/

 public function viewBlockPosts()
 {		
   // display header information
   $this->data['title'] = "Posts";
   $this->data['bcrumb'] = "Posts";

    if($this->userdata->group_id == 1 || $this->userdata->group_id == 2){
        $this->data['posts'] = $this->postsModel->getAllBlockPosts();
    }else{
        $this->data['posts'] = $this->postsModel->getAllEditorBlockPosts();
    }

   return view('Modules\Posts\Views\block-post\all_blockposts', $this->data);
 }

public function addBlockPost()
{
  // display header information
  $this->data['title'] = "Add Block Post";
  $this->data['bcrumb'] = "Add Block Post";

  $this->data['tags'] = $this->tagsModel->getAll();
  $this->data['authors'] = $this->usersModel->getAll();
  $this->data['categories']=$this->postscategoryModel->getOtherCategories();
  $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();

  if($this->request->getMethod() == 'POST')
  {

    //Getting Published Date for Post
    $pdate = $this->request->getVar('pdate');
    $ptime = $this->request->getVar('ptime');
    if($pdate){
      $publishedDate = $pdate.' '.$ptime;
    }else{
      $publishedDate = date('Y-m-d H:i:s');
    }

    // Generate Sub category alias for Menu Link
    $title = $this->request->getVar("title");
    $categoryId = $this->request->getVar("category_id");
    $categoryName = $this->postscategoryModel->getSingleCategory($categoryId); 
    $subCategory = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($categoryName->name)));
    $alias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar("title"))));
    $parentId = $this->postscategoryModel->getParentCategory($categoryId);

    if(empty($parentId)){
      $menuLink = $subCategory.'/'.$alias;
    }else{
      $parentCategoryId = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($parentId->name)));
      $menuLink = $this->generateMenuLink($subCategory, $parentCategoryId, $title);
    }
    

    $rules = [
      'title' => ['label'=>'Post Title', 'rules'=>'required'],
    ];
    $photoRules = [
        'photo' => [
            'label' => 'Image File',
            'rules' => 'uploaded[photo]'
                . '|is_image[photo]'
                . '|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                . '|max_size[photo,2024]'
        ],
    ];

    if(!$this->validate($rules)){ 
      session()->setTempdata('error', 'Post Title can not be empty', 3);
      return redirect()->to('administrator/posts/block-post/edit/'.$id.'-'.$alias);
    }
      
    // Handle file upload
    $photo = $this->request->getFile('photo');
    if ($photo->isValid() && !$photo->hasMoved()) {
      if ($this->validate($photoRules)) {
        $newName = $photo->getRandomName();
        $photo->move(ROOTPATH . 'media/posts', $newName);
        $nwn1 = base_url('media/posts/') . $newName;
      }else{
          $this->data['validation'] = $this->validator;
        }
    }else{
        $nwn1 = Null;
    }

    $postData = [
        'title'           => $this->request->getVar("title"),
        'alias'           => $alias,
        'photo'           => $nwn1,
        'menu_link'       => $menuLink,
        'excerpt'         => $this->request->getVar("excerpt"), 
        'category_id'     => $categoryId,
        'author_id'       => $this->request->getVar("author_id"),
        'is_block'        => 'Yes',
        'status'          => $this->request->getVar("status"), 
        'access'          => $this->request->getVar("access"),
        'published_date'  => $publishedDate, 
        'metadesc'        => $this->request->getVar("metadesc"),
        'metakey'         => $this->request->getVar("metakey"),
        'created_by'      => $this->userdata->user_id,
    ];
    $results = $this->postsModel->save($postData);

    if($results)
    {
        $postId = $this->postsModel->getInsertID();
        // Save Tags attached to the Post
        $tags = $this->request->getVar('tags');
        if($tags){
          foreach ($tags as $tag) {
            $tagPostData = [
                'tag_id' => $tag,
                'post_id' => $postId
            ];
            $this->posttagsModel->save($tagPostData);
          } 
        }
        
        //Save & Send Notification
        $adminmessage = 'New Block Post:  <strong>'.$title.'</strong> Post added successfully';
        $notificationType = 'posts';
        $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

        session()->setTempdata('success', 'Post added successfully', 3);
        return redirect()->to('administrator/posts/block-post/edit/'.$postId.'-'.$alias);
    }else{
        session()->setTempdata('error', 'Post NOT added', 3);
        return redirect()->to('administrator/posts/block-post/add');
    }
  }
  return view('Modules\Posts\Views\block-post\add_post', $this->data);
}
  public function editBlockPost($id = null)
  {
    $this->data['title'] = "Edit Block Post";
    $this->data['bcrumb'] = "Edit Block Post";

    $this->data['authors']      = $this->usersModel->getAll();
    $this->data['categories']   =$this->postscategoryModel->getAll();
    $this->data['categoryTree'] = $this->postscategoryModel->getCategoryList();
    $this->data['postTags'] = $this->posttagsModel->getPostTags($id);
    $singlePost   = $this->postsModel->where('id', $id)->orWhere('alias', $id)->first($id);

    $this->data['singlePost'] = $singlePost;
    $this->data['blockData'] = $this->postblocksModel->getSingleBlockPost($id);

    return view('Modules\Posts\Views\block-post\edit_blockpost', $this->data);
  }

  public function updateBlockPost()
  {
    $this->data['title'] = "Edit Block Post";
    $this->data['bcrumb'] = "Edit Block Post";

    $admins = $this->usersModel->getAdminUsers();
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->postscategoryModel->getOtherCategories();
    
    if($this->request->getMethod() == 'POST')
    {
      $id = $this->request->getPost('post_id');
      //Getting Published Date for Post
      $pdate = $this->request->getVar('pdate');
      $ptime = $this->request->getVar('ptime');
      if($pdate){
        $publishedDate = $pdate.' '.$ptime;
      }else{
        $publishedDate = date('Y-m-d H:i:s');
      }

      // Generate Sub category alias for Menu Link
      $singlePost   = $this->postsModel->where('id', $id)->first($id);
      $title = $this->request->getVar("title");
      $categoryId = $this->request->getVar("category_id");
      $categoryName = $this->postscategoryModel->getSingleCategory($categoryId); 
      $subCategory = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($categoryName->name)));
      $alias = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar("title"))));
      $parentId = $this->postscategoryModel->getParentCategory($categoryId);

      if(empty($parentId)){
        $menuLink = $subCategory.'/'.$alias;
      }else{
        $parentCategoryId = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($parentId->name)));
        $menuLink = $this->generateMenuLink($subCategory, $parentCategoryId, $title);
      }

        $rules = [
          'title' => ['label'=>'Post Title', 'rules'=>'required'],
        ];
        $photoRules = [
          'photo' => [
              'label' => 'Image File',
              'rules' => 'uploaded[photo]'
                  . '|is_image[photo]'
                  . '|mime_in[photo,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
                  . '|max_size[photo,2024]'
          ],
        ];

        if(!$this->validate($rules)){ 
          session()->setTempdata('error', 'Post Title can not be empty', 3);
          return redirect()->to('administrator/posts/block-post/edit/'.$id.'-'.$alias);
        }
         
        // Handle file upload
        $photo = $this->request->getFile('photo');
        if ($photo->isValid() && !$photo->hasMoved()) {
          if ($this->validate($photoRules)) {
            $newName = $photo->getRandomName();
            $photo->move(ROOTPATH . 'media/posts', $newName);
            $nwn1 = base_url('media/posts/') . $newName;
          }else{
              $this->data['validation'] = $this->validator;
            }
        }else{
            $nwn1 = $singlePost['photo'];
        }

        $postData = [
            'title'          => $title,
            'alias'          => $alias,
            'photo'           =>$nwn1,
            'menu_link'       => $menuLink,
            'content'         => $this->request->getVar("content"),
            'excerpt'         => $this->request->getVar("excerpt"), 
            'category_id'     => $categoryId,
            'author_id'       => $this->request->getVar("author_id"), 
            'status'          => $this->request->getVar("status"), 
            'access'          => $this->request->getVar("access"),
            'published_date'  => $publishedDate,
            'metadesc'        => $this->request->getVar("metadesc"),
            'metakey'         => $this->request->getVar("metakey"),
            'updated_by'      => $this->userdata->user_id,
          ];
          $results = $this->postsModel->update($id, $postData);
        
        if($results)
        {
          
          // Save Tags attached to the Post
          $tags = $this->request->getVar('tags');
          if($tags){
            foreach ($tags as $tag) {
              $tagPostData = [
                  'tag_id' => $tag,
                  'post_id' => $id
              ];
              $this->posttagsModel->save($tagPostData);
            } 
          }

          //Save & Send Notification
          $adminmessage = 'Block Post:  <strong>'.$title.'</strong> Post updated successfully';
          $notificationType = 'posts';
          $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

          session()->setFlashdata('info', 'Post updated successfully', 3);

          if($categoryId == 1){
            return redirect()->to('administrator/pages/block-pages');
          }
          return redirect()->to('administrator/posts/block-posts');
        }else{
            session()->setTempdata('error', 'Post NOT added', 3);
            return redirect()->to('administrator/posts/block-post/edit/'.$id.'-'.$alias);
        }
          
      }
    
    return view('Modules\Posts\Views\\block-post\edit_blockpost', $this->data);
  }
  public function viewBlockPost($id = null)
  {
    $page = $this->postsModel->getSinglePost($id);
    $this->data['title'] = $page->title." Page";
    $this->data['bcrumb'] = $page->title." Page";

    //Getting Hits & Saving them.
    $current_hits = $page->hits;
    $new_hits = $current_hits + 1;
    $this->postsModel->update($id, ['hits'=>$new_hits]);

    //Get User Unique Views/Visits - basing on session ID
    $user_ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $user_identifier = session()->get('logged_user');

    $userExists = $this->authloginModel->checkUserExists($user_ip, $user_identifier);
    $current_views = $page->views;

    if ($userExists) {
        $unique_views = $current_views + 1;
        $this->postsModel->update($id, ['views' => $unique_views]);
    }

    $this->data['comments'] = $this->postcommentsModel->getPostComments($id);
    $this->data['postTags'] = $this->posttagsModel->getPostTags($id);
    $this->data['singlePost'] = $this->postsModel->getSinglePost($id);

    //$this->data['blockData'] = $allBlocks;
    $this->data['blockData'] = $this->postblocksModel->getSingleBlockPost($id);
    return view('Modules\Posts\Views\block-post\view_blockpost', $this->data);
  }

/**========================================================================
 * POST CATEGORY /ADD/EDIT/DELETE
 ==========================================================================*/
  public function postCategories()
  {
   
    // display header information
		$this->data['title'] = "Post Categories";
    $this->data['bcrumb'] = "Post Categories";

    $this->data['post_categories'] = $this->postscategoryModel->getOtherCategories();
    $categories = $this->postscategoryModel->getOtherCategories();
    $masterCategories = [];
    foreach ($categories as $cat) {
        $masterCategory = $this->postscategoryModel->getParentCategory($cat->id);
        if ($masterCategory !== null) {
            $masterCategories[$cat->id] = $masterCategory->name;
        }
    }
    $this->data['masterCategories'] = $masterCategories;   

    return view('Modules\Posts\Views\category', $this->data);
  }

  public function addCategory()
  {    
    $this->data['post_categories'] = $this->postscategoryModel->getOtherCategories();
    

    if($this->request->getMethod() == 'POST'){
        $rules = [
          'name' => ['label'=>'Category Name', 'rules'=>'required'],
      ];

      if($this->validate($rules))
      {
          $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('name'))));
          $masterCategory = $this->request->getVar("master_category_id");

          if($masterCategory){
            $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'master_category_id'   => $this->request->getVar("master_category_id"),
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
            ];
            $results = $this->postscategoryModel->save($productData);
          }else{
            $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'master_category_id'   => Null,
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
            ];
            $results = $this->postscategoryModel->save($productData);
          }
          
          if($results)
          {
              session()->setTempdata('success', 'Category added successfully', 3);
              return redirect()->to('administrator/posts/categories');
          }else{
              session()->setTempdata('error', 'Category NOT added', 3);
              return redirect()->to('administrator/posts/categories');
          }
      }else{
        session()->setTempdata('error', 'Category Name can not be empty', 3);
        return redirect()->to('administrator/posts/categories');
      }
    }
    return view('Modules\Posts\Views\category', $this->data);
  }
  public function editCategory($id = null)
  {
    if($this->userdata->group_id != 1)
    {
      session()->setFlashdata('warning', 'Access denied');
      return redirect()->to(previous_url());
    }
    $this->data['title'] = "Post Categories";
    $this->data['bcrumb'] = "Post Categories";

    $this->data['post_categories'] = $this->postscategoryModel->getOtherCategories();
    $this->data['singleCategory'] = $this->postscategoryModel->where('id', $id)->first($id);

    return view('Modules\Posts\Views\category', $this->data);
  }
  public function updateCategory()
  {
    if($this->userdata->group_id != 1)
    {
      session()->setFlashdata('warning', 'Access denied');
      return redirect()->to(previous_url());
    }
    $this->data['title'] = "Post Categories";
    $this->data['bcrumb'] = "Post Categories";

    $this->data['post_categories'] = $this->postscategoryModel->getOtherCategories();
   
    if($this->request->getMethod() == 'POST'){
        $rules = [
          'name' => ['label'=>'Category 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'))));
          $masterCategory = $this->request->getVar("master_category_id");

          if($masterCategory){
            $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'master_category_id'   => $this->request->getVar("master_category_id"),
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
            ];
            $results = $this->postscategoryModel->update($id, $productData);
          }else{
            $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'master_category_id'   => Null,
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
            ];
            $results = $this->postscategoryModel->update($id, $productData);
          }
          
          if($results)
          {
              session()->setTempdata('success', 'Category updated successfully', 3);
              return redirect()->to('administrator/posts/categories');
          }else{
              session()->setTempdata('error', 'Category NOT updated', 3);
              return redirect()->to('administrator/posts/categories');
          }
      }else{
        session()->setTempdata('error', 'Category Name can not be empty', 3);
        return redirect()->to('posts/categories');
      }
    }
    return view('Modules\Posts\Views\category', $this->data);
  }
  public function delCategory($id)
  {
        $this->postscategoryModel->where('id', $id)->delete($id);
          if($this->request->isAJAX())
          {
            $response = [
              'error' => true,
              'msg' =>'Category deleted successfully',	   
            ];
            return $this->response->setJSON($response);
          }else{
            session()->setFlashdata('success', 'Category deleted successfully', 3);
			      return redirect()->to('administrator/posts/categories');
          }
  }

/**========================================================================
 * POST COMMENTS
 ==========================================================================*/
    public function allPostComments()
    {
      $this->data['title'] = "Post Comments";
      $this->data['bcrumb'] = "Post Comments";

      $this->data['post_comments'] = $this->postcommentsModel->getAll();

      return view('Modules\Posts\Views\comments\index', $this->data);
    }

    public function addPostComment()
    {
      $this->data['title'] = "Add Comment";
      $this->data['bcrumb'] = "Add Comment";

      if($this->request->getMethod() == 'POST')
      {
        $rules = [
          'description' => ['label'=>'Add Comment', 'rules'=>'required'],
        ];

        if($this->validate($rules))
        {
          $commentData = [
            'post_id'     => $this->request->getVar('post_id'),
            'description' => $this->request->getVar('description'),
            'user_id'     => $this->userdata->user_id,
          ];
          $results = $this->postcommentsModel->save($commentData);
          
          if($results)
          {
              if($this->request->isAJAX())
              {
                $response = [
                  'success' => true,
                  'msg'   => 'Comment saved successfully',
                ];
              }else{
                session()->setFlashdata('error', 'Comment saved successfully');
                return redirect()->to('administrator/posts/view/'+$post['id'].''.$post['alias']);
              }
          }else{
            if($this->request->isAJAX())
            {
              $response = [
                'error' => true,
                'msg'   => 'Comment NOT saved successfully',
              ];
            }else{
              session()->setFlashdata('error', 'Comment saved successfully');
              return redirect()->to('administrator/posts/view/'+$post['id'].''.$post['alias']);
            }
          }
        }else{
          if($this->request->isAJAX())
          {
            $response = [
              'error' => true,
              'msg'   => 'Comment can not be empty',
            ];
          }else{
            session()->setFlashdata('error', 'Comment can not be empty');
            return redirect()->to('administrator/posts/view/posts');
          }
        }
      }
    }
    public function editPostComment($id){
        $comment = $this->postcommentsModel->where('id', $id)->first($id);
        echo json_encode($comment);
    }
    public function updatePostComment()
    {
      $this->data['title'] = "Add Comment";
      $this->data['bcrumb'] = "Add Comment";

      $id = $this->request->getVar('id');
      if($this->request->getMethod() == 'POST')
      {

        $rules = [
          'description' => ['label'=>'Add Comment', 'rules'=>'required'],
        ];

        if($this->validate($rules))
        {
          $commentData = [
            'post_id'     => $this->request->getVar('post_id'),
            'description' => $this->request->getVar('description'),
            'user_id'     => $this->userdata->user_id,
          ];
          $results = $this->postcommentsModel->update($id, $commentData);
          
          if($results)
          {
            if($this->request->isAJAX())
            {
              $response = [
                'success' => true,
                'msg'   => 'Comment updated successfully',
              ];
            }else{
              session()->setFlashdata('error', 'Comment Not updated');
              return redirect()->to('administrator/posts/view/'+$post['id'].''.$post['alias']);
            }
          }
        }else{
          if($this->request->isAJAX())
          {
            $response = [
              'error' => true,
              'msg'   => 'Comment Area can not be empty',
            ];
          }else{
            session()->setFlashdata('error', 'Comment Area can not be empty');
            return redirect()->to('administrator/posts/comments');
          }
        }
      }
    }
    public function deletePostComment($id)
    {
        $commentId = $this->postcommentsModel->where('id',$id)->first($id);
        $this->postcommentsModel->where('id', $id)->delete($id);

        if($this->request->isAJAX())
        {
          $response = [
            'error' => true,
            'msg' =>'Comment deleted successfully',	   
          ];
          return $this->response->setJSON($response);
        }else{
          session()->setFlashdata('error', 'Comment deleted  successfully', 3);
                return redirect()->to('administrator/posts/comments');
        }
    }
}
