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

class Dashboard extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->model('dashboard_model');
        $this->load->model('common');
        $this->load->model('geofence_model');
        define('API_ACCESS_KEY1', 'AAAABxK6snc:APA91bGiOVlnshswyro_sSN6NZx7VUnG3FptNxPCbjOw9BkleT1eTmCHsL0FNksOrDmkI-b3OXrBOXO-R_JfzSwHt4HE8JpSgnXCjVrDIxpDnkAYnp2JkhSGlYVrhIVgxYiJFjVCpQ7Q');
        // $this->load->database();
    }


    public function profile(){
        $sessiondata=$this->session->userdata['session_data'];
        $data['userdata']=$this->common->readdatadocument("Users",$sessiondata['userId']);

        $this->template->template_render('profile', $data);
    }
    
    
    public function readnotification(){
        $sessiondata=$this->session->userdata['session_data'];
        $id=$sessiondata['userId'];

     
        $notification=$this->common->readdatafromcollectionwhereclause("Notification","userId","=",$id);
        $data = [];

        foreach ($notification as $d => $da) {
          //  echo $d;


            $da['notification_id']=$d;
            array_push($data,$da);
        }
     
     
        header('Content-Type: application/json');
        echo json_encode($data);
    }

    public function saveprofile(){
        $firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();


        $da = $this->input->post();
/*
        if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "reminder" . rand() . time() . $_FILES['file']['name'],
				]
			);

			echo $da['image'] = $uploadedFile->info()['mediaLink'];
		}
  */      
        if ($_FILES['file']['tmp_name'] != '') {
            $name =   rand() . time() . $_FILES['file']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['file']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $da['image'] = 'https://storage.googleapis.com/repidorx.appspot.com/'.$name;
        }


        $sessiondata=$this->session->userdata['session_data'];
        $id=$sessiondata['userId'];

		//print_r($da);
		if ($da['password'] != "") {
			$flag = $this->customer_model->update_customerpassword($id, $da['password']);




			if ($flag) {
				$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
				$this->session->set_flashdata('successmessage', 'Users has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Usome thing error Please try later');

				redirect('dashboard/profile/');
			}
		} else {
			$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
			$this->session->set_flashdata('successmessage', 'Users has been updated successfully');
		}
        redirect('dashboard/profile/');
    }

    public function leaves(){
        $data['services'] = $this->common->readdatafromcollectionwhereclause("Leaves", "status", "=", "pending");
        //$this->common->readdatafromcollectionwhereclause('Products');
   
  
        $this->template->template_render('leaves_management', $data);
    }
    //
    public function leavesapproved(){
        $data['services'] = $this->common->readdatafromcollectionwhereclause("Leaves", "status", "=", "Approved");
        //$this->common->readdatafromcollectionwhereclause('Products');
   
  
        $this->template->template_render('leaves_management1', $data);
    }
    public function chatimageupload()
    {
        $thisClientID = $this->input->post('myid');

        $collectionName = 'ClientChats';
        $conversationID = $this->input->post('conversationId');
        $lastMessageID = $this->input->post('msgId');;

        $data = array();
        $data['image'] = $this->input->post('fileUrl');
        $data['fromID'] = $thisClientID;
        $data['isRead'] = false;
        $data['messageId'] = $lastMessageID;
        $data['timestamp'] = $lastMessageID;
        $data['type'] = 'image';
        $data['content'] = "";

        $res = $this->common->adddatamodelnexted($collectionName, $conversationID, 'Conversations', $lastMessageID, $data);

        echo (json_encode(array('status' => "OK", 'message' => "Image Uploaded", 'data' => $data, 'conversationID' => $conversationID)));
    }
    function allsheet($params="all"){
        $jana=array();
        
        if($params=="weekly"){

            $filter="weekly";
            date_default_timezone_set('UTC');
            $currentDate = date('Y-m-d');    
            // Subtract 7 days from the current date
            $startdate = date('Y-m-d', strtotime('-7 days', strtotime($currentDate)))*1000;
            $currentDate = date('Y-m-d');
            $startOfDayStr = $currentDate . ' 23:59:59';
        
            // Convert the datetime string to a timestamp
            $enddate = strtotime($startOfDayStr)*1000;            
            $jobslist=$this->common->readdatafromcollectionwhereclause("Jobs");
            foreach($jobslist as $j=>$jobdata){
                $jobworkerlist =$this->common->nextedreaddatafromcollectionwhereclause("Jobs",$j,"JobWorker");
               foreach($jobworkerlist as $jb=>$jw){
                    if($jw['startTime']>=$startdate){
                        $myarray=array();
                        $myarray['jobsId']=$j;
                        $myarray['jobsdata']=$jobdata;
                        $myarray['workerlistid']=$jb;
                        $myarray['workerdata']=$jw;   
                        array_push($jana,$myarray);
                 
                    }
               }
            }
    
    
            $data['jobinfo']=$jana;
            $data['filter']="weekly";
        }
        if($params=="monthly"){
            $filter="monthly";
            date_default_timezone_set('UTC');
            $currentDate = date('Y-m-d');    
            // Subtract 7 days from the current date
            $startdate = date('Y-m-d', strtotime('-30 days', strtotime($currentDate)))*1000;
            $currentDate = date('Y-m-d');
            $startOfDayStr = $currentDate . ' 23:59:59';
        
            // Convert the datetime string to a timestamp
            $enddate = strtotime($startOfDayStr)*1000; 
            $jobslist=$this->common->readdatafromcollectionwhereclause("Jobs");
            foreach($jobslist as $j=>$jobdata){
                $jobworkerlist =$this->common->nextedreaddatafromcollectionwhereclause("Jobs",$j,"JobWorker");
               foreach($jobworkerlist as $jb=>$jw){
                    if($jw['startTime']>=$startdate){
                        $myarray=array();
                        $myarray['jobsId']=$j;
                        $myarray['jobsdata']=$jobdata;
                        $myarray['workerlistid']=$jb;
                        $myarray['workerdata']=$jw;   
                        array_push($jana,$myarray);
                 
                    }
               }
            }
            $data['jobinfo']=$jana;
            $data['filter']="monthly";
        }
        if($params=="all"){
            
            $filter="all";
            $jobslist=$this->common->readdatafromcollectionwhereclause("Jobs");
            foreach($jobslist as $j=>$jobdata){
                $jobworkerlist =$this->common->nextedreaddatafromcollectionwhereclause("Jobs",$j,"JobWorker");
               foreach($jobworkerlist as $jb=>$jw){
                        $myarray=array();
                        $myarray['jobsId']=$j;
                        $myarray['jobsdata']=$jobdata;
                        $myarray['workerlistid']=$jb;
                        $myarray['workerdata']=$jw;   
                        array_push($jana,$myarray);
                 
                    
               }
            }
            $data['jobinfo']=$jana;
            $data['filter']="all";
            
        }
        $this->template->template_render('dashboard1', $data);


    }

public function request(){
    $jobslist=$this->common->readdatafromcollectionwhereclause("JobEditApprove");
   
    $data['requestlist']=$jobslist;
    $this->template->template_render('dashboard2', $data);




}

public function requesthandle($p1,$p2){
   $requestdata= $this->common->readdatadocument("JobEditApprove",$p2);

if($p1=="accept"){
$data['isRead']=false;
$data['message']="Your Edit Request has been Approved";
$data['title']="Edit Request";
$data['type']="EditRequest";
$data['userId']=$requestdata['userId'];
$data['extradata']=$requestdata;
$data['timestamp']=time()*1000;
$uniqueid=time();
$this->common->adddatamodel('Notification',$uniqueid,$data);
$champa['status']="approve";
$this->common->updatedatamodel("JobEditApprove",$p2,$champa);
}
if($p1=="reject"){
    $data['isRead']=false;
    $data['message']="Your Edit Request has been Rejected";
    $data['title']="Edit Request";
    $data['type']="EditRequest";
    $data['userId']=$requestdata['userId'];
    $data['extradata']=$requestdata;
    $data['timestamp']=time()*1000;
    $uniqueid=time();
    $this->common->adddatamodel('Notification',$uniqueid,$data);
    $champa['status']="reject";
    $this->common->updatedatamodel("JobEditApprove",$p2,$champa);
    }
    redirect(base_url() . 'dashboard/request/');
}

    public function index()
    {
        $sessiondata=$this->session->userdata['session_data'];
        $id=$sessiondata['userId'];
		//$data['customerlist'] = $this->customer_model->getall_customer();
		$data['customerlist'] = $this->common->readdatafromcollectionwhereclause("OrderRequest","pharmacyID","=",$id);
		$data['doctorlist'] = $this->common->readdatafromcollectionwhereclause("Users","userRole","=","doctor");
		$data['driverlist'] = $this->common->readdatafromcollectionwhereclause("Users","userRole","=","driver");
        $sessiondata=$this->session->userdata['session_data'];
        $id=$sessiondata['userId'];
        $data['userlist'] = $this->common->readdatafromcollectionbetween("Attachment","pharmistID","=",$id,"type","=","patient");

       // $data['userlist'] = $this->common->readdatafromcollectionwhereclause("Users","userRole","=","user");

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




    public function bids()
    {
        $data["bookings"] = $this->common->readdatafromcollectionbetween("Bookings");
        $this->template->template_render('tasks', $data);
    }

    public function calendar()
    {
        $data["bookings"] = $this->common->readdatafromcollectionbetween("Bookings");
        $this->template->template_render('calendar', $data);
    }


    public function users()
    {
        $data["client"] = $this->common->readdatafromcollectionbetween("clients");
        $data["staff"] = $this->common->readdatafromcollectionbetween("staff");
        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";

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

    public function edituser()
    {
        $data["users"] = $this->common->readdatafromcollectionbetween("Bookings");
        $this->template->template_render('viewuser', $data);
    }
 
    //
    public function editnotifcation($id)
    {
        // 
        $data["category"] = $this->common->readdatadocument("News", $id);
        $data['catid'] = $id;
        $this->template->template_render('notification_edit', $data);
    }
    //editnews
    public function editnews($id)
    {
        // 
        $data["category"] = $this->common->readdatadocument("News", $id);
        $data['catid'] = $id;
        $this->template->template_render('news_edit', $data);
    }
    //editservices
    public function editservices($id)
    {
        // 
        $data["services"] = $this->common->readdatadocument("services", $id);
        $data['id'] = $id;
        $this->template->template_render('services_edit', $data);
    }
    public function viewprodoct($id)
    {
        // 
        $data["services"] = $this->common->readdatadocument("Products", $id);
        $data['id'] = $id;
        $this->template->template_render('product_view', $data);
    }
    public function editservicesdata($id)
    {
        $data = $this->input->post();
        $response = $this->common->updatedatamodel("services", $id, $data);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' services has been updated successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in update  services..');
        }
        redirect(base_url() . 'dashboard/editservices/' . $id);
    }
//cancelleave

public function cancelleave($id)
{
    $data['status'] ='Reject' ;
    $response = $this->common->updatedatamodel("Leaves", $id, $data);
    if ($response) {
        $this->session->set_flashdata('successmessage', ' Leaves has been Reject successfully..');
    } else {
        $this->session->set_flashdata('warningmessage', 'Error in update  services..');
    }
    redirect(base_url() . 'dashboard/leaves/');
}
public function approveleave($id)
{
    $data['status'] ='Approve' ;
    $response = $this->common->updatedatamodel("Leaves", $id, $data);
    if ($response) {
        $this->session->set_flashdata('successmessage', ' Leaves has been Approved successfully..');
    } else {
        $this->session->set_flashdata('warningmessage', 'Error in update  services..');
    }
    redirect(base_url() . 'dashboard/leaves/');
}
    //editnotificationdata
    public function editnotificationdata($id)
    {
        $data = $this->input->post();
        $response = $this->common->updatedatamodel("News", $id, $data);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' Announcement has been updated successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in update  Notification..');
        }
        redirect(base_url() . 'dashboard/editnotifcation/' . $id);
    }
    public function editnewsdata($id)
    {
        $data = $this->input->post();
        $response = $this->common->updatedatamodel("News", $id, $data);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' News has been updated successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in update  News.');
        }
        redirect(base_url() . 'dashboard/editnews/' . $id);
    }
    public function editcategorydata($id)
    {
        $data = $this->input->post();
        $response = $this->common->updatedatamodel("Category", $id, $data);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' Category has been updated successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in update  Category..');
        }
        redirect(base_url() . 'dashboard/editcategory/' . $id);
    }

    public function updatecompany($id = 0)
    {
        $data = $this->input->post();
        $response = $this->common->updatedatamodel("contactInfo", $id, $data);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' contact Info has been updated successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in update  contact Info..');
        }
        redirect(base_url() . 'dashboard/company/');
    }
    //deletenewnotification
    public function deleteproduct($id)
    {

        $response = $this->common->deletedatamodel("Products", $id);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' Products has been Removed successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in delete  Product..');
        }
        redirect(base_url() . 'dashboard/products/');
    }
    //deletenotification
    public function deletenotification($id)
    {

        $response = $this->common->deletedatamodel("News", $id);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' Announcement has been Removed successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in delete  Announcement..');
        }
        redirect(base_url() . 'dashboard/notification/');
    }
    public function deletenews($id)
    {

        $response = $this->common->deletedatamodel("News", $id);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' News has been Removed successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in delete  News.');
        }
        redirect(base_url() . 'dashboard/news/');
    }
   
    //deleteservices
    public function deleteservices($id)
    {

        $response = $this->common->deletedatamodel("services", $id);
        if ($response) {
            $this->session->set_flashdata('successmessage', ' services has been Removed successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in delete  services..');
        }
        redirect(base_url() . 'dashboard/services/');
    }
    public function categories()
    {
        $data["users"] = $this->common->readdatafromcollectionbetween("Category");

        $this->template->template_render('categories_management', $data);
    }
    //newnotification
    function newnotification()
    {
        $data["users"] = $this->common->readdatafromcollectionbetween("AssignNoty");

        $this->template->template_render('newnotification_management', $data);
    }
    function notification()
    {
        $data["users"] = $this->common->readdatafromcollectionbetween("News", "type", "=", "announcement");


        $this->template->template_render('notification_management', $data);
    }
    //news
    function news()
    {
        $data["users"] = $this->common->readdatafromcollectionbetween("News");

        $this->template->template_render('news_management', $data);
    }
    public function addcategory()
    {
        //     $data["users"] = $this->common->readdatafromcollectionbetween("Bookings");
        $this->template->template_render('category_add');
    }
    //addnotification
    public function addnotification()
    {
        //     $data["users"] = $this->common->readdatafromcollectionbetween("Bookings");
        $this->template->template_render('addnotification');
    }
    public function addnews()
    {
        //     $data["users"] = $this->common->readdatafromcollectionbetween("Bookings");
        $this->template->template_render('addnews');
    }
    //
    public function adddataproduct()
    {
     

$myimage=array();


        $data = $this->input->post();
        $firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();
        if ($_FILES['image']['tmp_name'] != '') {
          $uploadedFile = $defaultBucket->upload(
            file_get_contents($_FILES['image']['tmp_name']),
            [
              'name' => "UserImage/user" . rand() . time() . $_FILES['image']['name'],
            ]
          );
          $data['image'] = $uploadedFile->info()['mediaLink'];
        
        }
        foreach($_FILES["gallery"]["tmp_name"] as $key=>$tmp_name) {
            
            $ext=pathinfo($file_name,PATHINFO_EXTENSION);
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['gallery']['tmp_name'][$key]),
                [
                  'name' => "UserImage/user" . rand() . time() . $_FILES['gallery']['name'],
                ]
              );
              $myim = $uploadedFile->info()['mediaLink'];
            array_push($myimage,$myim);

            
        }
        $data['gallery']=$myimage;
     
       
        $id = time();
        $response = $this->common->adddatamodel("Products", $id, $data);
        //    $this->template->template_render('category_add');
        if ($response) {
            $this->session->set_flashdata('successmessage', 'New Category added successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in creating new Category..');
        }
        redirect(base_url() . 'dashboard/products');
    }

    public function addnotificationdata()
    {
        $token = array();

        $staffs = $this->common->readdatafromcollectionwhereclause("Users", "token", "<>", "");

        foreach ($staffs as $staffId => $staff) {
            if (!empty($staff['token'])) {
                array_push($token, $staff['token']);

                // var_dump($notification);
            }
        }

        $data = $this->input->post();
        $id = time();
        $data['createdata'] = $id * 1000;
        $response = $this->common->adddatamodel("News", $id, $data);
        $notification = $this->send_notification($token, "Announcement", $data['title'], time(), "annoncemnetnotification");
        //    $this->template->template_render('category_add');
        if ($response) {
            $this->session->set_flashdata('successmessage', 'New Announcement added successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in creating new Notification..');
        }
        redirect(base_url() . 'dashboard/addnotification');
    }
    //addnewsdata
    public function addnewsdata()
    {
        $data = $this->input->post();
        $id = time();
        $token = array();

        $staffs = $this->common->readdatafromcollectionwhereclause("Users", "token", "<>", "");

        foreach ($staffs as $staffId => $staff) {
            if (!empty($staff['token'])) {
                array_push($token, $staff['token']);

                // var_dump($notification);
            }
        }
        //print_r($token);
        $response = $this->common->adddatamodel("News", $id, $data);

        $notification = $this->send_notification($token, "News", $data['title'], time(), "newsnotification");
        //var_dump($notification);
        //exit;
        //    $this->template->template_render('category_add');
        if ($response) {
            $this->session->set_flashdata('successmessage', 'New News added successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error in creating new Notification..');
        }
        redirect(base_url() . 'dashboard/addnews');
    }

    public function services()
    {
        $data["services"] = $this->common->readdatafromcollectionbetween("services");

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

    public function addproduct()
    {
        $data["users"] = $this->common->readdatafromcollectionbetween("Category");
        $this->template->template_render('service_add', $data);
    }

    public function company()
    {
        $data["company"] = $this->common->readdatadocument("contactInfo", 0);

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

    public function geofence()
    {
        $data = array();
        $balti = array();
        $data["events"] = $this->common->readdatafromcollectionwhereclause("events");
        foreach ($data["events"] as $id => $staffdata) {

            //foreach($staffdata as $k){


            $x = $this->common->readdatafromcollectionwhereclause("staff", $staffdata['staffId']);
            foreach ($x as $c => $l) {
                // echo "<pre>";
                // print_r($l);
                // echo "</pre>";
                $ceta[0] = '<b>' . $l["firstName"] . ' ' . $l["lastName"] . '</b><br>Email: <b>' . $l["email"] . '</b><br>Phone: ' . $l["emergencyNumber"] . '<br>';
                $ceta[1] = $l['lat'];
                $ceta[2] = $l['lng'];
                $ceta[3] = ++$i;

                array_push($balti, $ceta);
                //}
            }


            //	echo "</pre>";
        }

        $data['tati'] = $balti;
        //    	echo "<pre>";
        //    print_r($data);
        //    echo "</pre>";       
        //    exit;
        $this->template->template_render('geofence', $data);
    }

    public function faq()
    {
        $data["guidelines"] = $this->common->readdatafromcollectionbetween("guidelines");
        $this->template->template_render('faq', $data);
    }

    public function uploadGuideline()
    {
        $firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();
        $data = $this->input->post();

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

        $id = time();
        $data['timestamp'] = $id * 1000;
        $response = $this->common->adddatamodel("guidelines", $id, $data);
        //    $this->template->template_render('category_add');
        if ($response) {
            $this->session->set_flashdata('successmessage', 'New Guideline added successfully..');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error adding new Guideline..');
        }
        redirect(base_url() . 'dashboard/faq');
    }

    public function iechart()
    {
        $data = $this->common->get_iechartdata();
        $res = "['" . implode("', '", array_keys($data)) . "']";
        $income = "['" . implode("', '", array_column($data, 'income')) . "']";
        $expense = "['" . implode("', '", array_column($data, 'expense')) . "']";
        echo json_encode(array('res' => $res, 'income' => $income, 'expense' => $expense));
    }
    public function remindermark()
    {
        $data = array('r_isread' => 1);
        $this->db->where('r_id', $this->input->post('r_id'));
        echo $this->db->update('reminder', $data);
    }


    function send_notification($token_id, $title, $body, $id, $type)
    {

        $icon = base_url('assets/uploads/logo.png');

        $finalPostArray = array(
            'registration_ids' => $token_id,
            'notification' => array(
                'body' => $body,
                'title' => $title,
                "image" => $icon,
                "sound" => "default"
            ),
            "data" => array(
                "click_action" => "FLUTTER_NOTIFICATION_CLICK",
                "type" => $type,
                "id" => $id,
                "sound" => "default",
                "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;
    }
}
