<?php
namespace Modules\Posts\Controllers;

use App\Controllers\Auth\AuthController;

class Tags extends AuthController
{
  public function initController($request, $response, $logger)
  {
    parent::initController($request, $response, $logger);
    $this->data['tags'] = $this->tagsModel->getAll();
  }

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

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

  public function getTagsList()
  {
    $tags = $this->tagsModel->getAllTags();
    $response = [
      'tags' => $tags,
      'success'=>true
    ];
    return $this->response->setJSON($response);
  }

  //Check if Tag Exists in DB
  public function checkTag()
  {
      $tagName = $this->request->getPost('name');
      $tag = $this->tagsModel->where('name', $tagName)->first();

      $response = [
          'exists' => ($tag !== null),
          'tagId' => ($tag !== null) ? $tag['id'] : null,
      ];
      return $this->response->setJSON($response);
  }

  public function addTag()
  { 
    $this->data['title'] = "Tags";
    $this->data['bcrumb'] = "Tags";

    $tagName = $this->request->getPost('name');
    $tag = $this->tagsModel->where('name', $tagName)->orWhere('id', $tagName)->first();
    if(!$tag){

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

      //Check Tag Name or ID does not exist before Adding.


      $rules = [
          'name' => ['label'=>'Tag Name', 'rules'=>'required'],
      ];

      if($this->validate($rules))
      {
          $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('name'))));
          $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'description'   => $this->request->getVar("description"),
          ];
          
          if($this->tagsModel->save($productData))
          {
            if($this->request->isAjax())
            {
              $response = [
                'success' => true,
                'msg' => 'Tag added successfully',
              ];
              return $this->response->setJSON($response);
            }else{
              session()->setTempdata('success', 'Tag updated successfully', 3);
              return redirect()->to('administrator/tags');
            }
          }else{
              session()->setTempdata('error', 'Category NOT added', 3);
              return redirect()->to('administrator/tags');
          }
      }else{
        session()->setTempdata('error', 'Tag Name can not be empty', 3);
        return redirect()->to('administrator/tags');
      }
    }
    return view('Modules\Posts\Views\tags\tags', $this->data);
  }else{
    if($this->request->isAJAX())
    {
      $response = [
        'error' => true,
        'msg' =>'Tag already exists',	   
      ];
      return $this->response->setJSON($response);
    }else{
      session()->setFlashdata('error', 'Tag already exits', 3);
      return redirect()->to('administrator/posts/add');
    }
  }
  }
  public function editTag($id = null)
  {
    $this->data['title'] = "Edit Tag";
    $this->data['bcrumb'] = "Post Categories";

    $this->data['singleTag'] = $this->tagsModel->where('id', $id)->first($id);
    return view('Modules\Posts\Views\tags\tags', $this->data);
  }
  public function updateTag()
  {
    $this->data['title'] = "Edit Tags";
    $this->data['bcrumb'] = "Edit Tags";
   
    if($this->request->getMethod() == 'POST'){
        $rules = [
          'name' => ['label'=>'Tag 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'))));
          $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'description'   => $this->request->getVar("description"),
              'updated_at'    => date("Y-m-d H:i:s"),
          ];
          
          if($this->tagsModel->update($id, $productData))
          {
            if($this->request->isAjax())
            {
              $response = [
                'success' => true,
                'msg' => 'Tag added successfully',
              ];
              return $this->response->setJSON($response);
            }else{
              session()->setTempdata('success', 'Tag updated successfully', 3);
              return redirect()->to('administrator/tags');
            }
          }else{
              session()->setTempdata('error', 'Tag NOT updated', 3);
              return redirect()->to('administrator/tags');
          }
      }else{
        session()->setTempdata('error', 'Tag Name can not be empty', 3);
        return redirect()->to('administrator/tags');
      }
    }else{
      if($this->request->isAJAX())
      {
        $response = [
          'error' => true,
          'msg' =>'Tag already exists',	   
        ];
        return $this->response->setJSON($response);
      }else{
        session()->setFlashdata('error', 'Tag already exits', 3);
			  return redirect()->to('administrator/posts/add');
      }
    }
    return view('Modules\Posts\Views\tags\tags', $this->data);
  }
  public function delTag($id)
  {
        $this->tagsModel->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', 'Tag deleted successfully', 3);
			      return redirect()->to('administrator/tags');
          }
    }

}