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

class Dashboard extends CI_Controller
{

  function __construct()
  {
    parent::__construct();
    // $this->load->database();f
    $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 courses()
  {
    $data["courses"] = $this->common->readdatafromcollectionbetween("Courses");
    
    $this->template->template_render('courses', $data);
  }
  
  public function addcourse()
  {
    $data["categories"] = $this->common->readdatafromcollectionbetween("Categories");
    $data["teams"] = $this->common->readdatafromcollectionbetween("Teams");
    
    $this->template->template_render('addcourse', $data);
  }

  public function insertcourse()
	{
		
		$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();

    $videoUrl = '';
    if (!empty($_FILES)) {
      foreach($_FILES['video']['tmp_name'] as $key => $value) {
        if ($_FILES['video']['tmp_name'][$key] != '') {
            $name = "Videos/video" . rand() . time() . $_FILES['video']['name'][$key];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['video']['tmp_name'][$key]),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $videoUrl = 'https://storage.googleapis.com/athletes-edge-95ced.appspot.com/'.$name;
        }
      }
    }

    $data = [
      'categoryId' => $post['categoryId'],
      'title' => $post['title'],
      'createdDate' => time()*1000,
      'isPro' => $post['isPro']?true:false,
      'rating' => 0,
      'totalTime' => 3,
      'description' => $post['description'],
      'allowedFor' => $post['allowedFor'],
      'allowedTeams' => explode(",",$post['allowedTeams']),
      'questions' => $questionsArray,
      'video' => $videoUrl,
    ];

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

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

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

  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()
  {
    $data['freelancers'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userRole', '=', 'freelancer');
    $data['users'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userRole', '=', 'user');
    $data['Coaches'] = $this->common->readnumberofdocumentsincollection('Coaches');
    $data['totalUsers'] = $this->common->readnumberofdocumentsincollection('Users');
    $data['Teams'] = $this->common->readnumberofdocumentsincollection('Teams');
    $data['Courses'] = $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 categories()
	{

		$data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
		$this->template->template_render('categories', $data);
	}
	public function editbadges()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['category'] = $this->common->readdatadocument('badges', $id);
    $lol=$this->common->readdatafromcollectionwhereclause('Courses');
    foreach($lol as $j=>$k){
      $ja[$j]=$k['title'];
    }
    $data['courselist']=$ja;

    $chama=array();
    $bedges=$this->common->readdatafromcollectionwhereclause('badges');
    foreach($bedges as $b=>$c){
      if($c['courses'] !="" ){
        foreach($c['courses'] as $d=>$j){
          array_push($chama,$j);
        }
        
      }

    }
    $mycategory=$data['category']['courses'];
    foreach($mycategory as $k=>$j){
      $index = array_search($j, $chama);
if ($index !== false) {
    unset($chama[$index]);
    $chama = array_values($chama); // ['math', 'english', 'physics']
}
 
    }


   $data['alreadyselected']=$chama; 

		$this->template->template_render('addbadegs', $data);
	}
  public function badges()
	{

		$data['categories'] = $this->common->readdatafromcollectionwhereclause('badges');
    $ja=array();
    $lol=$this->common->readdatafromcollectionwhereclause('Courses');
    foreach($lol as $j=>$k){
      $ja[$j]=$k['title'];
    }
    $data['couselist']=$ja;



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

  public function addQuote()
	{

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

  public function addcategory()
	{

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

  public function addbadegs()
	{
    //$data['courselist']=$this->common->readdatafromcollectionwhereclause('Courses');
    $lol=$this->common->readdatafromcollectionwhereclause('Courses');
    foreach($lol as $j=>$k){
      $ja[$j]=$k['title'];
    }
    $data['courselist']=$ja;
    $chama=array();
    $bedges=$this->common->readdatafromcollectionwhereclause('badges');
    foreach($bedges as $b=>$c){
      if($c['courses'] !=""){
        foreach($c['courses'] as $d=>$j){
          array_push($chama,$j);
        }
        
      }

    }

   $data['alreadyselected']=$chama; 
    //echo "<pre>";
    //print_r($chama);
    //echo "</pre>";
		$this->template->template_render('addbadegs',$data);
	}

  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 insertbadges()
	{
		
		$post = $this->input->post();
    $data['title'] = $post['title'];
    $data['courses'] = $post['courses'];

    $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('badges', $data);

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

    redirect(base_url('dashboard/badges'));		
	}
  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 updatebadge()
	{
    $post = $this->input->post();
    $data['title'] = $post['title'];
    $data['courses'] = $post['courses'];

    $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('badges', $post['id'], $data);

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

    redirect(base_url('dashboard/badges'));
	}
	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'));
	}
  public function deletebadge()
	{
    $id = $this->uri->segment(3);

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

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

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