<?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');
    $this->load->model('order_model');
  }
  
  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['allcoaches'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userRole', '=', 'coach');
    $data['users'] = $this->common->readnumberofdocumentsincollectionbetween('Users', 'userRole', '=', 'user');
    
    $data['allusers'] = $this->common->readnumberofdocumentsincollection('Users');
    $data['totalNews'] = $this->common->readnumberofdocumentsincollection('News');
   
    $this->template->template_render('dashboard', $data);
  }

  public function servicetype()
	{

		$data['quotes'] = $this->common->readdatafromcollectionwhereclause('ServiceTypes');
		$this->template->template_render('servicetype', $data);
	}
public function revenue()
	{

    $data=array();
		$this->template->template_render('revenue', $data);
	}

  public function categories()
	{

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

  public function addservicetype()
	{

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

  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['name'] = $post['name'];
    $data['id'] = time();
    $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 updatecategory()
	{
		$post = $this->input->post();
    $data['name'] = $post['name'];
    $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 insertservicetype()
	{
		
		$post = $this->input->post();
    $data['name'] = $post['name'];

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

    $iconUrl = '';
    if (!empty($_FILES)) {
        if ($_FILES['image']['tmp_name'] != '') {
            $name = "ServiceTypes/image" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $imageUrl = $uploadedFile->info()['mediaLink'];
        }
    }
    $data['image'] = $imageUrl;
    $data['id'] = time();


    $response = $this->common->adddatamodel('ServiceTypes', $data['id'], $data);

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

    redirect(base_url('dashboard/servicetype'));		
	}
	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 editservicetype()
	{
		$id = $this->uri->segment(3);
    $data['id'] = $id;
		$data['servicetype'] = $this->common->readdatadocument('ServiceTypes', $id);
		$this->template->template_render('addservicetype', $data);
	}

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

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


    if (!empty($_FILES)) {
        if ($_FILES['image']['tmp_name'] != '') {
            $name = "ServiceTypes/image" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $imageUrl = $uploadedFile->info()['mediaLink'];
              $data['image'] = $imageUrl;
            }
    }

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

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

    redirect(base_url('dashboard/servicetype'));
	}
  public function deleteservicetype()
	{
		$id = $this->uri->segment(3);
		$response = $this->common->deletedatamodel('ServiceTypes', $id);
		if ($response) {
      $this->session->set_flashdata('successmessage', 'Service Type deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

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

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

		$response = $this->common->deletedatamodel('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 vendors()
	{

   $this->template->template_render('vendors');
	}
    public function products()
	{
    $data['products'] = $this->common->readdatafromcollectionwhereclause('Products');
   $this->template->template_render('products_management', $data);
	}
	public function viewProduct($id)
	{
		$data['id'] = $id;
		$data['product'] = $this->common->readdatadocument('Products', $id);
		$this->template->template_render('products', $data);
	}
     public function serviceprovider()
	{
   $this->template->template_render('serviceprovider');
	}

  public function orders()
  {
    $filter_type = $this->input->get('filter');
    $start_date = $this->input->get('start_date');
    $end_date = $this->input->get('end_date');
    $status = $this->input->get('status');

    $data = array();
    
    // Set default filter to today if no filter is specified
    if (!$filter_type) {
      $filter_type = 'today';
    }

    switch ($filter_type) {
      case 'today':
        $data['orders'] = $this->order_model->get_today_orders();
        $data['filter_type'] = 'today';
        $data['filter_label'] = 'Today\'s Orders';
        break;
        
      case 'date_range':
        if ($start_date && $end_date) {
          $data['orders'] = $this->order_model->get_orders_with_filters($start_date, $end_date, $status);
          $data['filter_type'] = 'date_range';
          $data['start_date'] = $start_date;
          $data['end_date'] = $end_date;
          $data['status'] = $status;
          $data['filter_label'] = 'Orders from ' . date('M d, Y', strtotime($start_date)) . ' to ' . date('M d, Y', strtotime($end_date));
        } else {
          $data['orders'] = $this->order_model->get_all_orders();
          $data['filter_type'] = 'all';
          $data['filter_label'] = 'All Orders';
        }
        break;
        
      case 'all':
      default:
        $data['orders'] = $this->order_model->get_all_orders();
        $data['filter_type'] = 'all';
        $data['filter_label'] = 'All Orders';
        break;
    }

    // Get order counts for summary
    $data['today_count'] = $this->order_model->get_today_order_count();
    $data['total_count'] = count($this->order_model->get_all_orders());

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

  public function update_order_status()
  {
    $order_id = $this->input->post('order_id');
    $status = $this->input->post('status');
    
    if ($order_id && $status) {
      $response = $this->order_model->update_order_status($order_id, $status);
      
      if ($response) {
        $this->session->set_flashdata('successmessage', 'Order status updated successfully');
      } else {
        $this->session->set_flashdata('warningmessage', 'Failed to update order status');
      }
    } else {
      $this->session->set_flashdata('warningmessage', 'Invalid order data');
    }
    
    redirect(base_url('dashboard/orders'));
  }

  public function delete_order()
  {
    $order_id = $this->uri->segment(3);
    
    if ($order_id) {
      $response = $this->order_model->delete_order($order_id);
      
      if ($response) {
        $this->session->set_flashdata('successmessage', 'Order deleted successfully');
      } else {
        $this->session->set_flashdata('warningmessage', 'Failed to delete order');
      }
    } else {
      $this->session->set_flashdata('warningmessage', 'Invalid order ID');
    }
    
    redirect(base_url('dashboard/orders'));
  }

  public function view_order()
  {
    $order_id = $this->uri->segment(3);
    
    if ($order_id) {
      $data['order'] = $this->order_model->get_order_by_id($order_id);
      
      if ($data['order']) {
        $this->template->template_render('view_order', $data);
      } else {
        $this->session->set_flashdata('warningmessage', 'Order not found');
        redirect(base_url('dashboard/orders'));
      }
    } else {
      $this->session->set_flashdata('warningmessage', 'Invalid order ID');
      redirect(base_url('dashboard/orders'));
    }
  }
}