<?php

namespace Modules\Downloads\Controllers;

use App\Controllers\Auth\AuthController;

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

  }

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

    $this->data['downloads'] = $this->downloadsModel->getAll();
    return view('Modules\Downloads\Views\all', $this->data);

  }

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

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

    $this->data['tags'] = $this->tagsModel->getAll();
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->downloadscategoryModel->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]'
        ],
      ];
      $fileRules = [
        'file' => [
            'label' => 'File',
            'rules' => 'uploaded[file]'
                . '|max_size[file,5024]'
        ],
      ];
      if($this->validate($rules))
      {
        $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($this->request->getVar('title'))));
        $doc = $this->request->getFile('file');
        $file1 = $this->request->getFile('photo');

        //Upload Document file
        if($this->validate($fileRules)){
          $size = $doc->getSizeByUnit('kb');
          $ext = $doc->guessExtension();
          $newDoc4 = $doc->getClientName();
          $doc->move(ROOTPATH . 'media/downloads/files', $newDoc4);
          $doc4 = base_url('media/downloads/files/').$newDoc4;

          if($file1 != "")
          {
              if($this->validate($photoRules))
              { 
                  $newName4 = $file1->getRandomName();
                  $file1->move(ROOTPATH . 'media/downloads/photos', $newName4);
                  $nwn1 = base_url('/media/downloads/photos/').$newName4;

                  $postData = [
                    'title'           => $this->request->getVar("title"),
                    'alias'           => $slug,
                    'photo'           =>$nwn1,
                    'file'            => $doc4,
                    'file_type'       => $ext,
                    'file_size'       => $size,
                    'content'         => $this->request->getVar("content"),
                    'excerpt'         => $this->request->getVar("excerpt"),
                    'ordering'        => '1',
                    'category_id'     => $this->request->getVar("category_id"),
                    'status'          => $this->request->getVar("status"), 
                    'access'          => $this->request->getVar("access"),
                    'published_date'          => $this->request->getVar("published_date"),
                    'author'          => $this->request->getVar("author"),
                    'urls'            => $this->request->getVar("urls"),
                    'metadesc'        => $this->request->getVar("metadesc"),
                    'metakey'         => $this->request->getVar("metakey"),
                    'created_by'      => $this->userdata->user_id,
                ];
                
                $results = $this->downloadsModel->save($postData);
              }else{
                $this->data['validation'] = $this->validator;
              }
          }else{

            $postData = [
              'title'          => $this->request->getVar("title"),
              'alias'          => $slug,
              'file'            => $doc4,
              'file_type'       => $ext,
              'file_size'       => $size,
              'content'         => $this->request->getVar("content"),
              'excerpt'         => $this->request->getVar("excerpt"),
              'ordering'        => '1',
              'category_id'     => $this->request->getVar("category_id"),
              'status'          => $this->request->getVar("status"), 
              'access'          => $this->request->getVar("access"),
              'published_date'          => $this->request->getVar("published_date"),
              'author'          => $this->request->getVar("author"),
              'urls'            => $this->request->getVar("urls"),
              'metadesc'        => $this->request->getVar("metadesc"),
              'metakey'         => $this->request->getVar("metakey"),
              'created_by'      => $this->userdata->user_id,
              ];
            
              $results = $this->downloadsModel->save($postData);
          }

          if($results)
            {
              $downloadId = $this->downloadsModel->getInsertID();
              // Save Tags attached to the Post
              $tags = $this->request->getVar('tags');
              if($tags){
                foreach ($tags as $tag) {
                  $tagPostData = [
                      'tag_id' => $tag,
                      'download_id' => $downloadId
                  ];
                  $this->downloadstagsModel->save($tagPostData);
                } 
              }
              
              //Save & Send Notification
              $title = $this->request->getVar("title");
              $adminmessage = 'New Download:  <strong>'.$title.'</strong> has been uploaded successfully';
              $notificationType = 'posts';
              $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

              session()->setTempdata('success', 'Download added successfully', 3);
              return redirect()->to('administrator/downloads');
            }else{
                session()->setTempdata('error', 'Download NOT added', 3);
                return redirect()->to('administrator/downloads/add');
            }

        }else{
            session()->setTempdata('error', 'File is to big. Must be less than 5MB', 3);
            return redirect()->to('administrator/downloads/add');
        }
      }else{
        session()->setTempdata('error', 'Download Title can not be empty', 3);
        return redirect()->to('administrator/downloads/add');
      }
    }

    return view('Modules\Downloads\Views\add_download', $this->data);
  }
  public function editDownload($id = null)
  {
    $this->data['title'] = "Edit Download";
    $this->data['bcrumb'] = "Edit Download";

    //$this->data['postTags'] = $this->downloadstagsModel->getDownloadTags($id);
    $this->data['authors'] = $this->usersModel->getAll();
    $this->data['categories']=$this->downloadscategoryModel->getAll();
    $this->data['singleDownload'] = $this->downloadsModel->where('id', $id)->first($id);

    return view('Modules\Downloads\Views\edit_download', $this->data);
  }
  public function updateDownload()
{
    $this->data['title'] = "Edit Post";
    $this->data['bcrumb'] = "Edit Post";

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

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

        $rules = [
            'title' => ['label' => 'Post Title', 'rules' => 'required'],
        ];

        if ($this->validate($rules)) {

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

            $postData = [
                'title'         => $this->request->getVar("title"),
                'alias'         => $slug,
                'content'       => $this->request->getVar("content"),
                'excerpt'         => $this->request->getVar("excerpt"),
                'ordering' => $this->request->getVar("ordering"),
                'category_id' => $this->request->getVar("category_id"),
                'status' => $this->request->getVar("status"),
                'access' => $this->request->getVar("access"),
                'published_date'          => $this->request->getVar("published_date"),
              'author'          => $this->request->getVar("author"),
                'urls' => $this->request->getVar("urls"),
                'metadesc' => $this->request->getVar("metadesc"),
                'metakey' => $this->request->getVar("metakey"),
                'created_by' => $this->userdata->user_id,
            ];

            $doc = $this->request->getFile('file');
            $file1 = $this->request->getFile('photo');

            if ($doc->isValid()) {
                // Upload Document file
                $fileRules = [
                    'file' => [
                        'label' => 'File',
                        'rules' => 'uploaded[file]|max_size[file,5024]',
                    ],
                ];

                if ($this->validate($fileRules)) {
                    $size = $doc->getSizeByUnit('kb');
                    $ext = $doc->guessExtension();
                    $newDoc4 = $doc->getClientName();
                    $doc->move(ROOTPATH . 'media/downloads/files', $newDoc4);
                    $doc4 = base_url('media/downloads/files/') . $newDoc4;
                    $postData['file'] = $doc4;
                } else {
                    session()->setTempdata('error', 'File is too big. Must be less than 5MB', 3);
                    return redirect()->to('administrator/downloads/edit/' . $id . '-' . $slug);
                }
            }

            if ($file1->isValid()) {
                // Upload Image file
                $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($photoRules)) {
                    $newName4 = $file1->getRandomName();
                    $file1->move(ROOTPATH . 'media/downloads/photos', $newName4);
                    $nwn1 = base_url('/media/downloads/photos/') . $newName4;
                    $postData['photo'] = $nwn1;
                } else {
                    $this->data['validation'] = $this->validator;
                }
            }

            //Saving More Tags on Download
            $tags = $this->request->getVar('tags');
            if($tags){
              foreach ($tags as $tag) {
                $tagPostData = [
                    'tag_id' => $tag,
                    'download_id' => $id,
                ];
                $this->downloadstagsModel->save($tagPostData);
              } 
            }
            
            

            if ($this->downloadsModel->update($id, $postData)) {
              //Save & Send Notification
                $title = $this->request->getVar("title");
                $adminmessage = 'New Download:  <strong>'.$title.'</strong> has been updated successfully';
                $notificationType = 'posts';
                $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

                session()->setTempdata('success', 'Download updated successfully', 3);
                return redirect()->to('administrator/downloads');
            } else {
                session()->setTempdata('error', 'Download NOT updated', 3);
                return redirect()->to('administrator/downloads/edit/' . $id . '-' . $slug);
            }
        } else {
            $this->data['validation'] = $this->validator;
        }
    }

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

  public function delDownload($id)
  {
    $this->downloadsModel->where('id', $id)->delete($id);
    if($this->request->isAJAX())
    {
      $response = [
        'error' => true,
        'msg' =>'Download deleted successfully',	   
      ];
      return $this->response->setJSON($response);
    }else{
      session()->setFlashdata('success', 'Download deleted successfully', 3);
			return redirect()->to('administrator/downloads');
    }
  }
/**========================================================================
 * DOWNLOAD CATEGORY /ADD/EDIT/DELETE
 ==========================================================================*/
  public function downloadsCategories()
  {    
    // display header information
		$this->data['title'] = "Downloads Categories";
    $this->data['bcrumb'] = "Downloads Categories";

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

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

  public function addCategory()
  {    
    $this->data['downloads_categories'] = $this->downloadscategoryModel->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'))));
          $masterCategory = $this->request->getVar("parent_category_id");

          if($masterCategory){ 
            $productData = [
              'name'                => $this->request->getVar("name"),
              'alias'               => $slug,
              'description'         => $this->request->getVar("description"),
              'parent_category_id'   => $masterCategory,
              'created_by'          => $this->userdata->user_id,
            ];
            $results =  $this->downloadscategoryModel->save($productData);
          }else{
            $productData = [
              'name'                => $this->request->getVar("name"),
              'alias'               => $slug,
              'description'         => $this->request->getVar("description"),
              'parent_category_id'  => NULL,
              'created_by'          => $this->userdata->user_id,
            ];
            $results =  $this->downloadscategoryModel->save($productData);
          }
          if($results)
          {
              session()->setTempdata('success', 'Category added successfully', 3);
              return redirect()->to('administrator/downloads/categories');
          }else{
              session()->setTempdata('error', 'Category NOT added', 3);
              return redirect()->to('administrator/downloads/categories');
          }
      }else{
        session()->setTempdata('error', 'Category Name can not be empty', 3);
        return redirect()->to('administrator/downloads/categories');
      }
    }
    return view('Modules\Posts\Views\category', $this->data);
  }
  public function editCategory($id = null)
  {
    $this->data['title'] = "Downloads  Categories";
    $this->data['bcrumb'] = "Downloads  Categories";

    $this->data['downloads_categories'] = $this->downloadscategoryModel->getAll();
    $categories = $this->downloadscategoryModel->getOtherCategories();
    $masterCategories = [];
    foreach ($categories as $cat) {
        $masterCategory = $this->downloadscategoryModel->getParentCategory($cat->id);
        if ($masterCategory !== null) {
            $masterCategories[$cat->id] = $masterCategory->name;
        }
    }
    $this->data['masterCategories'] = $masterCategories;
    $this->data['singleCategory'] = $this->downloadscategoryModel->where('id', $id)->first($id);

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

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