<?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('customer_model');
          $this->load->model('common');
          	define( 'API_ACCESS_KEY1', 'AAAANrVnP-A:APA91bF12A4sgPNkTV9AHjD-ep7m10jqPeHyaeKo9gZVBh0SbSLcVWCd7l7NQ3dTpwxSrnNRDV4o2XldZMLv-Di_Lzx1rtjCjyM6eEO4Sypq95bwSk4McnvVBSgIhdb4CMGC3mSUZwgq');
			 $flag= $this->session->userdata('reslist'); 
			 if($flag==false){
				redirect(base_url().'Store');

			 }
	
		}
     function send_notification($token_id,$title,$body,$id,$type){
	 
	$icon=base_url('uploads/logo.png');
	
	$finalPostArray = array('registration_ids' => $token_id,
								'notification' => array('body' => $body,
														'title' => $title,
														"image"=> $icon,
														   "sound"=> "sample4_out.caf"
													),
									'aps'=>array(
										"sound"=> "sample4_out.caf"
									),				
								"data"=> array("click_action"=> "FLUTTER_NOTIFICATION_CLICK",
												"type"=>$type,
												"id"=>$id,
												"sound"=> "sample4_out.caf", 
												"soundios"=> "sample4_out.caf",
												"vibrate"=> 1)); 
		
	
		
		
		$headers = array
				(
					'Authorization: key=' . API_ACCESS_KEY1,
					'Content-Type: application/json'
				);
	#Send Reponse To FireBase Server	
			$ch = curl_init();
			curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
			curl_setopt( $ch,CURLOPT_POST, true );
			curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
			curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
			curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $finalPostArray ) );
			$result['mystatus'] = curl_exec($ch );
			curl_close( $ch );
	#Echo Result Of FireBase Server
	//$result['firbasestatus']=$fields;
	return $result;
		}

public function mytest($id="111",$msg="new data",$type="Event",$ntype="user"){
	$data = $this->customer_model->getall_customernew();;
	//exit;
		$token=array();
		$userIdArray=array();
	


		foreach($data["user"] as $l=>$j){
			 if(!empty($j['token'])  && $j['token'] !=""){
			 	  $userIdArray[$l] = false;
			array_push($token, $j['token'])	; 	
			 }
			 $ceta=array();
			 $ceta['reciverId']=$l;
			 $ceta['inserteddate']=time()*1000;
			 $ceta['senderId']="admin";
			 $ceta['type']="event";
			 $ceta['eventId']=$id;
			 $ceta['msg']="Admin has been added new event.";
			 $insertedid=rand().time();
			 $this->common->adddatamodel("Notification",$insertedid,$ceta);

	
		}
//		echo "<pre>";
//		print_r($data);
//		print_r($token);

		$notification=$this->send_notification($token,"New Event",$msg,$id,$type);
 //print_r($notification);
//echo "</pre>";
}
function millisecondsToYears($milliseconds) {
    $millisecondsInYear = 365.25 * 24 * 60 * 60 * 1000;
    $years = floor($milliseconds / $millisecondsInYear);
    return $years;
}
function findAgeGroup($age) {
    $ageGroups = [
        '0-17' => 'Under 18',
        '18-24' => '18-24',
        '25-34' => '25-34',
        '35-44' => '35-44',
        '45-54' => '45-54',
        '55+' => '55 and above'
    ];

    foreach ($ageGroups as $range => $label) {
        list($min, $max) = explode('-', $range);
        if ($age >= $min && ($age <= $max || $max == '+')) {
            return $range;
        }
    }

    return 'Unknown';
}
function calculateAgeGroup($dobArray) {
    $ageGroups = [
        '0-17' => 'Under 18',
        '18-24' => '18-24',
        '25-34' => '25-34',
        '35-44' => '35-44',
        '45-54' => '45-54',
        '55+' => '55 and above'
    ];

    $ageGroupCounts = array_fill_keys(array_values($ageGroups), 0);

    foreach ($dobArray as $dob) {
        // Assuming $dob is in milliseconds
        $dateOfBirthSeconds = $dob / 1000;
        $currentTimestamp = time();
        $ageInSeconds = $currentTimestamp - $dateOfBirthSeconds;
        $ageInYears = floor($ageInSeconds / (365.25 * 24 * 60 * 60));

        foreach ($ageGroups as $range => $group) {
            list($start, $end) = explode('-', $range);

            if ($ageInYears >= $start && $ageInYears <= $end) {
                $ageGroupCounts[$group]++;
                break;
            }
        }
    }

    return $ageGroupCounts;
}
	public function index()
	 {	
		$chanda=array();
		$id=$this->session->userdata('restid');
		$data['resid']['id'] = $id;
		$orders=$this->common->readdatafromcollectionbetween('Orders',"restId","=",$id);

		$dishreview=$this->common->readdatacollection("Restaurant","Reviews",$id);
		$resturentinfo= $this->common->readdatadocument("Restaurant",$id);
		$data['resturentinfo']=$resturentinfo;
		$data['dishreview']=$dishreview;
		
		$resvistor=array();
		// echo "<pre>";
		// print_r($resturentinfo['visit']);
		// echo "</pre>";
		 foreach($resturentinfo['visit'] as $res=>$j){
			$resvistor[$res]=$j;

		}
		arsort($resvistor);
		$filteredArray = array_filter($resvistor, function($value) {
			return $value > 1;
		}, ARRAY_FILTER_USE_BOTH);

		// Take only the top 5 elements
		$top5 = array_slice($filteredArray, 0, 5, true);
			foreach($top5 as $t=>$tt){
				$ceta['label']=getusername($t);
				$ceta['visit']=$tt;
		array_push($chanda,$ceta);
			}
$data['histogramedata']=json_encode($chanda);
// echo "<pre>";
// print_r($data);
// echo "</pre>";					
		// Output the result
		$timestamps2=array();
foreach($orders as $key=>$user){
	$timestamps2[$key]    = $user['date'];

}
array_multisort($timestamps2, SORT_ASC);

	 $data['users']=count($users);
		  foreach ($dishreview as $key => $user) {
			$timestamps[$key]    = $user['date'];

		}


		$data['clients'] = 0;
		$data['totalUsers'] = 0;
		$data['rides'] = 0;
		$jana=array();
		$peta=array();
		$mealwithnumber=array();


		$meals=$this->common->readdatafromcollectionbetween('Dishes',"res_id","=",$id);
		
		foreach ($meals as $key => $user) {


			$ceta=array();
         	$ceta['label']=$user['name'];
			$value=0;
			foreach($user['rating'] as $k=>$v){
				$value=$value+$v;
			}
			$ceta['y']=1*(number_format((float)$value/count($user['rating']), 2, '.', ''));
			array_push($jana, $ceta);


			foreach($user['visit'] as $k1=>$v1){
				$peta[$k1]=$v1;
			}
	$mealwithnumber[$key]=$peta;

		}

		
$male=0;
$female=0;
$totalvisit=0;
$ages=array();
$country=array();

$kapu=array();
		foreach ($peta as $key => $user) {
	
$userinfo=$this->common->readdatadocument("Users",$key);

if($userinfo['sex']=="male"){
	$male++;
}else{
	$female++;
}
$totalvisit=$totalvisit+$user;
if(isset($userinfo['dob'])){
	array_push($ages, $userinfo['dob']);
	$kapu[$key]=$this->millisecondsToYears($userinfo['dob']);
}
if(isset($userinfo['country'])){
	if(array_key_exists($userinfo['country'],$country)){
		$country[$userinfo['country']]=$country[$userinfo['country']]+$user;
	}else{
		$country[$userinfo['country']]=$user;
	}
	
}

}



$l12=array();
foreach($mealwithnumber as $key1=>$val){
	 $l1['meals']=$key1;
	$lour=array();
	foreach($val as $key=>$p){		
		if(array_key_exists($loru[$kapu[$key]])){
			$loru[$kapu[$key]]=$loru[$kapu[$key]]+$p;
		}else{
			$loru[$kapu[$key]]=$p;
		}
	}

	$l1['data']=$loru;
	array_push($l12,$l1);
}
$ageGroups = [
    '0-17' => 'Under 18',
    '18-24' => '18-24',
    '25-34' => '25-34',
    '35-44' => '35-44',
    '45-54' => '45-54',
    '55+' => '55 and above'
];
$ageGroupMealCounts = [];

// Loop through the data
foreach ($l12 as $entry) {
    $mealId = $entry['meals'];

    // Initialize counts for the current meal ID
    if (!isset($ageGroupMealCounts[$mealId])) {
        $ageGroupMealCounts[$mealId] = array_fill_keys(array_keys($ageGroups), 0);
    }

    foreach ($entry['data'] as $age => $visits) {
        // Determine the age group for the current age
        $ageGroup = $this->findAgeGroup($age);

        // Increment the count for the current age group and meal ID
        $ageGroupMealCounts[$mealId][$ageGroup] += $visits;
    }
}

$data['ageGroupMealCounts']=$ageGroupMealCounts;




$ageGroupCounts = $this->calculateAgeGroup($ages);

// Calculate total count
$totalCount = array_sum($ageGroupCounts);
$percentageData = [];
foreach ($ageGroupCounts as $group => $count) {
    $percentage = ($count / $totalCount) * 100;
    $percentageData[$group] = $percentage;
}

$data['country']=$country;
$data['agesgroup']=$percentageData;
$data['male']=$male;
$data['female']=$female;

		
		$data['dishbargraph']=json_encode($jana);
		$data['meal'] = count($meals);
 
		array_multisort($timestamps, SORT_ASC, $users);
	   	
		$labels = array();
	
		$labels[0]=  date('F', strtotime($labels[0]." + 7 month"));
		for($i =1; $i<=6; $i++) {
		  $timestamp = strtotime($labels[$i-1].' + 1 month');
		   $labels[$i] = date('F', $timestamp);
		}
		$labelStr = '';
		foreach($labels as $label) {
		  $labelStr .= '"'.$label.'", ';
		}
		
		$data['labelStr'] = $labelStr;
		//print_r($data);
		$dataStr = '';
		for($i =0; $i<count($labels); $i++) {
		  $num = 0;
		  foreach($timestamps as $timestamp) {
	
	
			if($labels[$i] == date('F', $timestamp/1000)) {
		   //   echo "yes";
			  $num += 1;
			}
		  }
		  $dataStr .= $num.',';
		}
		$data['dataStr'] = $dataStr;

		$labels = array();
	
		$labels[0]=  date('F', strtotime($labels[0]." + 7 month"));
		for($i =1; $i<=6; $i++) {
		  $timestamp = strtotime($labels[$i-1].' + 1 month');
		   $labels[$i] = date('F', $timestamp);
		}
		$labelStr = '';
		foreach($labels as $label) {
		  $labelStr .= '"'.$label.'", ';
		}
		
		$data['labelStr2'] = $labelStr;
		//print_r($data);
		$dataStr = '';
		for($i =0; $i<count($labels); $i++) {
		  $num = 0;
		  foreach($timestamps2 as $timestamp) {
	
	
			if($labels[$i] == date('F', $timestamp/1000)) {
		   //   echo "yes";
			  $num += 1;
			}
		  }
		  $dataStr .= $num.',';
		}
		$data['dataStr2'] = $dataStr;



// echo "<pre>";
// print_r($data);
// echo "</pre>";


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

	public function restaurant()
	{
		$id = $this->session->userdata('restid');
	
		$data['resid']['id'] = $id;

		$data['dishreview']=$this->common->readdatacollection("Restaurant","Reviews",$id);
		$data['resturentinfo'] = $this->common->readdatadocument("Restaurant",$id);
		$this->template->template_render('viewres', $data);

	}

public function restlist(){
	$this->session->set_userdata('restid', "");
	$this->session->set_userdata('restname', "");
	$this->session->set_userdata('reslist', false);
	redirect(base_url().'store');	
}
	public function dishes($id="")
	{
		$id=$this->session->userdata('restid');
	$data["specialities"] =$this->common->readdatafromcollectionbetween2where('Dishes',"res_id","=",$id);
          
          $this->template->template_render('dishes',$data);
	}

	public function adddishes()
	{
		$data["category"] = $this->dashboard_model->get_category();
		$data["mcategory"] = $this->common->readdatafromcollectionwhereclause("category");
		$data["foodtype"] = $this->common->readdatafromcollectionwhereclause("foodtype");
		$data["diettype"] = $this->common->readdatafromcollectionwhereclause("diettype");
		$this->template->template_render('adddishes',$data);
	}



	public function insertdish()
	{
		$data = $this->input->post();
		if(isset($data['Featured'])){
			$data['Featured']=true;
		}else{
			$data['Featured']=false;
		}
		if(isset($data['Special'])){
			$data['Special']=true;
		}else{
			$data['Special']=false;
		}
		if(isset($data['Seasonal'])){
			$data['Seasonal']=true;
		}else{
			$data['Seasonal']=false;
		}
		$data['ingredients']=explode(",",$data['ingredients']);
		// print_r($data);
		// exit;
		$resdata=$this->common->readdatadocument("Restaurant",$this->input->post('res_id'));
	

		$data['country']=$resdata['country'];
		$data['city']=$resdata['city'];
		$response = $this->dashboard_model->add_speciality($data);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'New dishes added successfully');
			redirect(base_url().'dashboard/dishes');
		} else {
			$errormsg = 'Error! dishes not added, please check data.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/dishes');
		}
	}
//updatecountry
  public function updateevent()
	{
		$data = $this->input->post();

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

        $data = $this->input->post();


        if ($_FILES['image']['tmp_name'] != '') {
            $fileName = "events" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
              file_get_contents($_FILES['image']['tmp_name']),
              [
                'name' => $fileName,
				'predefinedAcl' => 'publicRead'
              ]
            );
            // $data['image'] = 'https://firebasestorage.googleapis.com/v0/b/tattoo-f01b9.appspot.com/o/'.$fileName.'?alt=media';
                        $data['image'] = $uploadedFile->info()['mediaLink'];
          }
        $data['date'] = strtotime($data['date']);

		$response = $this->common->updatedatamodel("Restaurant", $data["id"], $data);
    
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Restaurant updated added successfully');
			redirect(base_url().'dashboard/restaurant');
		} else {
			$errormsg = 'Error! Restaurant not updated, please check event data.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/addrestaurant'.$data['id']);
		}
	}

	public function updatedish()
	{
		$firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();
		$resdata=$this->common->readdatadocument("Restaurant",$this->input->post('res_id'));
	
		$data = $this->input->post();
		if(isset($data['Limited'])){
			$data['Limited']=true;
		}else{
			$data['Limited']=false;
		}
		if(isset($data['Special'])){
			$data['Special']=true;
		}else{
			$data['Special']=false;
		}
		if(isset($data['Seasonal'])){
			$data['Seasonal']=true;
		}else{
			$data['Seasonal']=false;
		}
		$data['ingredients']=explode(",",$data['ingredients']);
		$data['country']=$resdata['country'];
		$data['city']=$resdata['city'];
		if ($_FILES['image']['tmp_name'] != '') {
            $fileName = "events" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
              file_get_contents($_FILES['image']['tmp_name']),
              [
                'name' => $fileName,
              ]
            );

            $data['image'] = $uploadedFile->info()['mediaLink'];
          }
		  if ($_FILES['image1']['tmp_name'] != '') {
            $fileName = "events" . rand() . time() . $_FILES['image1']['name'];
            $uploadedFile = $defaultBucket->upload(
              file_get_contents($_FILES['image1']['tmp_name']),
              [
                'name' => $fileName,
              ]
            );

            $data['image1'] = $uploadedFile->info()['mediaLink'];
          }
		  if ($_FILES['image2']['tmp_name'] != '') {
            $fileName = "events" . rand() . time() . $_FILES['image2']['name'];
            $uploadedFile = $defaultBucket->upload(
              file_get_contents($_FILES['image2']['tmp_name']),
              [
                'name' => $fileName,
              ]
            );

            $data['image2'] = $uploadedFile->info()['mediaLink'];
          }
		

		$response = $this->common->updatedatamodel("Dishes", $data["id"], $data);
    
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Dishes updated successfully');
			redirect(base_url().'dashboard/dishes');
		} else {
			$errormsg = 'Error! dishes not updated, please check data.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/editdish/'.$data['id']);
		}
	}

  public function editresturent()
	{
		$eid = $this->uri->segment(3);
		$data['event'] = $this->common->readdatadocument("Restaurant",$eid);
		$data["country"] = $this->dashboard_model->get_country();
		$data['event']['id'] = $eid;
		$data["mcategory"] = $this->common->readdatafromcollectionwhereclause("category");
		$this->template->template_render('restaurant_add', $data);
	}

	public function editdish()
	{
		$id = $this->uri->segment(3);
		$data['speciality'] = $this->common->readdatadocument("Dishes",$id);
		
		$data['speciality']['id'] = $id;
		$data["category"] = $this->dashboard_model->get_category();
		$data["foodtype"] = $this->common->readdatafromcollectionwhereclause("foodtype");
		$data["diettype"] = $this->common->readdatafromcollectionwhereclause("diettype");
		$data["mcategory"] = $this->common->readdatafromcollectionwhereclause("category");
		$this->template->template_render('adddishes', $data);
	}
	public function viewdish()
	{
		$id = $this->uri->segment(3);
		$data['Dish'] = $this->common->readdatadocument("Dishes",$id);
		$data['dish']['id'] = $id;
		$data['dishreview']=$this->common->readdatacollection("Dishes","Reviews",$id);
		$data['resturentinfo'] = $this->common->readdatadocument("Restaurant",$data['Dish']['res_id']);
		$this->template->template_render('viewdish', $data);
	}
	
	public function viewres()
	{
		$id = $this->uri->segment(3);
	
		$data['resid']['id'] = $id;

		$data['dishreview']=$this->common->readdatacollection("Restaurant","Reviews",$id);
		$data['resturentinfo'] = $this->common->readdatadocument("Restaurant",$id);
		$this->template->template_render('viewres', $data);
	}
	
	public function editcountry()
	{
		$id = $this->uri->segment(3);
		$data['event'] = $this->common->readdatadocument("Country",$id);
		$data['event']['id'] = $id;
		$this->template->template_render('category_add', $data);
	}

	public function deleteresturent($eid){
		$response = $this->common->deletedatamodel("Restaurant",$eid);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'Restaurant deleted successfully');
			redirect(base_url().'dashboard/restaurant');
		} else {
			$errormsg = 'Error! Restaurant cannot be deleted.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/restaurant');
		}
	}

	public function deletespeciality($id){
		$response = $this->common->deletedatamodel("dishes",$id);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'dishes deleted successfully');
			redirect(base_url().'dashboard/dishes');
		} else {
			$errormsg = 'Error! dishes cannot be deleted.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/dishes');
		}
	}
	//deletecountry
	public function deletecountry($id){
		$response = $this->common->deletedatamodel("Country",$id);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'country deleted successfully');
			redirect(base_url().'dashboard/country');
		} else {
			$errormsg = 'Error! country cannot be deleted.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/country');
		}
	}
	public function deletecategory($id){
		$response = $this->common->deletedatamodel("Categories",$id);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'dishes deleted successfully');
			redirect(base_url().'dashboard/category');
		} else {
			$errormsg = 'Error! dishes cannot be deleted.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url().'dashboard/category');
		}
	}
     
}