<?php

namespace Modules\Sliders\Controllers;

use App\Controllers\Auth\AuthController;


class Sliders extends AuthController
{

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

  public function index()
  {
    $this->data['title'] = "Sliders";
    $this->data['bcrumb'] = "Slider Dashboard";

    return view('Modules\Sliders\Views\index', $this->data);
  }
  /*** ======================================================================
   * SLIDERS ADD/EDIT/DELETE
   =========================================================================*/
  public function allSlides()
  {
    $this->data['title'] = "All Slides";
    $this->data['bcrumb'] = "Slides";

    $this->data['allslides'] = $this->slidersModel->getAll();
    return view('Modules\Sliders\Views\all_slides', $this->data);
  }
  public function addSlide()
  {
    $this->data['title'] = "Add Slide";
    $this->data['bcrumb'] = "Add Slide";

    $this->data['categories'] = $this->sliderscategoryModel->getAll();
    
    if($this->request->getMethod() == 'POST'){

      $rules = [
        'title' => ['label'=>'Slide Title', 'rules'=>'required'],
        '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'))));
        $file1 = $this->request->getFile('photo');

          $newName4 = $file1->getRandomName();
          $file1->move(ROOTPATH . 'media/sliders', $newName4);
          $nwn1 = base_url('media/sliders/').$newName4;

          $slideData = [
            'title'          => $this->request->getVar("title"),
            'alias'          => $slug,
            'photo'           =>$nwn1,
            'description'     => $this->request->getVar("description"), 
            'category_id'     => $this->request->getVar("category_id"), 
            'status'          => $this->request->getVar("status"),
            'link_text'       => $this->request->getVar("link_text"),
            'link'            => $this->request->getVar("link"),
            'link_2_text'     => $this->request->getVar("link_2_text"),
            'link_2'          => $this->request->getVar("link_2"),
            "ordering"        => $this->request->getVar("ordering"), 
            'access'          => $this->request->getVar("access"),
            'extra_1'         => $this->request->getVar("extra_1"),
            'extra_2'         => $this->request->getVar("extra_2"),
            'extra_3'         => $this->request->getVar("extra_3"),
            'extra_4'         => $this->request->getVar("extra_4"),
            'created_by'      => $this->userdata->user_id,
            ];
              
          if($this->slidersModel->save($slideData))
          {
              session()->setTempdata('success', 'Slide added successfully', 3);
              return redirect()->to('administrator/sliders/all');
          }else{
              session()->setTempdata('error', 'Slide NOT added', 3);
              return redirect()->to('sliders/add');
          }
      }else{
        $this->data['validation'] = $this->validator;
      }
        
    }
    return view('Modules\Sliders\Views\add_slide', $this->data);
  }
  public function editSlide($id = null)
  {
    $this->data['title'] = "Edit Slide";
    $this->data['bcrumb'] = "Edit Slide";

    $this->data['categories'] = $this->sliderscategoryModel->getAll();
    $this->data['myslide'] = $this->slidersModel->where('id', $id)->first($id);

    return view('Modules\Sliders\Views\edit_slider', $this->data);
  }
  public function updateSlide()
  {
    $this->data['title'] = "Edit Slide";
    $this->data['bcrumb'] = "Edit Slide";

    $id = $this->request->getVar("id");
    $this->data['categories'] = $this->sliderscategoryModel->getAll();
    $this->data['myslide'] = $this->slidersModel->where('id', $id)->first($id);

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

      $rules = [
        'title' => ['label'=>'Slide 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]'
        ],
      ];

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

      if(!$this->validate($rules)){
        $validation = \Config\Services::validation();
        $errors = $validation->getErrors();
        $errorMessage = implode('<br>', $errors);
        session()->setFlashdata('error', $errorMessage, 5);
        return redirect()->to('administrator/sliders/edit/'.$id.'-'.$slug);
      }
      
      // Handle file upload
      $myphoto = $this->request->getFile('photo');
      $sliderPic = $this->slidersModel->where('id', $id)->first($id);
      if ($myphoto->isValid() && !$myphoto->hasMoved()) {
          $newName = $myphoto->getRandomName();
          $myphoto->move(ROOTPATH . 'media/sliders', $newName);
          $nwn1 = base_url('media/sliders/') . $newName;
      }else{
          $nwn1 = $sliderPic['photo'];
      }

      $slideData = 
      [
          'title'          => $this->request->getVar("title"),
          'alias'          => $slug,
          'photo'           =>$nwn1,
          'description'     => $this->request->getVar("description"), 
          'category_id'     => $this->request->getVar("category_id"), 
          'status'          => $this->request->getVar("status"),
          'link_text'       => $this->request->getVar("link_text"),
          'link'            => $this->request->getVar("link"),
          'link_2_text'     => $this->request->getVar("link_2_text"),
          'link_2'          => $this->request->getVar("link_2"),
          "ordering"        => $this->request->getVar("ordering"), 
          'access'          => $this->request->getVar("access"),
          'extra_1'         => $this->request->getVar("extra_1"),
          'extra_2'         => $this->request->getVar("extra_2"),
          'extra_3'         => $this->request->getVar("extra_3"),
          'extra_4'         => $this->request->getVar("extra_4"),
          'updated_by'      => $this->userdata->user_id,
          'updated_at'      => date("Y-m-d H:i:s"),
        ];

        if($this->slidersModel->update($id, $slideData))
        {
            session()->setTempdata('success', 'Slide Updated successfully', 3);
            return redirect()->to('administrator/sliders/all');
        }else{
            session()->setTempdata('error', 'Slide NOT updated', 3);
            return redirect()->to('administrator/sliders/all');
        } 
    }
    return view('Modules\Sliders\Views\edit_slider', $this->data);
  }
  public function delSlide($id)
  {
    $this->slidersModel->where('id', $id)->delete($id);
    session()->setTempdata('success', 'Slide deleted successfully', 3);
    return redirect()->to('administrator/sliders/all');
  }
  /*** ======================================================================
   * SLIDER CATEGORY ADD/EDIT/DELETE
   =========================================================================*/
   public function sliderCategory()
   {
    $this->data['title'] = "Slider Categories";
    $this->data['bcrumb'] = "Slider Categories";

    $this->data['slider_categories'] = $this->sliderscategoryModel->getAll();
    return view('Modules\Sliders\Views\category', $this->data);
   }
   public function addCategory()
  {    
    $this->data['slider_categories'] = $this->sliderscategoryModel->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'))));
          $slideData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'description'   => $this->request->getVar("description"),
              'created_by'    => $this->userdata->user_id,
          ];
          
          if($this->sliderscategoryModel->save($slideData))
          {
              session()->setTempdata('success', 'Category added successfully', 3);
              return redirect()->to('administrator/sliders/categories');
          }else{
              session()->setTempdata('error', 'Category NOT added', 3);
              return redirect()->to('administrator/sliders/categories');
          }
      }else{
        session()->setTempdata('error', 'Category Name can not be empty', 3);
        return redirect()->to('administrator/sliders/categories');
      }
    }
    return view('Modules\sliders\Views\category', $this->data);
  }
  public function editCategory($id = null)
  {
    $this->data['title'] = "Slider Categories";
    $this->data['bcrumb'] = "Slider Categories";

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

    return view('Modules\Sliders\Views\category', $this->data);
  }
  public function updateCategory()
  {
    $this->data['title'] = "Slider Categories";
    $this->data['bcrumb'] = "Slider Categories";

    $this->data['slider_categories'] = $this->sliderscategoryModel->getAll();
   
    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'))));
          $productData = [
              'name'          => $this->request->getVar("name"),
              'alias'         => $slug,
              'description'   => $this->request->getVar("description"),
              'updated_by'    => $this->userdata->user_id,
              'updated_at'    => date("Y-m-d H:i:s"),
          ];
          
          if($this->sliderscategoryModel->update($id, $productData))
          {
              session()->setTempdata('success', 'Category updated successfully', 3);
              return redirect()->to('administrator/sliders/categories');
          }else{
              session()->setTempdata('error', 'Category NOT updated', 3);
              return redirect()->to('administrator/sliders/categories');
          }
      }else{
        session()->setTempdata('error', 'Category Name can not be empty', 3);
        return redirect()->to('administrator/sliders/categories');
      }
    }
    return view('Modules\Sliders\Views\category', $this->data);
  }
  public function delCategory($id)
    {
        $this->sliderscategoryModel->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/sliders/categories');
          }
    }

    //Banners for Frontside of Website
    public function showBanners()
    {
      
      $this->data['title'] = "Banners";
      $this->data['bcrumb'] = "Banners";

      $this->data['banners'] = $this->bannersModel->getAll();
      return view('Modules\Sliders\Views\banners', $this->data);
    }

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

      $this->data['banners'] = $this->bannersModel->getAll();
      if($this->request->getMethod() == 'POST')
      {
        $rules = [
          'name' => ['label'=>'Banner Name', 'rules'=>'required'],
          '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,1024]'
          ],
      ];
        if($this->validate($rules))
        {
          $file1 = $this->request->getFile('photo');
  
            $newName4 = $file1->getRandomName();
            $file1->move(ROOTPATH . 'media/banners', $newName4);
            $nwn1 = base_url('/media/banners/').$newName4;
  
            $bannerData = [
              'name'          => $this->request->getVar("name"),
              'photo'           =>$nwn1,
              'description'     => $this->request->getVar("description"),
              ];
                
            if($this->bannersModel->save($bannerData))
            {
                session()->setTempdata('success', 'Banner added successfully', 3);
                return redirect()->to('administrator/sliders/all/banners');
            }else{
                session()->setTempdata('error', 'Banner NOT added', 3);
                return redirect()->to('administrator/sliders/all/banners');
            }
        }else{
          $this->data['validation'] = $this->validator;
        }
      }
      return view('Modules\Sliders\Views\banners', $this->data);
    }

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

      $this->data['banners'] = $this->bannersModel->getAll();
      $this->data['singleBanner'] = $this->bannersModel->where('id', $id)->first($id);
      return view('Modules\Sliders\Views\banners', $this->data);
    }

    public function updateBanner()
    {
      $this->data['title'] = "Edit Banner";
      $this->data['bcrumb'] = "Edit Banner";

      $id = $this->request->getVar('id');
      $this->data['banners'] = $this->bannersModel->getAll();
      if($this->request->getMethod() == 'POST')
      {
        $rules = [
          'name' => ['label'=>'Banner Name', 'rules'=>'required'],
          '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,1024]'
          ],
      ];
        if($this->validate($rules))
        {
          $file1 = $this->request->getFile('photo');
  
            $newName4 = $file1->getRandomName();
            $file1->move(ROOTPATH . 'media/banners', $newName4);
            $nwn1 = base_url('/media/banners/').$newName4;
  
            $bannerData = [
              'name'            => $this->request->getVar("name"),
              'photo'           =>$nwn1,
              'description'     => $this->request->getVar("description"),
              'url'             => $this->request->getVar("url"),
              ];
                
            if($this->bannersModel->update($id, $bannerData))
            {
                session()->setTempdata('success', 'Banner updated successfully', 3);
                return redirect()->to('administrator/sliders/all/banners');
            }else{
                session()->setTempdata('error', 'Banner NOT added', 3);
                return redirect()->to('administrator/sliders/all/banners');
            }
        }else{
          $this->data['validation'] = $this->validator;
        }
      }
      return view('Modules\Sliders\Views\banners', $this->data);
    }




}