<?php

namespace Modules\Posts\Controllers;

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

class Pages extends AuthController
{

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

  /** ==========================================================
  *  PAGES
  *===============================================================*/  
  public function index()
  {	

    // display header information
		$this->data['title'] = "PAGES";
    $this->data['bcrumb'] = "Pages";

    $this->data['pages'] = $this->postsModel->getAllPages();

		return view('Modules\Posts\Views\pages\\all_pages', $this->data);
  }
  public function addPage()
  {
    
    $this->data['title'] = "Add Page";
    $this->data['bcrumb'] = "Add Page";

    $admins = $this->usersModel->getAdminUsers();
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->postscategoryModel->getAll();
    if($this->request->getMethod() == 'POST'){


      $rules = [
        'title' => ['label'=>'Page 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'))));
        $menuLink = $slug;
        $file1 = $this->request->getFile('photo');
        if($file1 != "")
        {
            if($this->validate($photoRules))
            { 
                $newName4 = $file1->getRandomName();
                $file1->move(ROOTPATH . 'media/pages', $newName4);
                $nwn1 = base_url('/media/pages/').$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"),
                  '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"), 
            'metadesc'        => $this->request->getVar("metadesc"),
            'metakey'         => $this->request->getVar("metakey"),
            'created_by'      => $this->userdata->user_id,
            ];

          $results = $this->postsModel->save($postData);
        }

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

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

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


  public function editPage($id = null)
  {
    $this->data['title'] = "Edit Page";
    $this->data['bcrumb'] = "Edit Page";

    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->postscategoryModel->getAll();
    $this->data['singlePost'] = $this->postsModel->where('id', $id)->first($id);

    return view('Modules\Posts\Views\pages\\edit_page', $this->data);
  }
  public function updatePage()
  {
    $this->data['title'] = "Edit Page";
    $this->data['bcrumb'] = "Edit Page";

    $admins = $this->usersModel->getAdminUsers();
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->postscategoryModel->getAll();
    if($this->request->getMethod() == 'POST'){

      $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'))));
        $menuLink = $slug;
        $file1 = $this->request->getFile('photo');
        if($file1 != "")
        {
            if($this->validate($photoRules))
            { 
                $newName4 = $file1->getRandomName();
                $file1->move(ROOTPATH . 'media/pages', $newName4);
                $nwn1 = base_url('/media/pages/').$newName4;

                $postData = [
                  'title'          => $this->request->getVar("title"),
                  'alias'          => $slug,
                  'photo'           =>$nwn1,
                  '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"),
                  'menu_link'       => $menuLink, 
                  'access'          => $this->request->getVar("access"), 
                  'metadesc'        => $this->request->getVar("metadesc"),
                  'metakey'         => $this->request->getVar("metakey"),
                  'created_by'      => $this->userdata->user_id,
              ];
              
              if($this->postsModel->update($id, $postData))
              {
                  //Save & Send Notification
                  $title = $this->request->getVar("title");
                  $adminmessage = 'Page:  <strong>'.$title.'</strong> has been Edited successfully';
                  $notificationType = 'posts';
                  $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

                  session()->setTempdata('success', 'Page edited successfully', 3);
                  return redirect()->to('administrator/pages');
              }else{
                  session()->setTempdata('error', 'Page NOT edited', 3);
                  return redirect()->to('administrator/pages/add');
              }
            }else{
              $this->data['validation'] = $this->validator;
            }
        }else{

          $postData = [
            'title'          => $this->request->getVar("title"),
            'alias'          => $slug,
            '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"), 
            'menu_link'       => $menuLink, 
            'access'          => $this->request->getVar("access"), 
            'metadesc'        => $this->request->getVar("metadesc"),
            'metakey'         => $this->request->getVar("metakey"),
            'created_by'      => $this->userdata->user_id,
            ];
          
          if($this->postsModel->update($id, $postData))
          {
              //Save & Send Notification
              $title = $this->request->getVar("title");
              $adminmessage = 'Page:  <strong>'.$title.'</strong> has been Edited successfully';
              $notificationType = 'posts';
              $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

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

    return view('Modules\Posts\Views\pages\\edit_page', $this->data);
  }
  public function viewPage($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['singlePage'] = $this->postsModel->getSinglePost($id);
    
    return view('Modules\Posts\Views\pages\\view_page', $this->data);
  }
  public function delPage($id)
  {
    $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 = 'Page:   <strong>'.$title.'</strong>  has been DELETED successfully';
      $notificationType = 'posts';
      $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

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

/**========================================================================
 *  BLOCK PAGE
 *  (using post blocks to make pages.)
 *=========================================================================*/
  public function viewBlockPages()
  {
    // display header information
    $this->data['title'] = "Block Pages";
    $this->data['bcrumb'] = "Block pages";

    $this->data['pages'] = $this->postsModel->getAllBlockPages();

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

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

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

    return view('Modules\Posts\Views\pages\add-block-page', $this->data);
  }

}