<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Dashboard extends CI_Controller
{

  function __construct()
  {
    parent::__construct();
    // $this->load->database();
    $this->load->helper('url');
    $this->load->library('session');
    $this->load->model('dashboard_model');
    $this->load->model('common');
  }
  
  public function settings()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('settings', $data);
  }

  public function coauthors()
  {
    $data["coauthors"] = $this->common->readdatafromcollectionbetween("CoAuthors");
    
    $this->template->template_render('coauthors', $data);
  }
  
  public function addcoauthor()
  {
    
    $this->template->template_render('addcoauthor');
  }
  
  public function insertcoauthor()
	{
    
    $userId = $_SESSION['session_data']['userId'];
    $post = $this->input->post();
    $data['name'] = $post['name'];
    $data['details'] = $post['details'];
    $data['authorId'] = $userId;

    
    $response = $this->common->addnewdatamodel('CoAuthors', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Co-Author added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/coauthors'));		
	}

  public function editcoauthor()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['coauthor'] = $this->common->readdatadocument('CoAuthors', $id);
    
		$this->template->template_render('addcoauthor', $data);
	}

  public function updatecoauthor()
	{
    $post = $this->input->post();
    $data['name'] = $post['name'];
    $data['details'] = $post['details'];

		$response = $this->common->updatedatamodel('CoAuthors', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Co-Author updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/coauthors'));
	}

  public function deletecoauthor()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('CoAuthors', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Co-Author deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/coauthors'));
	}

  public function narrators()
  {
    $data["narrators"] = $this->common->readdatafromcollectionbetween("Narrators");
    
    $this->template->template_render('narrators', $data);
  }
  
  public function addnarrator()
  {
    
    $this->template->template_render('addnarrator');
  }
  
  public function insertnarrator()
	{
    
    $userId = $_SESSION['session_data']['userId'];
    $post = $this->input->post();
    $data['name'] = $post['name'];
    $data['details'] = $post['details'];
    $data['authorId'] = $userId;

    
    $response = $this->common->addnewdatamodel('Narrators', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Narrator added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/narrators'));		
	}

  public function editnarrator()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['narrator'] = $this->common->readdatadocument('Narrators', $id);
    
		$this->template->template_render('addnarrator', $data);
	}

  public function updatenarrator()
	{
    $post = $this->input->post();
    $data['name'] = $post['name'];
    $data['details'] = $post['details'];

		$response = $this->common->updatedatamodel('Narrators', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Narrator updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/narrators'));
	}

  public function deletenarrator()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Narrators', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Narrator deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/narrators'));
	}

  public function publishers()
  {
    $data["publishers"] = $this->common->readdatafromcollectionbetween("Publishers");
    
    $this->template->template_render('publishers', $data);
  }
  
  public function addpublisher()
  {
    
    $this->template->template_render('addpublisher');
  }
  
  public function insertpublisher()
	{
    
    $userId = $_SESSION['session_data']['userId'];
    $post = $this->input->post();
    $data['name'] = $post['name'];
    $data['details'] = $post['details'];
    $data['authorId'] = $userId;

    
    $response = $this->common->addnewdatamodel('Publishers', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Publisher added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/publishers'));		
	}

  public function editpublisher()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['publisher'] = $this->common->readdatadocument('Publishers', $id);
    
		$this->template->template_render('addpublisher', $data);
	}

  public function updatepublisher()
	{
    $post = $this->input->post();
    $data['name'] = $post['name'];
    $data['details'] = $post['details'];

		$response = $this->common->updatedatamodel('Publishers', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Publisher updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/publishers'));
	}

  public function deletepublisher()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Publishers', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Publisher deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/publishers'));
	}

  public function courses()
  {
    $data["courses"] = array();
    //$this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('courses', $data);
  }
  //legal
  public function legal()
  {
    $data["courses"] = array();
    //$this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('legal', $data);
  }
  public function support()
  {
    $data["courses"] = array();
    //$this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('support', $data);
  }
  //promotions
  public function promotions()
  {
    $data["courses"] = array();
    //$this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('promotions', $data);
  } 
  public function earning()
  {
    $data["courses"] = array();
    //$this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('earning', $data);
  }

  public function books()
  {
    $data["books"] = $this->common->readdatafromcollectionbetween("Books");
    //$this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('books', $data);
  }
  public function addbook()
  {
    $data["categories"] = $this->common->readdatafromcollectionbetween("Categories");
    $data["authors"] = $this->common->readdatafromcollectionbetween("CoAuthors");
    $data["narrators"] = $this->common->readdatafromcollectionbetween("Narrators");
    $data["publishers"] = $this->common->readdatafromcollectionbetween("Publishers");
    
    $this->template->template_render('addbook', $data);
  }

  public function insertbook()
	{
		// echo('<pre>');
    // print_r($_FILES);
		// echo('</pre>');
    // die;
    $authorId = $_SESSION['session_data']['userId'];
    if(!$authorId){
      die('Access denied');
    }
		
    $post = $this->input->post();
    
    // $answers = $post['answer'];
    // $questionsArray = array();
    // foreach($post['question'] as $key => $question) {
    //   $questionsArray[$key]['question'] = $question[0];
    //   $theseAnswers = $answers[$key];
    //   foreach($theseAnswers as $answer) {
    //     $questionsArray[$key]['answers'][] = $answer;
    //   }
    // }
    
    
    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $image = '';
    if (!empty($_FILES)) {
        if ($_FILES['image']['tmp_name'] != '') {
            $name = "Books/featuredimage-" . rand() . time() . $_FILES['image']['name'];
            $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $image = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
        }
    }

    $artworkFiles = array();
    if (!empty($_FILES['artwork_file'])) {
      foreach($_FILES['artwork_file']['tmp_name'] as $key => $value) {
        if ($_FILES['artwork_file']['tmp_name'][$key] != '') {
            $name = "Books/artworkFile-".$key . rand() . time() . $_FILES['artwork_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['artwork_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $artwork_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $artwork_name = $post['artwork_name'][$key];
              $artworkFiles[$key] = ['file' => $artwork_file, 'name' => $artwork_name];
        }
      }
    }

    $frontMatters = array();
    if (!empty($_FILES['front_matter_text_file'])) {
      foreach($_FILES['front_matter_text_file']['tmp_name'] as $key => $value) {
        if ($_FILES['front_matter_text_file']['tmp_name'][$key] != '') {
            $name = "Books/front_matter_text_file-".$key . rand() . time() . $_FILES['front_matter_text_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['front_matter_text_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $front_matter_text_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $front_matter_name = $post['front_matter_name'][$key];
              $frontMatters[$key] = ['textFile' => $front_matter_text_file, 'name' => $front_matter_name];
        }
      }

      foreach($_FILES['front_matter_sound_file']['tmp_name'] as $key => $value) {
        if ($_FILES['front_matter_sound_file']['tmp_name'][$key] != '') {
            $name = "Books/front_matter_sound_file-".$key . rand() . time() . $_FILES['front_matter_sound_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['front_matter_sound_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $front_matter_sound_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $frontMatters[$key]['soundFile'] = $front_matter_sound_file;
        }
      }
    }

    $bodyMatters = array();
    if (!empty($_FILES['body_matter_text_file'])) {
      foreach($_FILES['body_matter_text_file']['tmp_name'] as $key => $value) {
        if ($_FILES['body_matter_text_file']['tmp_name'][$key] != '') {
            $name = "Books/body_matter_text_file-".$key . rand() . time() . $_FILES['body_matter_text_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['body_matter_text_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $body_matter_text_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $body_matter_name = $post['body_matter_name'][$key];
              $bodyMatters[$key] = ['textFile' => $body_matter_text_file, 'name' => $body_matter_name];
        }
      }

      foreach($_FILES['body_matter_sound_file']['tmp_name'] as $key => $value) {
        if ($_FILES['body_matter_sound_file']['tmp_name'][$key] != '') {
            $name = "Books/body_matter_sound_file-".$key . rand() . time() . $_FILES['body_matter_sound_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['body_matter_sound_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $body_matter_sound_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $bodyMatters[$key]['soundFile'] = $body_matter_sound_file;
        }
      }
    }

    $backMatters = array();
    if (!empty($_FILES['back_matter_text_file'])) {
      foreach($_FILES['back_matter_text_file']['tmp_name'] as $key => $value) {
        if ($_FILES['back_matter_text_file']['tmp_name'][$key] != '') {
            $name = "Books/back_matter_text_file-".$key . rand() . time() . $_FILES['back_matter_text_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['back_matter_text_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $back_matter_text_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $back_matter_name = $post['back_matter_name'][$key];
              $backMatters[$key] = ['textFile' => $back_matter_text_file, 'name' => $back_matter_name];
        }
      }

      foreach($_FILES['back_matter_sound_file']['tmp_name'] as $key => $value) {
        if ($_FILES['back_matter_sound_file']['tmp_name'][$key] != '') {
            $name = "Books/back_matter_sound_file-".$key . rand() . time() . $_FILES['back_matter_sound_file']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['back_matter_sound_file']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $back_matter_sound_file = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
              $backMatters[$key]['soundFile'] = $back_matter_sound_file;
        }
      }
    }

    $data = [
      'authorId' => $authorId,
      'categoryId' => $post['categoryId'],
      'title' => $post['title'],
      'createdDate' => time()*1000,
      'description' => $post['description'],
      'coauthors' => $post['coauthors'],
      'narrators' => $post['narrators'],
      'publishers' => $post['publishers'],
      'fileType' => $post['fileType'],
      'bookType' => $post['bookType'],
      'image' => $image,
      'artworkFiles' => $artworkFiles,
      'frontMatters' => $frontMatters,
      'bodyMatters' => $bodyMatters,
      'backMatters' => $backMatters,
    ];

    $response = $this->common->addnewdatamodel('Books', $data);

    if ($response) {
      echo('done');
      $this->session->set_flashdata('successmessage', 'Book added successfully..');
    } else {
      echo('not done');
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/books'));		
	}

  public function bookchapters($id)
  {
    $data["chapters"] = $this->common->readdatafromcollectionbetween("Chapters","bookId","=",$id);
    $data["bookId"] = $id;
    
    $this->template->template_render('chapters', $data);
  }

  public function insertchapter()
	{
    
    // $userId = $_SESSION['session_data']['userId'];
    // $data['authorId'] = $userId;

    $post = $this->input->post();
    $data['bookId'] = $post['bookId'];
    if(!$data['bookId']){
      redirect(base_url('dashboard/books'));
      exit;
    }
    $data['title'] = $post['title'];
    
    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $pdfFile = '';
    if (!empty($_FILES)) {
      if ($_FILES['pdf']['tmp_name'] != '') {
        $name = "Books/chapter-pdf-" . rand() . time() . $_FILES['pdf']['name'];
        $defaultBucket->upload(
            file_get_contents($_FILES['pdf']['tmp_name']),
            [
              'name' => $name,
              'predefinedAcl' => 'publicRead'
            ]
          );
          $pdfFile = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
      }
    }

    $data['pdfFile'] = $pdfFile;

    $audioFile = '';
    if (!empty($_FILES)) {
      if ($_FILES['audio']['tmp_name'] != '') {
        $name = "Books/chapter-audio-" . rand() . time() . $_FILES['audio']['name'];
        $defaultBucket->upload(
            file_get_contents($_FILES['audio']['tmp_name']),
            [
              'name' => $name,
              'predefinedAcl' => 'publicRead'
            ]
          );
          $audioFile = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
      }
    }

    $data['audioFile'] = $audioFile;

    
    $response = $this->common->addnewdatamodel('Chapters', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Chapter added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/bookchapters/'.$data['bookId']));		
	}

  public function updatechapter()
	{
    $post = $this->input->post();
    $bookId = $post['bookId'];
    $chapterId = $post['test'];
    // echo($chapterId);die;
    
    $data['title'] = $post['title'];

    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $pdfFile = '';
    if (!empty($_FILES)) {
      if ($_FILES['pdf']['tmp_name'] != '') {
        $name = "Books/chapter-pdf-" . rand() . time() . $_FILES['pdf']['name'];
        $defaultBucket->upload(
            file_get_contents($_FILES['pdf']['tmp_name']),
            [
              'name' => $name,
              'predefinedAcl' => 'publicRead'
            ]
          );
          $pdfFile = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
          $data['pdfFile'] = $pdfFile;
      }
    }


    $audioFile = '';
    if (!empty($_FILES)) {
      if ($_FILES['audio']['tmp_name'] != '') {
        $name = "Books/chapter-audio-" . rand() . time() . $_FILES['audio']['name'];
        $defaultBucket->upload(
            file_get_contents($_FILES['audio']['tmp_name']),
            [
              'name' => $name,
              'predefinedAcl' => 'publicRead'
            ]
          );
          $audioFile = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $name;
          $data['audioFile'] = $audioFile;
      }
    }

    $response = $this->common->updatedatamodel('Chapters', $chapterId, $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Chapter updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    
    redirect(base_url('dashboard/bookchapters/'.$bookId));
	}
  function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}
  public function getlen(){
    
    $file = 'https://storage.googleapis.com/audiobooks-c7875.firebasestorage.app/Books/chapter-audio-11152854291745924275sample-15s.mp3';
    
    if ($this->remoteFileExists($file)){
      
      $contents = file_get_contents($file);
      $make_hexa = hexdec(bin2hex(substr($contents,strlen($contents)-3)));
      if (strlen($contents) > $make_hexa){
          $pre_duration = hexdec(bin2hex(substr($contents,strlen($contents)-$make_hexa,3))) ;
          $post_duration = $pre_duration/1000;
          $timehours = $post_duration/3600;
          $timeminutes =($post_duration % 3600)/60;
          $timeseconds = ($post_duration % 3600) % 60;
          $timehours = explode(".", $timehours);
          $timeminutes = explode(".", $timeminutes);
          $timeseconds = explode(".", $timeseconds);
          $duration = $timehours[0]. ":" . $timeminutes[0]. ":" . $timeseconds[0];}
          echo 'du-'.$duration;
      } else {
          echo 'false';
      }
  }
  private function getDurationOfWav($path) {
      $cmd = "ffmpeg -i " . escapeshellarg($path) . " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//";
      return exec($cmd);
  }

  private function getDurationOfWavInMs($path) {
      $time = $this->getDurationOfWav($path);
      list($hms, $milli) = explode('.', $time);
      list($hours, $minutes, $seconds) = explode(':', $hms);
      $totalSeconds = ($hours * 3600) + ($minutes * 60) + $seconds;
      return ($totalSeconds * 1000) + $milli;
  }




  public function coaches()
  {
    $data["reelzz"] = [];
    
    
    $this->template->template_render('coaches', $data);
  }
  public function contactus()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('contactus', $data);
  }
  public function resource()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('resource', $data);
  }
  public function appointment()
  {
    $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");
    
    
    $this->template->template_render('appointment', $data);
  }

  public function questions()
  {
    if(!isset($_SESSION['type'])){

      $_SESSION['type'] = 'morning';
    }

    $type = $this->uri->segment(3);
    if($type){
      $_SESSION['type'] = $type;
    }
    $data["questions"] = $this->common->readdatacollection("Journal", "Questions", $_SESSION['type']);
    
    
    $this->template->template_render('questions', $data);
  }

  public function addQuestion()
  {
    $this->template->template_render('addQuestion');
  }

  public function saveQuestion()
  {
    $post = $this->input->post();
    
    if($post['type'] == 'Checkbox'){
      
      $options = $post['options'];
      unlink($post['options']);
  
      $optionsMap = [];

      foreach($options as $option){
        $optionsMap[$option] = false;
      }
      $post['options'] = $optionsMap;
    }
    if($post['count']){

      $post['count'] = (int)$post['count'];
    }

    if($post['type'] == 'Simple'){
  
      $post['count'] = 1;
      
    }

    if($post['type'] == 'Number'){
  
      $answers = [];

      for($i = 0; $i < $post['count']; $i++){
        $answers[] = '';
      }

      $post['answers'] = $answers;
    }

    $id = time();
    $this->common->adddatamodelnexted("Journal", $_SESSION['type'], "Questions", $id, $post);
    redirect(base_url('dashboard/questions'));
  }
  
//nexteddeletedatamodel
  public function saveSettings($id)
  {
    $post = $this->input->post();
    $response = $this->common->updatedatamodel("Settings", $id, $post);
    if($response) {
				$this->session->set_flashdata('successmessage', 'Settings has been updated');
    }else{
			$this->session->set_flashdata('warningmessage', 'Error! Some issue with firebase.Please try again');
    }

    redirect(base_url('dashboard/settings'));
  }



  public function index()
  {
    redirect(base_url('dashboard/courses'));
    $data['freelancers'] = 1;
//$this->common->readnumberofdocumentsincollectionbetween('Users', 'userRole', '=', 'freelancer');
    $data['users'] = 1;
//$this->common->readnumberofdocumentsincollectionbetween('Users', 'userRole', '=', 'user');
    $data['Coaches'] =1;
// $this->common->readnumberofdocumentsincollection('Coaches');
    $data['totalUsers'] = 1;//$this->common->readnumberofdocumentsincollection('Users');
    $data['Teams'] = 1;
//$this->common->readnumberofdocumentsincollection('Teams');
    $data['Courses'] = 1;
//$this->common->readnumberofdocumentsincollection('Courses');
   
    $users = $this->common->readdatafromcollectionwhereclause("Users", 'userRole', '=', 'user');
    $data['users']=count($users);
      foreach ($users as $key => $user) {
        $timestamps[$key]    = $user['createdDate'];
    }
    array_multisort($timestamps, SORT_ASC, $users);
    $labels = array();

    $labels[0] = date('F', strtotime(date('F')." - 3 months"));
    for($i =1; $i<=5; $i++) {
      $timestamp = strtotime($labels[$i-1].' + 1 month');
      $labels[$i] = date('F', $timestamp);
    }
    $labelStr = '';
    foreach($labels as $label) {
      $labelStr .= '"'.$label.'", ';
    }
    
    $data['labelStr'] = $labelStr;
    $dataStr = '';
    for($i =0; $i<count($labels); $i++) {
      $num = 0;
      foreach($timestamps as $timestamp) {
        if($labels[$i] == date('F', $timestamp/1000)) {
          $num += 0.2;
        }
      }
      $dataStr .= $num.',';
    }
    $data['dataStr'] = $dataStr;

   
    $this->template->template_render('dashboard', $data);
  }

  public function quotes()
	{

		$data['quotes'] = $this->common->readdatafromcollectionwhereclause('Quotes');
		$this->template->template_render('quotes', $data);
	}

  public function orders()
	{

		$data['categories'] = array();
    //$this->common->readdatafromcollectionwhereclause('Categories');
		$this->template->template_render('categories', $data);
	}

  public function addQuote()
	{

		$this->template->template_render('addquote');
	}

  public function addcategory()
	{

		$this->template->template_render('addcategory');
	}

  public function insertquote()
	{
		
		$post = $this->input->post();
    $data['quote'] = $post['quote'];
    $data['createdDate'] = time()*1000;
    $data['isActive'] = true;
    $response = $this->common->addnewdatamodel('Quotes', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Quote added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/quotes'));		
	}

  public function editquote()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['quote'] = $this->common->readdatadocument('Quotes', $id);
    if(!$data['quote']){
      redirect(base_url('dashboard/quotes'));
    }
		$this->template->template_render('editquote', $data);
	}

  public function updatequote()
	{
    $post = $this->input->post();
    $data['quote'] = $post['quote'];

		$response = $this->common->updatedatamodel('Quotes', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Quote updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/quotes'));
	}

  public function deletequote()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Quotes', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Quote deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/quotes'));
	}

  public function deleteCourse()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Courses', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Course deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/courses'));
	}

  public function deleteQuestion()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->nexteddeletedatamodel('Journal', $_SESSION['type'], 'Questions', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Question deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/questions'));
	}

  public function insertcategory()
	{
		
		$post = $this->input->post();
    $data['title'] = $post['title'];

    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();

    $iconUrl = '';
    if (!empty($_FILES)) {
        if ($_FILES['icon']['tmp_name'] != '') {
            $name = "Icons/ico" . rand() . time() . $_FILES['icon']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['icon']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $iconUrl = 'https://storage.googleapis.com/athletes-edge-95ced.appspot.com/'.$name;
        }
    }
    $data['icon'] = $iconUrl;


    $response = $this->common->addnewdatamodel('Categories', $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));		
	}
	public function editcategory()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['category'] = $this->common->readdatadocument('Categories', $id);
		$this->template->template_render('addcategory', $data);
	}

	public function updatecategory()
	{
    $post = $this->input->post();
    $data['title'] = $post['title'];

    $firebase = $this->firebase->init();
    $storage = $firebase->createStorage();
    $defaultBucket = $storage->getBucket();


    if (!empty($_FILES)) {
        if ($_FILES['icon']['tmp_name'] != '') {
            $name = "Icons/ico" . rand() . time() . $_FILES['icon']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['icon']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $iconUrl = 'https://storage.googleapis.com/athletes-edge-95ced.appspot.com/'.$name;
              $data['icon'] = $iconUrl;
            }
    }

		$response = $this->common->updatedatamodel('Categories', $post['id'], $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
	}

  public function deletecategory()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->nexteddeletedatamodel('Categories', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
	}

}