<?php

namespace Modules\Team\Controllers;

use App\Controllers\Auth\AuthController;

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

  public function index()
  {
    
	  $this->data['title'] = "Team Member Profiles";
    $this->data['bcrumb'] = "Team Member Profiles";

    $this->data['team_members'] = $this->teamModel->getAllNotTeamBlockMembers();
    

	  return View('Modules\Team\Views\index', $this->data);
  }

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

    $admins = $this->usersModel->getAdminUsers();
    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');
      }

      $deathDate = $this->request->getVar('died_at');

      $rules = [
        'title' => ['label'=>'Member Name', 'rules'=>'required'],
        'position'=>['label'=>'Job Title', 'rules'=>'required'],
        'category_id'=>['label'=>'Category', '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))
      {

        $file1 = $this->request->getFile('photo');
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        if($this->validate($photoRules))
        { 
              $newName4 = $file1->getRandomName();
              $file1->move(ROOTPATH . 'media/team', $newName4);
              $nwn1 = base_url('media/team/').$newName4;

              $teamData = [
                'title'       => $this->request->getVar('title'),
                'alias'       => $slug,
                'photo'       => $nwn1,
                'published_date'  => $publishedDate, 
                'category_id' => $this->request->getVar('category_id'),
                'email'       => $this->request->getVar('email'),
                'position'    => $this->request->getVar('position'),
                'excerpt'     => $this->request->getVar('excerpt'),
                'content'     => $this->request->getVar('content'),
                'birthday'    => $this->request->getVar('birthday'),
                'died_at'     => $deathDate ?: Null,
                'achievements'  => $this->request->getVar('achievements'),
                'relationship_status' => $this->request->getVar('relationship_status'),
                'urls'        => $this->request->getVar('urls'),
                'facebook'    => $this->request->getVar('facebook'),
                'twitter'     => $this->request->getVar('twitter'),
                'instagram'   => $this->request->getVar('instagram'),
                'tiktok'      => $this->request->getVar('tiktok'),
                'linkedin'    => $this->request->getVar('linkedin'),
                'snapchat'    => $this->request->getVar('snapchat'),
                'metadesc'    => $this->request->getVar('metadesc'),
                'status'      => $this->request->getVar('status'),
                'metakey'     => $this->request->getVar('metakey'),
                'created_by'  => $this->userdata->user_id,
              ];

              $results = $this->teamModel->save($teamData);
              if($results){

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

                session()->setTempdata('success', 'Member added successfully', 3);
                return redirect()->to('administrator/team/members');
              }else{
                session()->setTempdata('error', 'Member NOT added', 3);
                return redirect()->to('administrator/team/members');
              }
        }else{
          $this->data['validation'] = $this->validator;
        }
      }else{
        $this->data['validation'] = $this->validator;
      }

    }

    return View('Modules\Team\Views\add_member', $this->data);
  }
  
  public function editMember($member = null)
  {
    $this->data['title'] = 'Edit Member Details';
    $this->data['bcrumb'] = 'Edit Member Details';

    $this->data['member'] = $this->teamModel->getSingleMember($member);

    return View('Modules\Team\Views\edit_member', $this->data);
  }

  public function updateMember()
  {
    $this->data['title'] = 'Edit Member Details';
    $this->data['bcrumb'] = 'Edit Member Details';

    $admins = $this->usersModel->getAdminUsers();
 
    
    if($this->request->getMethod() == 'POST')
    {
      $id = $this->request->getVar('id');
      $rules = [
        'title'       => ['label'=>'Member Name', 'rules'=>'required'],
        'position'    =>['label'=>'Job Title', 'rules'=>'required'],
        'category_id' =>['label'=>'Category', '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]'
        ],
      ];
      
      $deathDate = $this->request->getVar('died_at');
      
      //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');
      }

      if($this->validate($rules))
      {
        
        $file1 = $this->request->getFile('photo');
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        if($file1 != "")
        {
             
            if(!$this->validate($photoRules))
            {
                $this->data['validation'] = $this->validator;
            }
            
            $newName4 = $file1->getRandomName();
            $file1->move(ROOTPATH . 'media/team', $newName4);
            $nwn1 = base_url('media/team/').$newName4;
              
            $teamData = [
              'title'       => $this->request->getVar('title'),
              'alias'       => $slug,
              'photo'       => $nwn1,
              'published_date'  => $publishedDate, 
              'category_id' => $this->request->getVar('category_id'),
              'email'       => $this->request->getVar('email'),
              'position'    => $this->request->getVar('position'),
              'excerpt'     => $this->request->getVar('excerpt'),
              'content'     => $this->request->getVar('content'),
              'birthday'    => $this->request->getVar('birthday'),
              'died_at'     => $deathDate ?: Null,
              'achievements'  => $this->request->getVar('achievements'),
              'relationship_status' => $this->request->getVar('relationship_status'),
              'urls'        => $this->request->getVar('urls'),
              'facebook'    => $this->request->getVar('facebook'),
              'twitter'     => $this->request->getVar('twitter'),
              'instagram'   => $this->request->getVar('instagram'),
              'tiktok'      => $this->request->getVar('tiktok'),
              'linkedin'    => $this->request->getVar('linkedin'),
              'snapchat'    => $this->request->getVar('snapchat'),
              'metadesc'    => $this->request->getVar('metadesc'),
              'status'      => $this->request->getVar('status'),
              'metakey'     => $this->request->getVar('metakey'),
              'updated_by'  => $this->userdata->user_id,
            ];
        }else{
          $teamData = [
            'title'       => $this->request->getVar('title'),
            'alias'       => $slug,
            'published_date'  => $publishedDate, 
            'category_id' => $this->request->getVar('category_id'),
            'email'       => $this->request->getVar('email'),
            'position'    => $this->request->getVar('position'),
            'excerpt'     => $this->request->getVar('excerpt'),
            'content'     => $this->request->getVar('content'),
            'birthday'    => $this->request->getVar('birthday'),
            'died_at'     => $deathDate ?: Null,
            'achievements'  => $this->request->getVar('achievements'),
            'relationship_status' => $this->request->getVar('relationship_status'),
            'urls'        => $this->request->getVar('urls'),
            'facebook'    => $this->request->getVar('facebook'),
            'twitter'     => $this->request->getVar('twitter'),
            'instagram'   => $this->request->getVar('instagram'),
            'tiktok'      => $this->request->getVar('tiktok'),
            'linkedin'    => $this->request->getVar('linkedin'),
            'snapchat'    => $this->request->getVar('snapchat'),
            'metadesc'    => $this->request->getVar('metadesc'),
            'status'      => $this->request->getVar('status'),
            'metakey'     => $this->request->getVar('metakey'),
            'updated_by'  => $this->userdata->user_id,
          ];
          
        }

        $results = $this->teamModel->update($id, $teamData);
        if($results){

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

          session()->setTempdata('success', 'Member updated successfully', 3);
          return redirect()->to('administrator/team/members');
        }else{
          session()->setTempdata('error', 'Member NOT added', 3);
          return redirect()->to('administrator/team/members');
        }

      }else{
        $this->data['validation'] = $this->validator;
      }
    }
    return View('Modules\Team\Views\edit_member', $this->data);
  }


  public function viewMember($member)
  {
    $memberDetails = $this->teamModel->getSingleMember($member);
    $this->data['title'] = 'Member Details';
    $this->data['bcrumb'] = 'Member Details';

    //Capture Hits per Member
    $current_hits = $memberDetails->hits;
    if($current_hits < 100){
      $new_hits = $current_hits + 100;
    }else{
      $new_hits = $current_hits + 1;
    }
    
    $this->teamModel->update($member, ['hits' => $new_hits]);
   
    $this->data['member'] = $this->teamModel->getSingleMember($member);

    return View('Modules\Team\Views\view_member', $this->data);
  }

  public function deleteMember($id)
  {
      if($this->userdata->group_id != 1 || $this->userdata->group_id != 2 ){
          session()->setFlashdata('warning', 'Access Denied', 3);
          return redirect()->to('administrator/team/members');
      }
    $admins = $this->usersModel->getAdminUsers();
    $member = $this->teamModel->getSingleMember($id);
    $this->teamModel->where('id', $id)->delete($id);
      if($this->request->isAJAX())
      {
        $response = [
          'error' => true,
          'msg' =>'Member deleted successfully',	   
        ];
        return $this->response->setJSON($response);
      }else{
        //Save & Send Notification
        $t = $member->title;
        $adminmessage = 'Team Member Profile - <strong>'.$title.' </strong> has been DELETED successfully';
        $notificationType = 'posts';
        $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);


        session()->setFlashdata('error', 'Member deleted successfully', 3);
        return redirect()->to('administrator/team/members');
      }
  }
/** ===================================================================
   * TEAM BLOCKS
*======================================================================*/
public function allBlockMembers()
{
  $this->data['title'] = "Team Block Members";
  $this->data['bcrumb'] = "Team Block Members";

  $admins = $this->usersModel->getAdminUsers();
  $this->data['team_members'] = $this->teamModel->getAllTeamBlockMembers();

  return View('Modules\Team\Views\team-blocks\all_blockmembers', $this->data);
}

public function addblockMember()
{
  $this->data['title'] = "Add Block Member";
  $this->data['bcrumb'] = "Add Block Member";

  $admins = $this->usersModel->getAdminUsers();
  $this->data['tags'] = $this->tagsModel->getAll();
  $this->data['authors'] = $this->usersModel->getAll();

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

    $deathDate = $this->request->getVar('died_at');
    if($deathDate)
    {
      $deathDate = $this->request->getVar('died_at');
    }else{
      $deathDate = NULL;
    }

    $rules = [
      'title' => ['label'=>'Member Name', 'rules'=>'required'],
      'position'=>['label'=>'Job Title', 'rules'=>'required'],
      'category_id'=>['label'=>'Category', '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))
    {
      $file1 = $this->request->getFile('photo');
      $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
      if($this->validate($photoRules))
      { 
            $newName4 = $file1->getRandomName();
            $file1->move(ROOTPATH . 'media/team', $newName4);
            $nwn1 = base_url('/media/team/')."/".$newName4;

            $teamData = [
              'title'       => $this->request->getVar('title'),
              'alias'       => $slug,
              'photo'       => $nwn1,
              'is_block'    => 'Yes',
              'category_id' => $this->request->getVar('category_id'),
              'position'    => $this->request->getVar('position'),
              'excerpt'     => $this->request->getVar('excerpt'),
              'content'     => $this->request->getVar('content'),
              'birthday'    => $this->request->getVar('birthday'),
              'died_at'     => $deathDate,
              'achievements'  => $this->request->getVar('achievements'),
              'relationship_status' => $this->request->getVar('relationship_status'),
              'urls'        => $this->request->getVar('urls'),
              'facebook'    => $this->request->getVar('facebook'),
              'twitter'     => $this->request->getVar('twitter'),
              'instagram'   => $this->request->getVar('instagram'),
              'tiktok'      => $this->request->getVar('tiktok'),
              'linkedin'    => $this->request->getVar('linkedin'),
              'snapchat'    => $this->request->getVar('snapchat'),
              'metadesc'    => $this->request->getVar('metadesc'),
              'status'      => $this->request->getVar('status'),
              'metakey'     => $this->request->getVar('metakey'),
              'created_by'  => $this->userdata->user_id,
            ];

            $results = $this->teamModel->save($teamData);
            if($results){
              $postId = $this->teamModel->getInsertID();
              //Save & Send Notification
              $title = $this->request->getVar("title");
              $adminmessage = 'New Team Member Profile - <strong>'.$title.' </strong> has been created successfully';
              $notificationType = 'posts';
              $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

              session()->setTempdata('success', 'Member added successfully', 3);
              return redirect()->to('administrator/team/member/block/edit/'.$postId.'-'.$slug);
            }else{
              session()->setTempdata('error', 'Member NOT added', 3);
              return redirect()->to('administrator/team/member/block/add');
            }

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

  }
  return View('Modules\Team\Views\team-blocks\add_blockmember', $this->data);
}

public function editblockMember($id = null)
  {
    $this->data['title'] = 'Edit Member Details';
    $this->data['bcrumb'] = 'Edit Member Details';

    $this->data['member'] = $this->teamModel->getSingleMember($id);

    // Retrieve block data for a specific Team Member 
    $textBlocks     = $this->postblock_textModel->getAllTextBlocksPerTeam($id);
    $codeBlocks     = $this->postblock_codeModel->getAllCodeBlocksPerTeam($id);
    $advertcodeBlocks     = $this->postblock_advertcodeModel->getAllAdvertCodeBlocksPerTeam($id);
    $headingBlocks  = $this->postblock_headingModel->getAllHeadingBlocksPerTeam($id);
    $listBlocks     = $this->postblock_listModel->getAllListBlocksPerTeam($id);
    $videoBlocks    =  $this->postblock_videoModel->getAllVideoBlocksPerTeam($id);
    $imageBlocks    = $this->postblock_imageModel->getAllImageBlocksPerTeam($id);

    // Merge all block arrays into a single array
    $allBlocks = array_merge($textBlocks, $headingBlocks, $imageBlocks, $listBlocks, $codeBlocks, $videoBlocks, $advertcodeBlocks);

    // Sort the merged array by created_at timestamp
    usort($allBlocks, function ($a, $b) {
        // Compare timestamps (assuming created_at is a field in each block)
        return strtotime($a->created_at) - strtotime($b->created_at);
    });

    $this->data['blockData'] = $allBlocks;

    return View('Modules\Team\Views\team-blocks\edit_blockmember', $this->data);
  }

  public function updateblockMember()
  {
    $this->data['title'] = 'Edit Member Details';
    $this->data['bcrumb'] = 'Edit Member Details';

    $admins = $this->usersModel->getAdminUsers();
    $id = $this->request->getVar('id');
    $deathDate = $this->request->getVar('died_at');
    if($deathDate)
    {
      $deathDate = $this->request->getVar('died_at');
    }else{
      $deathDate = NULL;
    }
    
    if($this->request->getMethod() == 'POST')
    {
      $rules = [
        'title'       => ['label'=>'Member Name', 'rules'=>'required'],
        'position'    =>['label'=>'Job Title', 'rules'=>'required'],
        'category_id' =>['label'=>'Category', '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))
      {
        
        $file1 = $this->request->getFile('photo');
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        if($file1 != "")
        {
          if($this->validate($photoRules))
          {
            $teamData = [
              'title'       => $this->request->getVar('title'),
              'alias'       => $slug,
              'photo'       => $nwn1,
              'is_block'    => 'Yes',
              'category_id' => $this->request->getVar('category_id'),
              'position'    => $this->request->getVar('position'),
              'excerpt'     => $this->request->getVar('excerpt'),
              'content'     => $this->request->getVar('content'),
              'birthday'    => $this->request->getVar('birthday'),
              'died_at'     => $deathDate,
              'achievements'  => $this->request->getVar('achievements'),
              'relationship_status' => $this->request->getVar('relationship_status'),
              'urls'        => $this->request->getVar('urls'),
              'facebook'    => $this->request->getVar('facebook'),
              'twitter'     => $this->request->getVar('twitter'),
              'instagram'   => $this->request->getVar('instagram'),
              'tiktok'      => $this->request->getVar('tiktok'),
              'linkedin'    => $this->request->getVar('linkedin'),
              'snapchat'    => $this->request->getVar('snapchat'),
              'metadesc'    => $this->request->getVar('metadesc'),
              'status'      => $this->request->getVar('status'),
              'metakey'     => $this->request->getVar('metakey'),
              'created_by'  => $this->userdata->user_id,
            ];
            $results = $this->teamModel->update($id, $teamData);

          }else{
            $this->data['validation'] = $this->validator;
          }
        }else{
          $teamData = [
            'title'       => $this->request->getVar('title'),
            'alias'       => $slug,
            'is_block'    => 'Yes',
            'category_id' => $this->request->getVar('category_id'),
            'position'    => $this->request->getVar('position'),
            'excerpt'     => $this->request->getVar('excerpt'),
            'content'     => $this->request->getVar('content'),
            'birthday'    => $this->request->getVar('birthday'),
            'died_at'     => $deathDate,
            'achievements'  => $this->request->getVar('achievements'),
            'relationship_status' => $this->request->getVar('relationship_status'),
            'urls'        => $this->request->getVar('urls'),
            'facebook'    => $this->request->getVar('facebook'),
            'twitter'     => $this->request->getVar('twitter'),
            'instagram'   => $this->request->getVar('instagram'),
            'tiktok'      => $this->request->getVar('tiktok'),
            'linkedin'    => $this->request->getVar('linkedin'),
            'snapchat'    => $this->request->getVar('snapchat'),
            'metadesc'    => $this->request->getVar('metadesc'),
            'status'      => $this->request->getVar('status'),
            'metakey'     => $this->request->getVar('metakey'),
            'created_by'  => $this->userdata->user_id,
          ];
          $results = $this->teamModel->update($id, $teamData);
        }

        if($results){

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

          session()->setTempdata('success', 'Member updated successfully', 3);
          return redirect()->to('administrator/team/member/blocks');
        }else{
          session()->setTempdata('error', 'Member NOT added', 3);
          return redirect()->to('administrator/team/member/block/edit/'.$id.'-'.$slug);
        }

      }else{
        $this->data['validation'] = $this->validator;
      }
    }
    //return View('Modules\Team\Views\edit_member', $this->data);
  }

  public function viewblockMember($member)
  {
    $memberDetails = $this->teamModel->getSingleMember($member);
    $this->data['title'] = $memberDetails->title.' Member Details';
    $this->data['bcrumb'] = 'Member Details';

    //Capture Hits per Member
    $current_hits = $memberDetails->hits;
    if($current_hits < 100){
      $new_hits = $current_hits + 100;
    }else{
      $new_hits = $current_hits + 1;
    }
    
    $this->teamModel->update($member, ['hits' => $new_hits]);
   
    $this->data['member'] = $this->teamModel->getSingleMember($member);

    // Retrieve block data for a specific post
    $textBlocks     = $this->postblock_textModel->getAllTextBlocksPerTeam($member);
    $codeBlocks     = $this->postblock_codeModel->getAllCodeBlocksPerTeam($member);
    $advertcodeBlocks     = $this->postblock_advertcodeModel->getAllAdvertCodeBlocksPerTeam($member);
    $headingBlocks  = $this->postblock_headingModel->getAllHeadingBlocksPerTeam($member);
    $listBlocks     = $this->postblock_listModel->getAllListBlocksPerTeam($member);
    $videoBlocks    =  $this->postblock_videoModel->getAllVideoBlocksPerTeam($member);
    $imageBlocks    = $this->postblock_imageModel->getAllImageBlocksPerTeam($member);

    // Merge all block arrays into a single array
    $allBlocks = array_merge($textBlocks, $headingBlocks, $imageBlocks, $listBlocks, $codeBlocks, $videoBlocks, $advertcodeBlocks);

    // Sort the merged array by created_at timestamp
    usort($allBlocks, function ($a, $b) {
        // Compare timestamps (assuming created_at is a field in each block)
        return strtotime($a->created_at) - strtotime($b->created_at);
    });

    $this->data['blockData'] = $allBlocks;

    return View('Modules\Team\Views\team-blocks\view_blockmember', $this->data);
  }

/** ===================================================================
   * CATEGORIES ADD/EDIT/DELETE
*======================================================================*/
  public function categories()
  {
    $this->data['title'] = "Team Categories";
    $this->data['bcrumb'] = "Categories";


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

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

  public function addCategory()
  {
    $this->data['title'] = "Team Categories";
    $this->data['bcrumb'] = "Categories";
    $this->data['team_categories'] = $this->teamcategoryModel->getAll();

    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'))));
        $parentId = $this->request->getVar('parent_category_id');
        if($parentId){
          $catData = [
            'name'                => $this->request->getVar('name'),
            'alias'               => $slug,
            'description'         => $this->request->getVar('description'),
            'parent_category_id'  => $parentId,
            'created_by'          => $this->userdata->user_id,
          ];
          $results = $this->teamcategoryModel->save($catData);
        }else{
          $catData = [
            'name'                => $this->request->getVar('name'),
            'alias'               => $slug,
            'description'         => $this->request->getVar('description'),
            'parent_category_id'  => NULL,
            'created_by'          => $this->userdata->user_id,
          ];
          $results = $this->teamcategoryModel->save($catData);
        }

        if($results){
          session()->setTempdata('success', 'Category created successfully');
          return redirect()->to(base_url('administrator/team/categories'));
        }else{
          session()->setTempdata('success', 'Category NOT created successfully');
          return redirect()->to(base_url('administrator/team/categories'));
        }
      }else{
        $this->data['validation'] = $this->validator;
      }

    }
    return View('Modules\Team\Views\category', $this->data);
  }
  public function editCategory($id = null)
  {
    $this->data['title'] = "Team Categories";
    $this->data['bcrumb'] = "Categories";

    $this->data['team_categories'] = $this->teamcategoryModel->getAll();
    $this->data['singleCategory'] = $this->teamcategoryModel->where('id', $id)->first($id);

    return View('Modules\Team\Views\category', $this->data);
  }
  public function updateCategory()
  {
    $this->data['title'] = "Team Categories";
    $this->data['bcrumb'] = "Categories";
    $this->data['team_categories'] = $this->teamcategoryModel->getAll();

    $id = $this->request->getVar('id');
    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'))));
        $parentId = $this->request->getVar('parent_category_id');
        if($parentId){
          $catData = [
            'name'                => $this->request->getVar('name'),
            'alias'               => $slug,
            'description'         => $this->request->getVar('description'),
            'parent_category_id'  => $parentId,
            'updated_by'          => $this->userdata->user_id,
          ];
          $results = $this->teamcategoryModel->update($id, $catData);
        }else{
          $catData = [
            'name'                => $this->request->getVar('name'),
            'alias'               => $slug,
            'description'         => $this->request->getVar('description'),
            'parent_category_id'  => NULL,
            'updated_by'          => $this->userdata->user_id,
          ];
          $results = $this->teamcategoryModel->update($id, $catData);
        }

        if($results){
          session()->setTempdata('success', 'Category updated successfully');
          return redirect()->to(base_url('administrator/team/categories'));
        }else{
          session()->setTempdata('success', 'Category NOT updated');
          return redirect()->to(base_url('administrator/team/categories'));
        }
      }else{
        $this->data['validation'] = $this->validator;
      }

    }
    return View('Modules\Team\Views\category', $this->data);
  }
  public function delCategory($id)
  {
      if($this->userdata->group_id != 1 || $this->userdata->group_id != 2 ){
          session()->setFlashdata('warning', 'Access Denied', 3);
          return redirect()->to('administrator/team/members');
      }
        $this->teamcategoryModel->where('id', $id)->delete($id);
          if($this->request->isAJAX())
          {
            $response = [
              'error' => true,
              'msg' =>'Category deleted successfully',	   
            ];
            return $this->response->setJSON($response);
          }else{
            session()->setFlashdata('error', 'Category deleted successfully', 3);
			      return redirect()->to('administrator/team/categories');
          }
    }

}
