<?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 index()
  {
    $data['foodtypes'] = $this->common->readnumberofdocumentsincollection('FoodTypes');
    $data['allergytypes'] = $this->common->readnumberofdocumentsincollection('Allergies');
   
    $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 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 quotes()
	{

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

  public function plans()
	{

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

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

  public function insertplan()
	{
		
		$post = $this->input->post();
    $data['title'] = $post['title'];
    $data['type'] = $post['type'];
    $data['price'] = (float)$post['price'];


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

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

    redirect(base_url('dashboard/plans'));		
	}
	public function editplan()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['plan'] = $this->common->readdatadocument('Plans', $id);
		$this->template->template_render('addplan', $data);
	}

	public function updateplan()
	{
    $post = $this->input->post();
    $data['title'] = $post['title'];
    $data['type'] = $post['type'];
    $data['price'] = (float)$post['price'];

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

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

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

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

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

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

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

  public function foodtypes()
	{

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

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

  public function insertfoodtype()
	{
		
		$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/' . $defaultBucket->name() . '/' . $name;
        }
    }
    $data['icon'] = $iconUrl;


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

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

    redirect(base_url('dashboard/foodtypes'));		
	}
	public function editfoodtype()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['foodtype'] = $this->common->readdatadocument('FoodTypes', $id);
		$this->template->template_render('addfoodtype', $data);
	}

	public function updatefoodtype()
	{
    $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/' . $defaultBucket->name() . '/' . $name;
              $data['icon'] = $iconUrl;
            }
    }

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

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

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

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

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

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

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

public function allergies()
{

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

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

  public function insertallergy()
	{
		
		$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/' . $defaultBucket->name() . '/' . $name;
        }
    }
    $data['icon'] = $iconUrl;


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

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

    redirect(base_url('dashboard/allergies'));		
	}
	public function editallergy()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['allergy'] = $this->common->readdatadocument('Allergies', $id);
		$this->template->template_render('addallergy', $data);
	}

	public function updateallergy()
	{
    $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/' . $defaultBucket->name() . '/' . $name;
              $data['icon'] = $iconUrl;
            }
    }

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

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

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

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

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

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

    redirect(base_url('dashboard/allergies'));
	}
//dietaryrestrictions
public function dietaryrestrictions()
{

  $data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
  $this->template->template_render('dietaryrestrictions', $data);
} 
public function setting()
	{

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


  public function adddietaryrestrictions()
	{

		$this->template->template_render('adddietaryrestrictions');
	}
  public function editdietaryrestrictions()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['category'] = $this->common->readdatadocument('Categories', $id);
		$this->template->template_render('adddietaryrestrictions', $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'));
	}

  

}