<?php
 header("Access-Control-Allow-Origin: *"); 
 //header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
 //header('Access-Control-Expose-Headers', 'Accept-Ranges, Content-Encoding, Content-Length, Content-Range');
 header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
 
 //header('Content-type: application/xml');
 
 
  
//error_reporting(0);

require_once("Classes/initializer.php");


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';


// use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\Exception;

// require 'PHPMailer/src/Exception.php';
// require 'PHPMailer/src/PHPMailer.php';
// require 'PHPMailer/src/SMTP.php';


// require_once("PHPMailer/PHPMailer.php");
// require_once("PHPMailer/Exception.php");
// require_once("PHPMailer/SMTP.php");

// use PHPMailer\PHPMailer;
// use PHPMailer\SMTP;
// use PHPMailer\Exception;

// use PHPMailer/PHPMailer;
// use PHPMailer/Exception;
// use PHPMailer/SMTP;

//require_once("Classes/qr-code.php");

//require_once("UpdateServer.php");


//Where the server should find ONLINE Orders
//define("ONLINE_ORDER_URL", "http://videals.biz/APEX_POS_TEST/APEX-POS-DB/index.php?get_ONLINE_ORDERS=get_ONLINE_ORDERS");

/////
//error_log(print_r($_POST,true));
// $DISHES_SERVED;
// $EDIT_ORDER_TOTAL;
 
$current_TIMESTAMP = new DateTime();

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = trim($_POST['action']);
   // error_log( print_R("hitted index" ,true) );
          switch($action) {
            case 'Get_Packages' : Get_Packages();break;
            case 'APP_VerifyUser' : APP_VerifyUser();break;
            case 'SetReviews' : SetReviews();break;
            case 'APP_UpdateOnesignal' : APP_UpdateOnesignal();break;
            case 'Send_Inquiry' : Send_Inquiry();break;
            case 'CreateItineraries' : CreateItineraries();break;
            case 'SaveActivityMyItinerary' : SaveActivityMyItinerary();break;
            case 'IMAGE_API' : IMAGE_API();break;
            case 'SaveMyItinerary' : SaveMyItinerary();break;
            case 'Reserve_activity' : Reserve_activity();break;

            case 'Get_My_Itinerary' : Get_My_Itinerary();break;
            case 'Marke_Itinerary_Attended' : Marke_Itinerary_Attended();break;
            case 'Remove_Itinerary_Pack' : Remove_Itinerary_Pack();break;
            case 'Get_Itinerary_pack_Data' : Get_Itinerary_pack_Data();break;
            case 'Like_Business' : Like_Business();break;
            case 'Like_Highlight' : Like_Highlight();break;
            case 'Like_Pack' : Like_Pack();break;

            case 'Share_Business' : Share_Business();break;
            case 'Share_Highlight' : Share_Highlight();break;
            case 'Share_Pack' : Share_Pack();break;
            case 'update_myList' : update_myList();break;
            case 'get_Reviews': get_Reviews();break;
            case 'Get_my_Messages': Get_my_Messages();break;
            case 'Get_Highlights': Get_Highlights();break;
            case 'Save_suggestion': Save_suggestion();break;





          

            // ...etc...
        }
      
}elseif (isset($_GET['get_ONLINE_ORDERS']) ){
    TASTE_SERVER_ONLINE ();
}




// $createStaff = new Staff ("Blank");
// $createStaff ->First_Name = "Jon";
// $createStaff ->Last_Name = "Ismael";
// $createStaff ->Password = "356a192b7913b04c54574d18c28d46e6395428ab";
// $createStaff ->Privilege = "Staff";
// $createStaff ->Username = "Jonathan";
// $createStaff ->Salary = "995.55";

function Reserve_activity () {
    $UserID=Customer::find_by_id($_POST['Auth_User']);
    $FrugalData= json_decode ($_POST['frugalData']);
    $Business= json_decode ($_POST['Businenss']);

    $pack_id=  trim($_POST['Pack_id']);

    if (Itinerary::Verify_IF_UserItinerary($UserID->id, $pack_id)) {
        $itinerary = new Itinerary ("Blank");
        $itinerary->Bus_id = $Business;
        $itinerary->User_id =$UserID->id;
        $itinerary->Package_id =$pack_id;
        $itinerary->RequestedDate =  date( 'Y-m-d H:i:s',strtotime($FrugalData->fromDate));
        $itinerary->To_Requested_Date = date( 'Y-m-d H:i:s',strtotime( $FrugalData->toDate));
        $itinerary->NumberofPeron = $FrugalData->NumberOfPerson;

        if ( $itinerary->save() ) {

            //se should alert vendor
            PotencialSale($UserID->id,  $itinerary->Bus_id, $itinerary->Package_id,$itinerary->RequestedDate, $itinerary->id) ;
            
            echo json_encode (  array ("result"=>false, "Itinerary"=> Itinerary::getMyItinerary($UserID->id), "Message"=>"The activity was added to your itinerary and the vendor was contacted"));

        } else {
            echo json_encode (  array ("result"=>false, "Message"=>"This activity could not be added to your itinerary."));

        }
        

    }else {
        echo json_encode (  array ("result"=>false, "Message"=>"This activity is currently in your itinerary."));
   
       }


 }


 function SaveActivityMyItinerary() {

    $UserID=json_decode (trim($_POST['Auth_User']));
    error_log( print_R("user hitteed",true) );

    error_log( print_R( trim($_POST['Auth_User']),true) );
    $RequestedDate = trim($_POST['DATEPaased']); 
    $Date_Events= json_decode ($_POST['Events']);

    error_log( print_R("SaveActivityMyItinerary hitteed",true) );
    error_log( print_R($Date_Events,true) );



    if (Itinerary::Verify_IF_UserItinerary($UserID,   $Date_Events->id )) {
        ///here will check if user has any itinerary Pending

         # code...
        //$RequestedDate = $Date_Events[$key]->Day ;
        //$NOP = $Date_Events[$key]->NumberofPerson ;
        $NOP = 1 ;


          //Creating itinerary Object
                //$itinerayData =$Pack_value[0];
               //setting itinenary based on  values
               $itinerary = new Itinerary ("Blank");
               $itinerary->Bus_id =$Date_Events->Bus_id;
               $itinerary->User_id =$UserID;
               $itinerary->Package_id =$Date_Events->id;
               $itinerary->RequestedDate = $RequestedDate;
               $itinerary->NumberofPeron =$NOP;
 

               if ($itinerary->save()) {
                PotencialSale ($itinerary->User_id, $itinerary->Bus_id,$itinerary->Package_id, $itinerary->RequestedDate,$itinerary->id  );
               }  

 
     
    echo json_encode (  array ("result"=>true, "Message"=>"Your activity has been added to your itinerary. We have notified  the service provider to arrange payment and confirm availability"));
    } else {
     echo json_encode (  array ("result"=>false, "Message"=>"This activity is already in your itinerary."));

    }
    
 }


function SaveMyItinerary() {

      $UserID=json_decode (trim($_POST['Auth_User']));
    $Date_Events= json_decode ($_POST['Events']);

    if (Itinerary::Verify_IF_UserItinerary($UserID)) {
        ///here will check if user has any itinerary Pending

    foreach ($Date_Events as $key => $value) {
        # code...
        $RequestedDate = $Date_Events[$key]->Day ;
        $NOP = $Date_Events[$key]->NumberofPerson ;

          //Creating itinerary Object
          foreach ($Date_Events[$key]->Packs as $Pack_key => $Pack_value) {
               $itinerayData =$Pack_value[0];
               //setting itinenary based on  values
               $itinerary = new Itinerary ("Blank");
               $itinerary->Bus_id =$itinerayData->Bus_id;
               $itinerary->User_id =$UserID;
               $itinerary->Package_id =$itinerayData->id;
               $itinerary->RequestedDate = $RequestedDate;
               $itinerary->NumberofPeron =$NOP;
 

               if ($itinerary->save()) {
                PotencialSale ($itinerary->User_id, $itinerary->Bus_id,$itinerary->Package_id, $itinerary->RequestedDate,$itinerary->id  );
               }  

          }

    }
    
    echo json_encode (  array ("result"=>true, "Message"=>"Your Itinerary has been created. We have notified all the service providers in your itinerary to arrange payment and confirm availability"));
    } else {
     echo json_encode (  array ("result"=>false, "Message"=>"You have an itinerary with pending activities. Feel free to add other activities individually"));

    }
    
 }

function TEST_cURL (){
    //echo json_encode (  Orders::FindONLINEOrders());
    echo json_encode (  array (
        'Orders'=>  Orders::FindONLINEOrders(),
        'Customers'=> Customer::FindRegistered(),
        'Reservation'=> Reservation::GetOnlineReservations()
    )
       
    );

}


function Save_suggestion () {
    $Suggestion = new Suggestion ("Blank");
    
    foreach( $_POST as $attribute=>$value){ 
         if(property_exists($Suggestion,$attribute)) {
            $Suggestion ->$attribute =addslashes(trim($value)) ;
         }
       }

      /// $Suggestion->$Comment = addslashes(trim($Suggestion->$Comment));

       echo json_encode (   $Suggestion->save());

}



function SetReviews() {
    define('UPLOAD_DIR', 'BVIS_IMG/');

 
   // $requestedIMG = file_get_contents(trim($_POST['URL']));

    $Review = new Reviews ("Blank");
    
    foreach( $_POST as $attribute=>$value){ 
         if(property_exists($Review,$attribute)) {
            $Review ->$attribute =trim($value) ;
         }
       }

       //$Review ->$Review = "PROVIDED";
       //we will need to mark the itierary as reviewed
       ///WE traform the image and the save it
       if ($Review->Image != "false") {

        $image_parts = explode(";base64,", $Review->Image);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);

        $file = UPLOAD_DIR . md5(uniqid() ).'.jpg';
 
        if ( file_put_contents($file, $image_base64)) {
            $Review->Image = RESOURCE_URL .$file;

            $Review->save();

        } else {
            $Review->Image = RESOURCE_URL ."BVIS_IMG/noneImg.jpg";
            $Review->save();
        }
          } else {
                # code...
                $Review->Image = RESOURCE_URL ."BVIS_IMG/noneImg.jpg";
                 $Review->save(); 
           }


       //$Review ->$Review = "PROVIDED";
        //we will need to mark the itierary as reviewed
        $itinerary = Itinerary::find_by_id(trim($_POST['Itinerary_Item']));
        $itinerary->Review ="PROVIDED";
        $itinerary->save();

        //we should notify by email the 
        UserReviews($Review) ;


           echo json_encode  ( true );


}


function IMAGE_API (){
   $file_info = new finfo(FILEINFO_MIME_TYPE);
   $requestedIMG = file_get_contents(trim($_POST['URL']));
   $mime_type = $file_info->buffer( $requestedIMG);
    echo json_encode ( 'data:image/' . $filetype .';base64,' . base64_encode($requestedIMG) );
}


function Share_Pack() {
    $Business = Packages::find_by_id (trim($_POST['Pack_id']));

    $Business->Shares = $Business->Shares + 1;
      // $Business->save();
      unset( $Business->LongDescription);
    echo json_encode (  $Business->save());
}



function Share_Highlight () {
    $Highlight = Highlights::find_by_id (trim($_POST['highlight']));

    $Highlight->Shares = $Highlight->Shares + 1;
   // $Business->save();
     unset( $Highlight->LongDescription);
     unset($Highlight->Content);
     unset($Highlight->Short_Intro);
     $Highlight->save();
     Get_Highlights();

}

function Share_Business () {
    $Business = Business::find_by_id (trim($_POST['Bus_id']));

    $Business->Shares = $Business->Shares + 1;
   // $Business->save();
     unset( $Business->LongDescription);
    echo json_encode (  $Business->save());
}

function Get_my_Messages (){
    $userID =trim($_POST['Auth_User']);
$sql = "SELECT * FROM `BVIS_Messages` WHERE `DateAdded` > (NOW() - INTERVAL 1 MONTH) AND `User_id` = '{$userID}'";

    $msgs = Messages::find_by_sql ( $sql,"chatting");

    $Organized_msg =[];

    foreach($msgs as $msg)
{ 
    $Organized_msg[$msg->Bus_id][] = $msg;
}


echo json_encode ( $Organized_msg );


}

function Get_Highlights() {
    $sql = "SELECT * FROM `BVIS_Highlights` WHERE `Active` = 'Yes'";

     echo json_encode ( Highlights::find_by_sql ($sql,"Highlights_logo") );

}

function get_Reviews() {
    $id = trim($_POST['Id']);
  
    if (trim($_POST['Mode_Passed']) == 'Package') {
        $sql ="SELECT * FROM `BVIS_Reviews` WHERE `Package_id`='{$id}' AND `Public`='Yes'";
    } else {
        # code...
        //witing for business reviews requests
        $sql ="SELECT * FROM `BVIS_Reviews` WHERE `Bus_id`='{$id}' AND `Public`='Yes'";
		 
    }

 
        $review = Reviews::find_by_sql ( $sql,"SettingReviews");

       
 

    echo json_encode (  [ $review ] );

    
 
}

function update_myList() {
    $list = json_decode(trim($_POST['List']));


    $newList =  [];
    $i=0;
    foreach ( $list  as $key => $value) {
        $sql = "SELECT * FROM `BVIS_Packages` WHERE `id`= '{$value->id}'";

        $pack = Packages::find_by_id ( $value->id, "PackagesList");

         $newList[$i] = $pack ;
         $i++;

    }

    echo json_encode ( $newList );
    
}

function Like_Pack () {
    $pack = Packages::find_by_id (trim($_POST['Pack_id']));


    $pack->Likes = $pack->Likes + 1;
    unset( $pack->LongDescription);

   // $Business->save();
    echo json_encode (  $pack->save());


    ///we should returno serverdata and sotre 

}


function Like_Highlight() {
     
    $Highlights = Highlights::find_by_id (trim($_POST['highlight']));

    $Highlights->Likes = $Highlights->Likes + 1;
    unset($Highlights->Content);
    unset($Highlights->Short_Intro);

    echo json_encode ($Highlights->save());


}


function Like_Business() {
 
    $Business = Business::find_by_id (trim($_POST['Bus_id']));


    $Business->Likes = $Business->Likes + 1;
   // $Business->save();
    echo json_encode (  $Business->save());

   
   // Get_Packages ();


}
 
function Get_Itinerary_pack_Data () {
    $sql = "SELECT * FROM `BVIS_Itineraries` WHERE `id`='{$_POST['Pack_id']}'";
    $itinerayPack = Itinerary::find_by_sql ($sql, 'Reviewing' );
     

    echo json_encode  ($itinerayPack );



}

function Remove_Itinerary_Pack() {
    $itineray = Itinerary::find_by_id (trim($_POST['Pack_id']));
    
    $itineray->Confirmation = "REMOVED";

    if ($itineray->save() ) {
        echo json_encode ( Itinerary::getMyItinerary($itineray->User_id));
    } else {
        echo json_encode ( false);
    }
     

 
}


function Marke_Itinerary_Attended () {
    $itineray = Itinerary::find_by_id (trim($_POST['Pack_id']));
    
    $itineray->Confirmation = "Attended";

    if (    $itineray->save() ) {
        echo json_encode ( Itinerary::getMyItinerary($itineray->User_id));
    } else {
        echo json_encode ( false);
    }
     

 
}

function Get_My_Itinerary() {

    //$requestedIMG = file_get_contents(trim($_POST['Auth_User']));
    echo json_encode ( Itinerary::getMyItinerary(trim($_POST['Auth_User'])) );


}

function  CreateItineraries() {

    ///this function will attend to create
    //randon itineries 

    //we get the current datetime

    
    //$Categories = Categories::getMyCategories();

    $BusinessUsed = [];
    $CatToExclude =[];

    $ItinerariesCollection = [];
 
    $Activities = [];

    $frugalData ;

    $tempFrom;
    $tempTo;
    $numOfDays;
    $frugalBudget;
    $frugaLNOP;
    $NorrowIsland;


    if (isset($_POST['frugalData']) && !empty ($_POST['frugalData']) ) {
        $frugalData = json_decode ( $_POST['frugalData']);
        $tempFrom = new Datetime($frugalData->fromDate);
        $tempTo = new Datetime($frugalData->toDate);
        //difference between two dates
        $diff = date_diff( $tempFrom, $tempTo);
        $numOfDays = $diff->format("%a") ;

        $frugalBudget=$frugalData->Budget;
        $frugaLNOP = $frugalData->NumberOfPerson;

       $NorrowIsland =  str_replace('_', ' ', $frugalData->Island);
       // $NorrowIsland =    $frugalData->Island;
	    // $NorrowIsland = 'Virgin Gorda';
		

    } else {
        # code...
        $NorrowIsland = 'All';

    }
    

    ///this loop control the number of 
    //intineraries to be sent

     $loopTrakcer = 0; //this tracker will stop the loop if we don have any packages
    while (count($ItinerariesCollection)  <5 ||   $loopTrakcer==5 ) {
   
          //Thiss loop control the number of days
        //in the itinerary

        //we can consider getting the number of dates based
        //on the user inputs sent
        if ( isset($numOfDays) ) {
            # code...
            $Days =(int)($numOfDays == 0  ? 1 : $numOfDays ) ;
        } else {
            # code...
           $Days = rand(1,10);
        }
        

        if ( isset($tempFrom) ) {
            $curren_Date =$tempFrom;
        } else {
            $curren_Date = new Datetime();
        }
        
       
        if ( isset($frugaLNOP) ) {
            $numOfPerson =$frugaLNOP;
        } else {
            $numOfPerson  = rand(1,10);
        }
        
       
       

     



        for ($i=0; $i < $Days; $i++) { 
            $PackesCollection=[];
           
           // $itineraryDay =  $curren_Date->modify('+ '.i.' day');
            $PackesCollection ["Day"]=$curren_Date->format("Y-m-d");
            $PackesCollection ["NumberofPerson"]= $numOfPerson ;


            // array_push($PackesCollection, );

            if ( isset($frugalBudget) ) {
                $Budget = $frugalBudget/$Days;
            } else {
                $Budget = rand(800,5000)/$Days;
            }
        
            

           
            


            ///we need to pass details to the package 
            //function and it will return packages based 
            //on the criteria
            //We need the following values for SuggestPackages
            #1-Budget
            #2-Date
            #3-Total Days
            #4-Current Day

            $criteria = array(
            "numOfPerson"=>$numOfPerson,
            "Budget"=>$Budget,
             "Date"=>$curren_Date,
             "Total_Days"=>$Days,
             "Current_Day"=>$i,
             "BusinessUsed"=>$BusinessUsed,
            "CatToExclude"=> $CatToExclude,
             "NorrowIsland"=> $NorrowIsland );

            
            
           $PackesCollection ["Packs"]=Packages::SuggestPackages ($criteria);
           
           if (sizeof($PackesCollection ["Packs"] )>0 ) {
              foreach ( $PackesCollection ["Packs"] as $key => $value) {
                 array_push( $BusinessUsed,$value[0]->id);
                array_push($CatToExclude, $value[0]->Category);
                }

                array_push($Activities,$PackesCollection );
           }
          

          

            //if user provide budget, we will need 
            //to split based on the amount of days
            
            //before clearing  PackesCollection 
            //we pass it to the collections
           
          if (!isset($tempFrom) ) {
                $curren_Date =  $curren_Date->modify('+1 day');

            }



            # code...
        }//End of ontrol the number of days

        array_push($ItinerariesCollection,$Activities );
        $CatToExclude =[];

           
        if (isset($tempFrom) ) {
            $curren_Date = $tempFrom;
         }
     


        $Activities=[];

        $loopTrakcer++;
     

    }///END loop control the number of 
  

      
   ///before returning we need to make sure 
   //that there is not blank Itinerart
  //sleep(30);
    echo json_encode (array_filter($ItinerariesCollection));




}




function Get_Packages () {


 
   if ( isset( $_POST['Auth_User']) &&  $_POST['Auth_User'] !="false" ) {
        //We  have user set, so we send Businesses data and
        //otther goodies and all other data 
        echo json_encode (  array (
            'Business'=>  Business::FindActiveBusinesses(),
            'Categories'=> Categories::find_all(),
            "TotalPack" => Packages::findBusPackagesCount ()
           // 'Bus_packages'=>  Packages::FindActivePackages(),
    
            // 'Customers'=> Customer::FindRegistered(),
            // 'Reservation'=> Reservation::GetOnlineReservations()
        )
           
        );
        
   }else { 
    //We dont have user set, so we send Businesses data and
    //otther goodies
    echo json_encode (  array (
        'Business'=>  Business::FindActiveBusinesses(),
        'Categories'=> Categories::find_all(),
        "TotalPack" => Packages::findBusPackagesCount ()
       // 'Bus_packages'=>  Packages::FindActivePackages(),

        // 'Customers'=> Customer::FindRegistered(),
        // 'Reservation'=> Reservation::GetOnlineReservations()
    )
       
    );

   }

 

    
}


function UserReviews($reviewObj) {
    //Getting Ready To email
    $User=Customer::find_by_id($reviewObj->User_id);
    $Business=Business::find_by_id($reviewObj->Bus_id);
    $Package=Packages::find_by_id($reviewObj->Package_id);
 

// //     // Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

 
//Server settings
// $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
// $mail->isSMTP();                                            // Send using SMTP
// $mail->Host       = "localhost";              // Set the SMTP server to send through
// $mail->SMTPAuth   = false;                                   // Enable SMTP authentication
// $mail->Username   = 'test@videals.biz';                     // SMTP username
// $mail->Password   = '12345678';   
// // $mail->SMTPAutoTLS = 1025; 

// // $mail->isSMTP();                                            // Send using SMTP
// // $mail->Host       = "smtp.gmail.com";              // Set the SMTP server to send through
// // $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
// // $mail->Username   = 'vislander84@gmail.com';                     // SMTP username
// // $mail->Password   = 'Caribbean01';   
// // $mail->SMTPAutoTLS = false; 
//                         // SMTP password
// //$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
// $mail->Port       = 1025;   
// //$mail->SMTPSecure = "tls";


$mail->Port = 465;
$mail->Host = "mail.bvistaycation.com";
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->SMTPAuth = true;
$mail->Username   = 'info@bvistaycation.com';
$mail->Password   = 'Tourism1!';

// $mail->isSMTP();
// $mail->Host = 'localhost';
// $mail->SMTPAuth = false;
// $mail->Port = 1025;
//      // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

//Recipients
$mail->setFrom('info@bvistaycation.com', 'BVI Staycation');
$mail->addAddress(  $Business->email,  $Business->Name);     // Add a recipient

//$mail->addCustomHeader("BCC:info@bvistaycation.com");    // Add a recipient
 //$mail->addAddress('apexbvi@gmail.com');               // Name is optional
$mail->addReplyTo('info@bvistaycation.com', 'BVI Staycation');
// $mail->addCC('cc@example.com');
// $mail->addBCC('bcc@example.com');

// Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'BVI Staycation - USER REVIEW';


$HTML_message = file_get_contents('BVIS_Review.html');

$HTML_message = str_replace('%PackageName%',$Package->Name, $HTML_message);
$HTML_message = str_replace('%user%', $User->Full_Name, $HTML_message);
$HTML_message = str_replace('%Phone%',  $Business->Phone, $HTML_message);
$HTML_message = str_replace('%email%',  $User->Email, $HTML_message);
 $HTML_message = str_replace('%Rate%',  $reviewObj->Stars, $HTML_message);
  $HTML_message = str_replace('%BusName%',  $Business->Name, $HTML_message);
  $HTML_message = str_replace('%ImageLinnk%',  $reviewObj->Image, $HTML_message);




// $HTML_message = str_replace('%rating%', $Review->Starts, $HTML_message);
// $HTML_message = str_replace('%ref%', $Review->id, $HTML_message);
$HTML_message = str_replace('%comment%',  $reviewObj->Comment, $HTML_message);
// $HTML_message = str_replace('%BusName%', $Bus->Name, $HTML_message);
// $HTML_message = str_replace('%uEmail%',  $user->Email, $HTML_message);

$DD = new DateTime();
$dateR = new DateTime( $dateR);
$HTML_message = str_replace('%date%',   $DD->format("l jS \of F Y @ h:i:s A")  , $HTML_message);

$HTML_message = str_replace('%RequestedDate%',  $dateR->format("l jS \of F Y @ h:i:s A")  , $HTML_message);


$HTML_message = wordwrap($HTML_message,70);



$mail->Body    =   $HTML_message ;
$mail->AltBody =  strip_tags($HTML_message) ;

// $result = $mail->send();

if(!$mail->send()) {
 return false ;
    } else {
        $mail->addAddress(  "info@bvistaycation.com",  "BVI Staycation App");     // Add a recipient
        $mail->send();
        return true ;
    }





 }




function PotencialSale($userID="", $Bus_id, $pack_id, $dateR, $itinerary_ID) {
    //Getting Ready To email
    $User=Customer::find_by_id($userID);
    $Business=Business::find_by_id($Bus_id);
    $Package=Packages::find_by_id($pack_id);
    $itinerary=Itinerary::find_by_id($itinerary_ID);




// //     // Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

 
$mail->Port = 465;
$mail->Host = "mail.bvistaycation.com";
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->SMTPAuth = true;
$mail->Username   = 'info@bvistaycation.com';
$mail->Password   = 'Tourism1!';


// $mail->isSMTP();
// $mail->Host = 'localhost';
// $mail->SMTPAuth = false;
// $mail->Port = 1025;
                             // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

//Recipients
$mail->setFrom('info@bvistaycation.com', 'BVI Staycation');
$mail->addAddress(  $Business->email,  $Business->Name);     // Add a recipient
//$mail->addAddress('apexbvi@gmail.com');               // Name is optional
$mail->addReplyTo('info@bvistaycation.com', 'BVI Staycation');
// $mail->addCC('cc@example.com');
// $mail->addBCC('bcc@example.com');

// Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'BVI Staycation - PROSPECTIVE CUSTOMER';


$HTML_message = file_get_contents('BVIS_potencial.html');

$HTML_message = str_replace('%PackageName%',$Package->Name, $HTML_message);
$HTML_message = str_replace('%user%', $User->Full_Name, $HTML_message);
$HTML_message = str_replace('%Phone%',  $Business->Phone, $HTML_message);
$HTML_message = str_replace('%email%',  $User->Email, $HTML_message);
$HTML_message = str_replace('%provider%',  $Business->Name, $HTML_message);
$HTML_message = str_replace('%costPrice%',  $Package->Cost, $HTML_message);
$HTML_message = str_replace('%provider%',  $Business->Name, $HTML_message);
$HTML_message = str_replace('%NOPS%',  $itinerary->NumberofPeron, $HTML_message);
$HTML_message = str_replace('%BusName%',  $Business->Name, $HTML_message);



// $HTML_message = str_replace('%rating%', $Review->Starts, $HTML_message);
// $HTML_message = str_replace('%ref%', $Review->id, $HTML_message);
$HTML_message = str_replace('%comment%',  $Question, $HTML_message);
// $HTML_message = str_replace('%BusName%', $Bus->Name, $HTML_message);
// $HTML_message = str_replace('%uEmail%',  $user->Email, $HTML_message);

$data = array('Bus_id'=> $Business->id,
                   'User_id'=> $User->id,
                   'Package_id'=>$Package->id,
                   'SecureCode'=> SecureReply::GetSecureCode()
                );


 $ConfirmBTN = array('Bus_id'=> $Business->id,
                'User_id'=> $User->id,
                'Package_id'=>$Package->id,
                'SecureCode'=> SecureReply::GetSecureCode(),
                'Itinerary'=> $itinerary->id
             );



             



           

      $refURL = RESOURCE_URL."BVIS_BusReply.php?Data=".urlencode(serialize($data));
      $ConfirmURL = RESOURCE_URL."BVIS_BusConfirm.php?Data=".urlencode(serialize($ConfirmBTN));
      $Decline = RESOURCE_URL."BVIS_BusDecline.php?Data=".urlencode(serialize($ConfirmBTN));


    $HTML_message = str_replace('%HREF_URL%',  $refURL , $HTML_message);
    $HTML_message = str_replace('%Confirm_URL%',  $ConfirmURL , $HTML_message);
    $HTML_message = str_replace('%Decline_URL%',   $Decline , $HTML_message);


$DD = new DateTime();
$dateR = new DateTime( $dateR);
$HTML_message = str_replace('%date%',   $DD->format("l jS \of F Y @ h:i:s A")  , $HTML_message);

$HTML_message = str_replace('%RequestedDate%',  $dateR->format("l jS \of F Y @ h:i:s A")  , $HTML_message);


$HTML_message = wordwrap($HTML_message,70);



$mail->Body    =   $HTML_message ;
$mail->AltBody =  strip_tags($HTML_message) ;

// $result = $mail->send();

if(!$mail->send()) {
 return false ;
    } else {
        return true ;
    }





 }

function Send_Inquiry() {

    $User=Customer::find_by_id($_POST['Auth_User']);
    $Business=Business::find_by_id($_POST['BusID']);
    $Package=Packages::find_by_id($_POST['PackagesID']);
    $Question=addslashes(trim($_POST['Question']));

    // ini_set("SMTP","mail.videals.biz");
    // ini_set("smtp_port","25");


    //require_once("PHPMailer/PHPMailer.php");


// //     // Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

$mail->Port = 465;
$mail->Host = "mail.bvistaycation.com";
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->SMTPAuth = true;
$mail->Username   = 'info@bvistaycation.com';
$mail->Password   = 'Tourism1!';

   //  $mail->isSMTP();
// $mail->Host = 'localhost';
// $mail->SMTPAuth = false; 
// $mail->Port = 1025;
                                 // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom('info@bvistaycation.com', 'BVI Staycation App');
    $mail->addAddress(  $Business->email,  $Business->Name);     // Add a recipient
    //$mail->addAddress('apexbvi@gmail.com');               // Name is optional
    $mail->addReplyTo('info@bvistaycation.com', 'BVI Staycation App');
    // $mail->addCC('cc@example.com');
    // $mail->addBCC('bcc@example.com');

    // Attachments
    // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'BVI Staycation - INQUIRY';


	$HTML_message = file_get_contents('BVIS_inquiry.html');
 
	$HTML_message = str_replace('%PackageName%',$Package->Name, $HTML_message);
	$HTML_message = str_replace('%user%', $User->Full_Name, $HTML_message);
	$HTML_message = str_replace('%provider%',  $Business->Name, $HTML_message);
	// $HTML_message = str_replace('%rating%', $Review->Starts, $HTML_message);
	// $HTML_message = str_replace('%ref%', $Review->id, $HTML_message);
	$HTML_message = str_replace('%comment%',  $Question, $HTML_message);
	// $HTML_message = str_replace('%BusName%', $Bus->Name, $HTML_message);
    // $HTML_message = str_replace('%uEmail%',  $user->Email, $HTML_message);
    

    ///we create the link to tha page and 
    ///add it to the Reply Button
    $data = array('Bus_id'=> $Business->id,
                   'User_id'=> $User->id,
                   'Package_id'=>$Package->id,
                   'SecureCode'=> SecureReply::GetSecureCode()
                );

      $refURL = RESOURCE_URL."BVIS_BusReply.php?Data=".urlencode(serialize($data));

    $HTML_message = str_replace('%HREF_URL%',  $refURL , $HTML_message);

	
	$DD = new DateTime();

	$HTML_message = str_replace('%date%',   $DD->format("l jS \of F Y @ h:i:s A")  , $HTML_message);

    $HTML_message = wordwrap($HTML_message,70);
    

    
    $mail->Body    =   $HTML_message ;
    $mail->AltBody =  strip_tags($HTML_message) ;

  // $result = $mail->send();

   if(!$mail->send()) {
    echo json_encode ( false );
        } else {
            //we should save se the message
            $msg = new Messages ("Blank");
            $msg->Bus_id = $Business->id;
            $msg->User_id = $User->id;
            $msg->Message = $Question;
            $msg->Package_id =$Package->id;
            $msg->save();


            
            echo json_encode ( true );
        }

    ////////END PHPMailer //////
    

    // $User=Customer::find_by_id($_POST['Auth_User']);
    // $Business=Business::find_by_id($_POST['BusID']);
    // $Package=Packages::find_by_id($_POST['PackagesID']);
    // $Question=trim($_POST['Question']);



    //SETTING EMAIL 

  

	// //   $subject = "php mail test";
	// //   $message = "php test message";
    // //   $headers = 'From:' . $sender;
      
    // //  $RESULT =   mail($recipient, $subject, $message);

  
    //   $recipient =  $Business->email;

	//   $to =   'test@videals.biz';
	//   $subject = 'BVI Staycation inquiry';
	//   $from = 'BVI Staycation <noreply@bvistaycation>';
  
	//   // To send HTML mail, the Content-type header must be set
	//   $headers  = 'MIME-Version: 1.0' . "\r\n";
	//   $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    //   $headers .= "Importance: High\n";
    //   $headers .= "X-MSMail-Priority: High\n";
    //   $headers .= "X-Priority: 1 (Highest)\n";
	  
	  
	  
 
	//   // Create email headers
	//   $headers .= 'From: '.$from."\r\n".
	//       'Reply-To: '.$from."\r\n" .
	//       'X-Mailer: PHP/' . phpversion();
  
  
	// //
	// $HTML_message = file_get_contents('BVIS_inquiry.html');
 
	// $HTML_message = str_replace('%PackageName%',$Package->Name, $HTML_message);
	// $HTML_message = str_replace('%user%', $User->Full_Name, $HTML_message);
	// $HTML_message = str_replace('%provider%',  $Business->Name, $HTML_message);
	// // $HTML_message = str_replace('%rating%', $Review->Starts, $HTML_message);
	// // $HTML_message = str_replace('%ref%', $Review->id, $HTML_message);
	// $HTML_message = str_replace('%comment%',  $Question, $HTML_message);
	// // $HTML_message = str_replace('%BusName%', $Bus->Name, $HTML_message);
	// // $HTML_message = str_replace('%uEmail%',  $user->Email, $HTML_message);
	
	// $DD = new DateTime();

	// $HTML_message = str_replace('%date%',   $DD->format("l jS \of F Y @ h:i:s A")  , $HTML_message);

    // $HTML_message = wordwrap($HTML_message,70);
    
    


//	$RESULT =   mail($recipient, $subject, $HTML_message , $headers);
 
	  // $headers = 'From: <VIQueue@apexbvi.com>>' . "\r\n" .
  // 	  'Reply-To: <VIQueue@apexbvi.com>>';
  //
  // 	  mail('<apexbvi@gmail.com>', 'the subject', 'the message', $headers,
  // 	    '-info@apexbvi.com');
  //
  
 
   // echo json_encode ( $RESULT  );





}


function APP_UpdateOnesignal() {
    // error_log( print_R("APP_VerifyUser hitteed",true) );
    // error_log( print_R($_POST,true) );
 
     //we should return the updated user
     $result = Customer::UpdateOneSignal_ID($_POST);
    error_log( print_R($result ,true) );
 
    if ($result ) {
      echo json_encode ( Customer::find_by_id($_POST['id']),"Customer" );
    } else {
     echo json_encode ( false);
    }
    
     
 }
 



   
function APP_VerifyUser() {

    $Customer = new Customer ("Blank");
       
       //this is not save for customer rewards and credits
        error_log( print_R("SAME PHONE" ,true) );
                   
                       foreach($_POST as $attribute=>$value){
                           if(property_exists($Customer,$attribute)) {
                           $Customer->$attribute =addslashes (trim($value)) ;
                           }
                       }
                       
                    //    if( !empty ( $_POST['Optional_ID'] ) ) {
                              
                    //     $Customer->id=$_POST['Optional_ID'];
                    //        }

                    error_log( print_R("data send here PHONE" ,true) );
                    error_log( print_R( $Customer ,true) );
                    //before attending to stored checck if onesignal exist
                    //we also check for onesigna N/A value to avoid duplicating
                    if ($Customer->id == "" ) {
                     $Customer->id = Customer::GetID_with_SignalID($Customer->OneSignal, $Customer->OneSignal_id );
                        //since this is an update we should reset all
                        //values set by admin to give rights to users
                    } 

                    // if ($Customer->Avatar == "") {
                    //     $Customer->Avatar="assets/avatar.svg";
                    // }
                    

 
                       $result = $Customer->save();
                       if ($result) {
                           echo json_encode (array(
                               'Req_State'=>true,
                               'Customer'=>Customer::find_by_id($Customer->id, "Customer")
                           ));
                          // echo json_encode ($Customer);
           
                       } else { echo json_encode (array(
                           'Req_State'=>false,
                           'Msg'=>"Could not veriry user. Contact administrator"
                       )); }
                       

}




// function MarkRegiteredCustomer_POS(){

//     global $database;

//     //storing new customers
//     $customerOnServer = $_POST['list'];

//     foreach( $customerOnServer as $key=>$value) {
//         $Customer = new Customer ("Blank");


//         foreach( $customerOnServer[$key] as $attribute=>$value){ 
//              if(property_exists($Customer,$attribute)  ) {

//                 //we only set id since we will only set $attribute Sent_to_POS
//                 if ($attribute=="id") {
//                     $Customer->$attribute =trim($value) ;
//                     $sql = "UPDATE `Customer` SET `Sent_to_POS`='YES' WHERE `id`='{$value}'";
//                     $Result = $database->query($sql);
//                 }
                 
               
//              }
//            }

//             //we need to set the other attributes before saving object
//          // $Customer->Sent_to_POS  = "FFF";


        
//     }

//     echo json_encode ( true);
   
    

// }

// function UpdateCustomer (){
//     echo json_encode ( Customer::find_by_id ($_POST['userID']) );
// }

// function Ask_ONLINE_To_Mark_Customer ($cutomorerList) {


//     $post = [
//         'action' => 'MarkRegiteredCustomer_POS',
//         'list'=> $cutomorerList
//     ];

// //    error_log( print_R( curl_exec($ch),true) );

    
//     $ch = curl_init();
//     curl_setopt($ch, CURLOPT_URL, ONLINE_ORDER_CURL);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

//     $response =  json_decode (curl_exec($ch));
   
//     error_log( print_R( $response ,true) );


//     // close the connection, release resources used
//     curl_close($ch);
   
//     //var_export($response);
//     //in here we handle the response  and we shoul store it in our local server
//     //error_log( print_R($f,true) );

// }

// function Update_Menu () {
// //EXCLUSIVE FOR SERVER
//  $uploads_Files = $_SERVER['DOCUMENT_ROOT'];
//           $tmp_name = $_FILES["CODED_FILE"]["tmp_name"];
//         // basename() may prevent filesystem traversal attacks;
//         // further validation/sanitation of the filename may be appropriate
//         $name = basename($_FILES["CODED_FILE"]["name"]);
//         //move_uploaded_file($tmp_name, "$uploads_Files/$name")
//        if ( move_uploaded_file($tmp_name, $uploads_Files."/uploaded".$name)) {
 
//             $query = file_get_contents($uploads_Files."/uploaded".$name);

//               $final = $uploads_Files."/uploaded".$name;
//               error_log( print_R($final,true) );

//                $temp =execute_sql($final);
           
//             unlink($final) or die("Couldn't delete file");
//              error_log( print_R($temp,true) );

//              echo json_encode (  $temp );
//             //echo json_encode ($Result);

//        }


// }

// function Local_SERVER_updateOnlineMenu () {

//     $Backup = new DBbackup();
//     $file = $Backup->backup(['MenuDishes' , 'SideDishes']);
 
//      $curlFile = curl_file_create($file,"sql", basename($file) );
 
//      $post = [
//          'action' => 'Update_Menu',
//          'CODED_FILE'=> $curlFile 
//      ];
//     //LOCAL SERVER LINK // / "http://192.168.0.102:8888/APEX-POS-DB/index.php"
//      $ch = curl_init();
//      curl_setopt($ch, CURLOPT_URL, ONLINE_ORDER_CURL);
//      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000);
//      curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
//      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
 
//      $response = json_decode (curl_exec($ch));
//      error_log( print_R( $response ,true) );
 
//      unlink($file) or die("Couldn't delete file");
//      curl_close($ch);
 
//      echo json_encode ($response);

// }


// function TASTE_SERVER_ONLINE (){
//     testWhy ();
  
// // $orderID = 10000000691;

// // $orderDetails = OrdersInfo::findDishInfo ($orderID,""); 

// // $itemsInOrder = array();


// // foreach ($orderDetails as $key => $value) {
// //     array_push($itemsInOrder, new item($orderDetails[$key]['DishInfo']->Qty ."X " .$orderDetails[$key]['DishInfo']->Name , $orderDetails[$key]['DishInfo']->Price, false)  ) ;

// //     //now loop choices and push to array
// //     $choices = $orderDetails[$key]['ItemChoices'];
// //     foreach ($choices as $Choicekey => $Choicevalue) {
// //         //looping options
// //         $options = $choices[$Choicekey]->Options;
// //         foreach ($options  as $Optkey => $Optvalue) {
// //             if ( $options[$Optkey]->checked==1 ) {
// //                 array_push($itemsInOrder, new item(strtoupper("  ".$options[$Optkey]->CustomName), "", false)  ) ;
// //                 array_push($itemsInOrder, new item("  ".$options[$Optkey]->Name , $options[$Optkey]->Price, false)  ) ;
// //             }
// //         }
     
// //     }

// //     //now looping extra
// //     $Extra = $orderDetails[$key]['Extra'];
// //     foreach ($Extra as $Checkey => $Checkvalue) {
// //         if ($Extra[$Extrakey]->checked != "false") {
// //           array_push($itemsInOrder, new item("  EXTRA", "", false));
// //           break;
// //         }
        
        
// //     }

// //         foreach ($Extra as $Extrakey => $Extravalue) {
// //             if ($Extra[$Extrakey]->checked != "false") {
// //                 array_push($itemsInOrder, new item("  ".$Extra[$Extrakey]->Name , $Extra[$Extrakey]->Price, false)  ) ;

// //             }

// //         }
  
   


// // }

// // error_log( print_R($orderDetails,true) );
// // error_log( print_R($itemsInOrder,true) );



// // OrdersExtra::FindOrderExtra ($orderID="", $OrderDishInfo_id="");
// // OrdersItemChoice::FindOrderChoices ($orderID="", $OrderDishInfo_id=""); 

// //first loop to find dishes in orddr



// // $filename = '/var/www/APEX_BACKUO' . date("Y-m-d-H-i-s") . '.sql';

// // /*
// //  *  db backup
// //  */

// // $command = "mysqldump --single-transaction -hDB_SERVER -uDB_USER -pDB_PASS DB_NAME > $filename";
// // system($command);
// // if ($command == '') {
// //     /* no output is good */
// //    // echo 'not done';
// //     error_log(print_r($filename ,true));
// // } else {
// //    /* we have something to log the output here */
// //     //echo 'done';
// //     error_log(print_r($filename ,true));
// // }



//      // $f = json_decode (file_get_contents(ONLINE_ORDER_URL));
 
//     // error_log( print_R($f,true) );
//     // echo json_encode ($f);

//     // $geteData = "SELECT `Interactive_date` FROM `Orders` ORDER BY `Interactive_date` ASC LIMIT 1";
//     // $Interactive_date = $database->query($geteData);
//     // $FinalData = mysqli_fetch_array( $Interactive_date, MYSQLI_NUM) ;


//     // $getCusomerData = "SELECT `Interactive_date` FROM `Customer` ORDER BY `Interactive_date` ASC LIMIT 1";
//     // $Interactive_date_Customer = $database->query($getCusomerData);
//     // $FinalDataCustomer = mysqli_fetch_array( $Interactive_date_Customer, MYSQLI_NUM) ;

//     //error_log( print_R( $FinalData[0][0],true) );

// //     $post = [
// //         'action' => 'TEST_cURL'
// //     ];
        
// //     $ch = curl_init();
// //     curl_setopt($ch, CURLOPT_URL, ONLINE_ORDER_CURL);
// //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// //     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000);
// //     curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
// //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// //     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

// //     $response = json_decode (curl_exec($ch));

// //     // close the connection, release resources used
// //     curl_close($ch);
   
// //     //var_export($response);
// //     //in here we handle the response  and we shoul store it in our local server
// //     error_log( print_R($f,true) );
// //     $resutl = $response;
   
    
// //     //storing new customers
// //     $customerOnServer = $response->Customers ;

// //     foreach( $customerOnServer as $key=>$value) {
// //         $Customer = new Customer ("Blank");


// //         foreach( $customerOnServer[$key] as $attribute=>$value){ 
// //              if(property_exists($Customer,$attribute)) {
// //                  $Customer->$attribute =trim($value) ;
               
// //              }
          
        
// //            }
 
// //            //we need to set the other attributes before saving object
// //           $Customer->Sent_to_POS  = "YES";
// //          // $Customer->Interactive_date  =  date('Y-m-d');

// //           error_log( print_R("before saving ",true) );
// //           error_log( print_R($Customer,true) );
// //           unset($Customer->Interactive_date);
// //           error_log( print_R($Customer,true) );

// //           $Customer->verifyCustomer();

        
// //     }
    

// //     foreach( $response->Orders as $index=>$value) {

// //          RegisterONLINE_Sales($value);
        
// //      }


 




   

// //     //Tell server to Mark Users
// //    Ask_ONLINE_To_Mark_Customer ( $customerOnServer);

  


// //     //this is for testing...not needed
// //     echo json_encode ($response);



// }




//  function execute_sql($file){
//     //1st method; directly via mysql
//     $mysql_paths = array();
//     //use mysql location from `which` command.
//     $mysql = trim(`which mysql`);
//     if (is_executable($mysql))
//     {
//         array_unshift($mysql_paths, $mysql);
//     }
//     //Default paths
//     $mysql_paths[] = '/Applications/MAMP/Library/bin/mysql';  //Mac Mamp
//     $mysql_paths[] = 'c:\xampp\mysql\bin\mysql.exe';//XAMPP
//     $mysql_paths[] = '/usr/bin/mysql';  //Linux
//     $mysql_paths[] = '/usr/local/mysql/bin/mysql'; //Mac
//     $mysql_paths[] = '/usr/local/bin/mysql'; //Linux
//     $mysql_paths[] = '/usr/mysql/bin/mysql'; //Linux

//     $database = DB_NAME;
//     $db_hostname = DB_SERVER;
//     $db_username= DB_USER;
//     $db_password = DB_PASS;
//     $file_to_execute = escapeshellarg($file);
//     foreach($mysql_paths as $mysql)
//     {
//         if (is_executable($mysql))
//         {
//                 $execute_command = "\"$mysql\" --host=$db_hostname --user=$db_username --password=$db_password $database < $file_to_execute";
//                 $status = false;
//                 system($execute_command, $status);
//                 return $status == 0;
//         }
//     }

//     if ($this->db->dbdriver == 'mysqli')
//     {
//         //2nd method; using mysqli
//         mysqli_multi_query($this->db->conn_id,file_get_contents($file));
//         //Make sure this keeps php waiting for queries to be done
//         do{} while(mysqli_more_results($this->db->conn_id) && mysqli_next_result($this->db->conn_id));
//         return TRUE;
//     }

//     //3rd Method Use PDO as command. See http://stackoverflow.com/a/6461110/627473
//     //Needs php 5.3, mysqlnd driver
//     $mysqlnd = function_exists('mysqli_fetch_all');

//     if ($mysqlnd && version_compare(PHP_VERSION, '5.3.0') >= 0) 
//     {
//         $database = $this->db->database;
//         $db_hostname = $this->db->hostname;
//         $db_username= $this->db->username;
//         $db_password = $this->db->password;
//         $dsn = "mysql:dbname=$database;host=$db_hostname";
//         $db = new PDO($dsn, $db_username, $db_password);
//         $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
//         $sql = file_get_contents($file);
//         $db->exec($sql);

//         return TRUE;

//     }

//     return FALSE;
// }


// function KitchenHistory(){

//     $Report = array(
//         "NumberOfOrders"=>OrdersInfo::NumberOfOrder_chef_Interact(),
//          "DeclinedByChef"=>OrdersInfo::DeclindedByChef(),
//          "PraparedByChef"=>OrdersInfo::PraparedByChef(),
//          "Dishes"=>OrdersInfo::Dishes_chef_Interact()
//                          );

//      echo json_encode ( $Report);

// }

// function getProfitReport () {
//     echo json_encode (  Expenses::MonthtlyProgress_Inventory ($_POST['dateToReport'],"") );
// }

// function getStafDailyReport () {
//     error_log(print_r($_POST['Date'],true));
//     $report = array (
//         "Orders_Summary"=>array ( "GRAPH_DATA"=>Orders::StaffCatSells ($_POST['Date'], $_POST['StaffID']) ) 
//         // ,
//         // "Sales_Totals"=>array ( "TOTAL_SALES_GRAPH_DATA"=>Orders::StaffTotalSells ($_POST['Date'], $_POST['StaffID']) ) ,
      
// );

// echo json_encode ( $report);

 
// }

// function OverViewReport (){
//     error_log(print_r($_POST['SummaryDate'],true));

//     $myTotalSales = Orders::GetTotalSales($_POST['SummaryDate']);

//     $report = array (
//             "TotalSales"=>$myTotalSales == null ? '0':$myTotalSales ,
//             "NewCustomers"=>Customer::FindNewCustomers($_POST['SummaryDate']),
//             "RepeatCustomers"=> Orders::FindRepeatCustomers($_POST['SummaryDate']),
//             "NumberOfOrders"=>Orders::NumberOfOrders($_POST['SummaryDate']),
//             "DoughnutChart"=>Orders::doughnutChartData($_POST['SummaryDate']),
//             "CashBreakDown"=>Orders::CashBreakDown($_POST['SummaryDate']),
//             "MonthtlyProgress"=>Orders::MonthtlyProgress(),
//             "soldDishes"=> Orders::soldDishes()
//     );

//     echo json_encode ( $report);

// }

// function UserOrders() {
//     error_log( print_R("UserOrders",true) );
//    // echo json_encode ( false );

//     echo json_encode ( Orders::UserOders(trim($_POST['UserID'])));

// }

// function SetStaffPermission () {
//     $Staff = Staff::find_by_id($_POST['StaffID']);
//     $Staff->Permission =$_POST['Permission'];

//     if ($_POST['Permission'] =="") {
//         $Staff->Permission ="NO PERMISSION";
//     } else {
//         $Staff->Permission =$_POST['Permission'];
//     }
    
//     if ($Staff->save()) {
//         echo json_encode (  Staff::find_all("Staff"));
//     } else {
//         echo json_encode ( false);
//     }


// }

// function SetDailyFloat(){
 
//     error_log( print_R($_POST,true) );
//     $Staff = Staff::find_by_id($_POST['StaffID']);
//     $Staff->Daily_Float =$_POST['Amount'];

//     if ($Staff->save()) {
//         echo json_encode (  Staff::find_all("Staff"));
      
//     } else {
//         echo json_encode ( false);
//     }
    
    
// }

// function APP_GetMenu() {
//     error_log( print_R("APP_GetMenu hitteed",true) );
  

//    //error_log( print_R( MenuDishes::find_all("MenuDishes"),true) );
//     // error_log( print_R( "que viste",true) );
    
//     $Data_ForAPP = array(
//         "SideDishes"=>SideDishes::find_all("SideDishes"),
//         "MenuDishes"=>MenuDishes::find_all("MenuDishes")
//                         );

//                         // MenuDishes header('Content-type:application/json;charset=utf-8');
//                         // header('Content-type: application/json');

    
//     echo json_encode ( $Data_ForAPP );

  
    

// }

// function APP_UpdateOnesignal() {
//    // error_log( print_R("APP_VerifyUser hitteed",true) );
//    // error_log( print_R($_POST,true) );

//     //we should return the updated user
//     $result = Customer::UpdateOneSignal_ID($_POST);
//    error_log( print_R($result ,true) );

//    if ($result ) {
//      echo json_encode ( Customer::find_by_id($_POST['id']) );
//    } else {
//     echo json_encode ( false);
//    }
   
    
// }

// function CancelReservationStaff () {
//     global $database;
  
//     $id= trim($_POST["ReservationID"]);
//     if ($_POST["OnlineUpdate"]==true) {
//         $sql = "UPDATE `Reservation` SET `Status`='CANCELLED' WHERE `ONLINE_id` = '".$id."' ";
  
//      } else {
//          $sql = "UPDATE `Reservation` SET `Status`='CANCELLED' WHERE `id` = '".$id."' ";
//     }
    
//     $Result = $database->query($sql);
 

//    // error_log( print_R($Result,true) );

//     if ($Result ) {
//          //we need to alert user 
//          if ($_POST["OnlineUpdate"]==true) {
//             $reservation =  Reservation::getReservation_by_ONLINE_ID($id);
//          } else {
//             $reservation =  Reservation::find_by_id( trim($id));
//          }
         
        

//         if (SERVER_MODE=="ONLINE") {
//             $post = [
//                 'action' => 'CancelReservationStaff',
//                 'OnlineUpdate'=>true,
//                 'ReservationID'=>$reservation->ONLINE_id
//                ];
        
//             ONLINE_SERVER_MARKER ($post);
//            }else{

//             $confirmDate = new Datetime ( $reservation->Time);

//             $msg = "Hi ".Customer::GetCustomerName($reservation->Customer_id).", your reservation for ". $reservation->Person ." person at The Best restaurant at ".$confirmDate->format('g:ia \o\n l jS F Y')." Was CANCELLED ";

//             $CustomerData =array(
//                 "token"=>Customer::GetCustomerToken($reservation->Customer_id),
//                 "Msg"=>$msg,
//                 'header'=>'RESERVATION',
//                 'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
//                 'bigPic'=>'http://apexbvi.com/cancelPOS' ///big pictures
//             );
                
//            }
       
//       //   error_log( print_R("CancelReservationStaff" ,true) ); 
         
//          OneSignalsendMessage($CustomerData);

//         echo json_encode ( Reservation::GetReservations () );

       
//         // error_log( print_R("CancelReservationStaff 11111" ,true) );


        
//       } else {
//         //error_log( print_R("CancelReservationStaff FALSSSSSSSSS" ,true) );
//        echo json_encode ( false);
       

//       }

// }


// function TablesReports () {
//    // global $database;
//     //getting all table orders were table/taps are open 
//    // $sql = 'SELECT * FROM `Orders` WHERE `Cash`= "UNPAID" AND `TableNum` != "N/A" ';

//     echo json_encode (  Orders::FindUnpaidDineInOrders());

// }

// function ConfirmReservStaff () {

//     global $database;

//     $id= trim($_POST["ReservationID"]);
//     if ($_POST["OnlineUpdate"]==true) {
//         $sql = "UPDATE `Reservation` SET `Status`='CONFIRMED' WHERE `ONLINE_id` = '".$id."' ";
  
//      } else {
//         $sql = "UPDATE `Reservation` SET `Status`='CONFIRMED' WHERE `id` = '".$id."' ";
//     }


//     $Result = $database->query($sql);
 

//     if ($Result ) {
 
//           //we need to alert user 
//           if ($_POST["OnlineUpdate"]==true) {
//             $reservation =  Reservation::getReservation_by_ONLINE_ID($id);
//          } else {
//             $reservation =  Reservation::find_by_id( trim($id));
//          }

//          if (SERVER_MODE=="LOCAL") {
//             $post = [
//                 'action' => 'ConfirmReservStaff',
//                 'OnlineUpdate'=>true,
//                 'ReservationID'=>$reservation->ONLINE_id
//                ];
        
//             ONLINE_SERVER_MARKER ($post);
//             echo json_encode ( Reservation::GetReservations () );
            
//            }else{   
//                // error_log( print_R($reservation,true) );
       
//           // error_log( print_R(Customer::GetCustomerToken($reservation->Customer_id),true) );
       
//            $confirmDate = new Datetime ( $reservation->Time);
        
       
//              $msg = "This is to Confirm your reservation for ". $reservation->Person ." person at The Best restaurant at ".$confirmDate ->format('g:ia \o\n l jS F Y');
//              //$msg .= "
       
//            $CustomerData =array(
//               "token"=>Customer::GetCustomerToken($reservation->Customer_id),
//               "Msg"=>$msg,
//               'header'=>'RESERVATION CONFIRMED',
//               'bigPic'=>'http://apexbvi.com/icons.png', ///big pictures
//               'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
//            );
       
//            OneSignalsendMessage($CustomerData);

       
//     }
         

     
//       } else {
//        echo json_encode ( false);
//       }

//     //$reservation= Reservation::find_by_id( trim($_POST["ReservationID"]) );
    

 

// }

// function MarkReser_Attented () {
//     global $database;

//     $id= trim($_POST["ReservationID"]);

//     $sql = "UPDATE `Reservation` SET `Attended`='Yes' WHERE `id` = '".$id."' ";

//     $Result = $database->query($sql);

//     error_log( print_R($_POST,true) );
//     error_log( print_R($reservation,true) );

//     if ($Result ) {
//         echo json_encode ( Reservation::GetReservations () );
//       } else {
//        echo json_encode ( false);
//       }

//     //$reservation= Reservation::find_by_id( trim($_POST["ReservationID"]) );
    

// }

// function updateCustomer_Credit () {


//     $Customer = new Customer ("Blank");

//     foreach($_POST['updatedCustomer'] as $attribute=>$value){ 
//         if(property_exists($Customer,$attribute)) {
//         $Customer->$attribute =trim($value) ;
//       }
//     }

//     $Customer ->save();

 
//     if ($_POST["ConfirmPayment"] ==true && SERVER_MODE=="ONLINE") {
//         setlocale(LC_MONETARY,"en_US");
//         //money_format("We earnestly acknowledge your payment of %i", $Amount)
//       $msg =  money_format("We earnestly acknowledge your payment of %i", $_POST["Amount"])." Thank You!";

//       $CustomerData =array(
//          "token"=>Customer::GetCustomerToken($Customer->id ),
//          "Msg"=>$msg,
//          'header'=>'PAYMENT RECEIVED',
//          'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
//       );
  
//       OneSignalsendMessage($CustomerData);
//     }  

 

// }


// function GetStaffs() {

//     echo json_encode ( Staff::find_all(""));

// }

// function RemindUser() {
//     error_log( print_R($_POST,true) );

//     $reservation = Reservation::find_by_id($_POST["ReservationID"]);
//  // error_log( print_R($reservation,true) );

//    // error_log( print_R(Customer::GetCustomerToken($reservation->Customer_id),true) );

//     $confirmDate = new Datetime ( $reservation->Time);
 

//       $msg = "This is a reminder, you have a reservation for ". $reservation->Person ." person at The Best restaurant at ".$confirmDate ->format('g:ia \o\n l jS F Y');
//       //$msg .= "

//     $CustomerData =array(
//        "token"=>Customer::GetCustomerToken($reservation->Customer_id),
//        "Msg"=>$msg,
//        'header'=>'RESERVATION',
//        'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
//     );

//     OneSignalsendMessage($CustomerData);

// }

// function APP_VerifyUser() {

//     $Customer = new Customer ("Blank");

//     if (!empty($_POST['Optional_ID'] ) && isset($_POST['Optional_ID']) && $_POST['EDITING_USER']!="true" ) {
//         global $database;

//         //we are not editing. this is assuming that we
//         //are in a diferent phone or in a fresh app install 
//         $sql = "SELECT * FROM `Customer` WHERE `id`='{$_POST['Optional_ID']}' AND `Full_Name`='{$_POST['Full_Name']}' AND `DOB`='{$_POST['DOB']}' AND `Email`='{$_POST['Email']}' AND `Phone`='{$_POST['Phone']}' ";
//         $result =  $database->query($sql);
//         if($result->num_rows == 1 ){

//             foreach($_POST as $attribute=>$value){ 
//                 if(property_exists($Customer,$attribute)) {
//                 $Customer->$attribute =trim($value) ;
//               }
//             }



//             $Customer->id=$_POST['Optional_ID'];
//             error_log( print_R($Customer,true) );

//             //do not verify. Try saving since we have an Id
//             //$result = $Customer->verifyCustomer();
//             $result = $Customer->save();

//             if ($result) {
//                 echo json_encode (array(
//                     'Req_State'=>true,
//                     'Customer'=>Customer::find_by_id($_POST['Optional_ID'])
//                 )); 
//                // echo json_encode ($Customer);

//             } else { echo json_encode (array(
//                 'Req_State'=>false,
//                 'Msg'=>"Could not veriry user. Please ensure to grant necessary persmission to this app 77. Contact system administrator"
//             )); }

            
//         } else{
//             echo json_encode (array(
//                 'Req_State'=>false,
//                 'Msg'=>"The credentials do not match the ID in our records. Contact system administrator"

//             )); 
//         }

//     } else if ($_POST['EDITING_USER']=="true" ){
//            // error_log( print_R("you seeeSEEEEEEE CustomerUdating",true) );
//        // error_log( print_R($_POST['CustomerUdating'] ,true) );

//         //INCASE NEEDED !empty($_POST['CustomerUdating'] ) && isset($_POST['CustomerUdating']) 

//                     error_log( print_R("SAME PHONEv aasdfds" ,true) );
//                     error_log( print_R($_POST ,true) );


//          $customer_In_DB = Customer::find_by_id($_POST['Optional_ID']);

//          error_log( print_R($customer_In_DB  ,true) );

//             if ( $customer_In_DB->UUID == $_POST['UUID'] ) {

//                 //we need to ensure that user is updating 
//                 //credentials in the same phone
//                 error_log( print_R("SAME PHONE" ,true) );
                
//                     foreach($_POST as $attribute=>$value){ 
//                         if(property_exists($Customer,$attribute)) {
//                         $Customer->$attribute =trim($value) ;
//                         }
//                     }

//                     $Customer->id=$_POST['Optional_ID'];

//                     $result = $Customer->save();
//                     if ($result) {
//                         echo json_encode (array(
//                             'Req_State'=>true,
//                             'Customer'=>Customer::find_by_id($_POST['Optional_ID'])
//                         )); 
//                        // echo json_encode ($Customer);
        
//                     } else { echo json_encode (array(
//                         'Req_State'=>false,
//                         'Msg'=>"Could not veriry user. Contact administrator"
//                     )); }
                
//             } else {
//                 //the only reason of this to fail
//                 //is if we have an invalid ID or UUID Is not the same

//                 echo json_encode (array(
//                     'Req_State'=>false,
//                     'Msg'=>"The credentials do not match the ID in our records. Contact administrator 9"

//                 )); 
        
        
            
//             }
            
//     } else {

//         //we need to make sure that data is valid
//         //and the same as stoted 
//         error_log( print_R("final else",true) );
//         error_log( print_R($_POST,true) );

//         $DB_Customer = Customer::Find_By_OneSignalID($_POST['OneSignal_id']);

//         error_log( print_R($DB_Customer,true) );

//         if ( $DB_Customer->UUID == $_POST['UUID'] && $DB_Customer->DOB == $_POST['DOB'] && 
//         $DB_Customer->Full_Name == $_POST['Full_Name'] && $DB_Customer->Phone == $_POST['Phone'] && 
//         $DB_Customer->Email == $_POST['Email']  ) {
           
//             foreach($_POST as $attribute=>$value){ 
//                 if(property_exists($Customer,$attribute)) {
//                 $Customer->$attribute =trim($value) ;
//               }
//             }
        
//             //we need to set the other attributes before saving object
        
//             if (isset($Customer->id ) || isset($Customer->OneSignal_id ) ) {
//             //this mean that we had an update and will be updated.
//             //this update will need to be sent to the POS
//             $Customer->Sent_to_POS  = "No";
//             }
//             //$Customer ->Registed_Date  =  date('Y-m-d H:i:s') ;
//             //$Customer ->Points  = 1 ;
//             //$Customer ->id  = "24";
            
//             //echo json_encode ($Customer);
//             $result = $Customer->verifyCustomer();
//             if ($result) {
//                 echo json_encode (array(
//                     'Req_State'=>true,
//                     'Customer'=>Customer::find_by_id( $DB_Customer->id)
//                 )); 
//             } else { echo json_encode (false);}
//             //echo json_encode (false);
            
//         }else{
//             echo json_encode (array(
//                 'Req_State'=>false,
//                 'Msg'=>"This Device is currently registered. Kindly provide your previous credentials. Contact system administrator"

//             )); 
//         }
        
//     }
    
// }

// function sendMessage () {

//    // error_log(print_r(Customer::GetCustomerToken( trim($_POST['id']) )));
    
//     $CustomerData =array(
//         "token"=>Customer::GetCustomerToken( trim($_POST['id']) ),
//         "Msg"=>trim($_POST['Message']),
//         'header'=> "Hi ". trim($_POST['Name']),
//         'bigPic'=>'http://apexbvi.com/icons.png', ///big pictures
//         'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
//      );
 
 
//      $result = OneSignalsendMessage($CustomerData);
//  if ($result) {
//      echo json_encode (true);
//   } else { echo json_encode (false);}

// }

// function OrderReady() {
//     //error_log(print_r($_POST['StaffID'],true));
//     //Orders::FindOrderReady();
//     //echo json_encode ( Orders::FindOrderDishesStateForStaff());
//     $finalReport = array();
       
    
//     $Report;
//     $ReportArr = [];
//     $ReadyCount=0;

//    $numOfReady = OrdersInfo::FindOrderDishesStateForStaff($_POST['StaffID']);
//     //error_log( print_R($numOfReady,true) );
//    //error_log( print_R("indise OrderReady after",true) );


//     if (count($numOfReady ) > 0) {
      
//          //.(count($numOfReady) > 1 ? "items are marked as Ready or are being Prepared." : "item is marked as Ready or is being Prepared.");
//         foreach ($numOfReady as $value) {
//             //we may need to check the order type to personalize
//             //the message bases on the order type.
//              $orderDetails = Orders::find_by_id ($value['Orders_ID']);

           
            


//             $ReadyCount = $value['Qty'] +  $ReadyCount ;
           

//             // error_log( print_R($orderDetails,true) );
//             // error_log( print_R("VALUE order orderDetails",true) );

//            $PersonalizeStr='';

//             switch ($orderDetails->Type) {
//                 case 'TakeOut':
//                 $PersonalizeStr=" marked as TakeOut for ".$orderDetails->ClientName ;
//                     break;
//                 case 'Delivery':
//                 $PersonalizeStr=" marked as Delivery for ".$orderDetails->ClientName ;
//                     break;
//                 case 'DineIn':
//                 $PersonalizeStr=" marked as DineIn for ".$orderDetails->TableNum;
//                     break;
                
                
//                 default:
//                // $PersonalizeStr="";
//                     break;
//             }

            

//             if ($value['Dish_Status']=='DECLINED') {
//                 array_push($ReportArr,'⇒ ORDER #'.$value['Orders_ID'].$PersonalizeStr.', has '.$value['Qty'].($value['Qty'] > 1 ? ' items' : ' item'). ' marked as DECLINED.');

//             } else {
//                 array_push($ReportArr,'⇒ ORDER #'.$value['Orders_ID'].$PersonalizeStr.', has '.$value['Qty'].($value['Qty'] > 1 ? ' items' : ' item'). ' ready to be served.');

//             }

 
//             //$Report .='ORDER #'.$value['Orders_ID'].$PersonalizeStr.', has '.$value['Qty'].($value['Qty'] > 1 ? ' items' : ' item'). " ready to be served.".PHP_EOL;
// //            array_push($ReportArr,'⇒ ORDER #'.$value['Orders_ID'].$PersonalizeStr.', has '.$value['Qty'].($value['Qty'] > 1 ? ' items' : ' item'). ' ready to be served.');
//            // error_log( print_R(json_encode ($Report),true) );
//            // error_log( print_R("VALUE IN LOOP",true) );
 
//         }

//         //echo json_encode ($String );
//         $finalReport ['ReadyCount']=$ReadyCount ;
//        // $finalReport ['Report']=json_encode (addslashes($Report)) ;
//         $finalReport ['ReportArr']=$ReportArr ;
//         $finalReport ['PaidOrders']= Orders::ReportOrder($_POST['StaffID']) ;
//         $finalReport ['TotalOrders']= Orders::GetTotalUnpaidOrder() ;

//         $finalReport ['Menu']= RefreshMenuReturn(); ;

        
//     } else {
//        // echo json_encode ("This order was fully updated.");

//     }
 


//    // error_log( print_R($Report,true) );

//     echo json_encode ($finalReport);


//    // echo json_encode ( OrdersInfo::FindOrderDishesStateForStaff($_POST['StaffID']));

//     //MySQLDatabase::close_connection();
    
// }

// function GetMyStock () {
//     $myStock = Stock::find_all();
//     array_multisort( array_column($myStock, "Availability"), SORT_ASC, $myStock );
//     echo json_encode ( $myStock );
// }

// function SaveStock () {
//    $newStock = new Stock ("Blank");
//    //dynamically seeting the stock object


//    foreach($_POST as $attribute=>$value){
//     if(property_exists($newStock,$attribute)) {
//         $newStock->$attribute = $value;
//     }
//   }

// //we need to set the other attributes before saving object
// $newStock ->Stocked_Date  = date('Y-m-d H:i:s') ;
// $newStock ->Last_Consumed =  $newStock ->Stocked_Date; 
// //  $newStock ->Used_by       = '0.1';
// $newStock ->Availability  = "100";
// $newStock ->Available_Qt = $newStock ->Original_Qt;


// $result = $newStock->save();
// if ($result) {
//     echo json_encode (Stock::find_all());
// } else { echo json_encode (false);}

// }

// function Chef_OrderInteraction () {
//     $StatePassed = trim($_POST['StatePassed']);

//     if (!empty($_POST['MarkingOnlineDish']) && isset( $_POST['MarkingOnlineDish']) ) { 
//         $OnlineOrder = Orders::getOrder_by_ONLINE_ID(trim($_POST['Order_ONLINE_ID']));
//         echo json_encode (Orders::Chef_OrderInteraction($OnlineOrder->id,$StatePassed ) );

//   } else {
//     $OrderID = trim($_POST['OrderID']);
//     echo json_encode (Orders::Chef_OrderInteraction($OrderID,$StatePassed ) );
//   }


// }

// function DeleteConsumable () {
//    // error_log(print_r($_POST,true));
//     $newConsumable = new Consumables ("Blank");
//     $newConsumable ->id = trim($_POST['Consumable']);

//     $dishId = trim($_POST['Consumable']);
//     $dishtype= trim($_POST['Dish_type']);

//     $result = $newConsumable->delete();

//     if ( $result){
//         Stock::Decrease_Used_by( trim($_POST['Stock_id']));
//         $sql = "SELECT * FROM Consumables WHERE Dish_id='".$dishId."' AND Dish_Type ='".$dishtype."'";
        
//         echo json_encode (Consumables::find_by_sql($sql,""));
//     }else{ 
//         echo json_encode (false);
//     }
   
// }

// function  UserCancelOrder() {
//     $id = $_POST["orderID"];
//     $orderFound = Orders::find_by_id($id);
//     if ( $orderFound ->Chef_Interaction =="CLOSE" && OrdersInfo::FindOrderDishesStateUSER($id)==0) {
//         $orderFound->Chef_Interaction="DECLINED";
//         $orderFound->Status="DECLINED";  
//         if ( $orderFound->save() ) {
//             echo json_encode ( Orders::UserOders(  $orderFound->Customer_id) );
//         } else {
//             echo json_encode (false);
//         }
        
//     } else {
//         echo json_encode (false);
//     }
// }

// function MarkDecline() {
//     error_log(print_r($_POST,true));
//     // error_log(print_r("hooked",true));

//     if (!empty($_POST['MarkingOnlineDish']) && isset( $_POST['MarkingOnlineDish']) ) { 
//            $dishInfo = OrdersInfo::getDishInfo_ONLINE_ID(trim($_POST['DishInfo_ONLINE_ID']));
//            echo json_encode (  OrdersInfo::DeclineByChef( $dishInfo->OrderDishInfo_id ,$dishInfo->Orders_ID ) ) ; 
 
//      } else {
//         echo json_encode (  OrdersInfo::DeclineByChef($_POST['DishId'], trim($_POST['OrderIDPassed'] )) ) ; 
//     }


// }

// function MarkReady () {
//     error_log(print_r($_POST,true));
//     // error_log(print_r("hooked",true));

//     if (!empty($_POST['MarkingOnlineDish']) && isset( $_POST['MarkingOnlineDish']) ) {
//         //we find dish id based on OnlineId
 
//            $dishInfo = OrdersInfo::getDishInfo_ONLINE_ID(trim($_POST['DishInfo_ONLINE_ID']));
 
//            //$dishId = $dishInfo->OrderDishInfo_id;

//            echo json_encode (  OrdersInfo::MarkDishReady( $dishInfo->OrderDishInfo_id ,$dishInfo->Orders_ID ) ) ; 
 
 
//      } else {
//         echo json_encode (  OrdersInfo::MarkDishReady($_POST['DishId'], trim($_POST['OrderIDPassed'] )) ) ; 
//      }

   
   
// }

// function MarkPaid() {

//     if ($_POST['OnlinePayment']==true) {
//         $orderData = $_POST['order'];
//         $order = Orders::getOrder_by_ONLINE_ID($orderData['ONLINE_id']);
//         $order ->Payment_Method = $orderData["Payment_Method"];
//         $order ->Reference = $orderData["Reference"];
//         $order ->Cash = $orderData["Cash"];
//         $order ->Tip = $orderData["Tip"];

//         $order->save();
     
//         # code...
//     } else {
//          echo json_encode (Orders::MarkOderAsPaid ($_POST)); 
//     }
    
 
  
//     //echo json_encode (true);

//     //we may need to mark paid on server?????

// }

// function MarkPreparing() {

//     if (!empty($_POST['MarkingOnlineDish']) && isset( $_POST['MarkingOnlineDish']) ) {
//        //we find dish id based on OnlineId
//           $dishInfo = OrdersInfo::getDishInfo_ONLINE_ID(trim($_POST['DishInfo_ONLINE_ID']));
//           $dishId = $dishInfo->OrderDishInfo_id; 

//     } else {
//         $dishId = trim($_POST['DishId']);
//     }
    
    
 
//     echo json_encode (OrdersInfo::MarkPreparing($dishId));

// }

// function MarkDishServed() {

//     $dishId = trim($_POST['DishId']);
//     $Orders_ID = trim($_POST['Orders_ID']);

//     echo json_encode (OrdersInfo::MarkServed($dishId,$Orders_ID));

// }

// function GetMoreUnpaidOrder () {
//     $Table = trim($_POST['Table']);
//     $pageNum = trim($_POST['PageNumber']);

//     echo json_encode ( Orders::GetMoreUnpaidOrder($Table,$pageNum ));
// }

// function GetOrders() {
//   //error_log(print_r( Orders::FindUnpaidOrders() ));
//   // error_log( print_R("see oneee hWTFFFFFFFFF" ,true) );
 
//  echo json_encode ( Orders::FindUnpaidOrders());
 
// }

// function GetOderToView (){
//     $Order_ID = trim($_POST['Order_ID']);
//     echo json_encode ( Orders::FindOrderByID ($Order_ID));   
// }

// function GetOrdersChef () {
//     //error_log(print_r( "before entering"));
//     echo json_encode ( Orders:: FindOrders_Chef ());

    
// }

// function ConfirmDecline() {

//     echo json_encode ( Orders::ConfirmDecline ( trim($_POST['orderID'])));

// }

// function DeleteItem () {
//     $objToDelete;
//     error_log(print_r($_POST,true));
//     switch (trim($_POST['class'])) {
//         case "Stock":
//             $objToDelete = new Stock ("Blank");
//             $objToDelete ->id = trim($_POST['Stock_id']);
//             $result = $objToDelete->delete();

//             if ( $result){
//                 echo json_encode (Stock::find_all());
//             }else{ 
//                 echo json_encode (false);
//             }
            
//             break;
//         case "SideDish":
//             $objToDelete = new SideDishes ("Blank");
//             $objToDelete ->id = trim($_POST['Stock_id']);
//             $result = $objToDelete->delete();

//             //will need to decrease stock

//             if ( $result){
//                 echo json_encode (SideDishes::find_all_Admin("SideDishes"));
//             }else{ 
//                 echo json_encode (false);
//             }
            
//             break;
//         case "MenuDishes":
//             $objToDelete = new MenuDishes ("Blank");
//             $objToDelete ->id = trim($_POST['MenuDish_id']);
//             $result = $objToDelete->delete();

//             if ( $result){
//             $sql = "SELECT * FROM `DishCustomization` WHERE `MenuDishes_id`='".$objToDelete ->id."' AND (`CustomType`='DishChoice' OR `CustomType`='ExtraIngredient')";
//             $DishCustomization = DishCustomization::find_by_sql($sql,"");
//             foreach($DishCustomization as $key => $value) {
//             //error_log(print_r($value->id,true));
//             SideDishes::Decrease_Used_by($value->SideDish_id);
//             //wee need to delete since it will not be use
//             //any more because menudisih no esze
//             $DishCustomizationToDelete = new DishCustomization ("Blank");
//             $DishCustomizationToDelete->id =$value->id;
//             $DishCustomizationToDelete->delete();
            
//             }
           
//            //we find all MenuDiches 
//                 //we need to delete all menudish entry in
//                 //the consumable database and decrease fron 
//                 //the sidedishes if needed
//                 MenuDishes::DeleteFromConsumable($objToDelete ->id, "MenuDish");
//                 SideDishes::Decrease_Used_by ($objToDelete ->id);
//                 //will need to send updated version of full array
//                 echo json_encode (MenuDishes::find_all_Admin("MenuDishes"));
//             }else{ 
//                 echo json_encode (false);
//             }
            
            
//             break;
//         default:
            
//     }
   

//     //error_log(print_r($result,true));
//     //error_log( print_R("22222 TRYINGGGGG!!! DeleteFromConsumable",true) );
    
//         // if ( $result){
//         //     if ( trim($_POST['class']) =="SideDish"){
//         //         echo json_encode (SideDishes::find_all("SideDishes"));
//         //     }else{
//         //         echo json_encode ($objToDelete::find_all());
//         //     }
           
//         // }else{ 
//         //     echo json_encode (false);
//         // }

   

  
// }

// function SaveExpense (){
//     error_log(print_r($_POST,true));
//     $newExpense = new Expenses ("Blank");

//     foreach($_POST as $attribute=>$value){
//         if(property_exists($newExpense,$attribute)) {
//             $newExpense->$attribute = $value;
//         }
//       }

//       $newExpense ->Date_created  = date('Y-m-d H:i:s') ;

//       $result =  $newExpense->save();

//       if ($result){
//         echo json_encode ( Expenses::find_all());

//       }else{
//         echo json_encode (false);
//       }
// }


// function DeleteDishCustomization () {
//     error_log(print_r($_POST,true));

//     //first get the the sidedish id
//     $sql = "SELECT * FROM `DishCustomization` WHERE `id`='".trim($_POST['DishCustomizationId'])."' AND `CustomType`='".trim($_POST['CustomizationType'])."'";
//     $DishCustomization = DishCustomization::find_by_sql($sql,"");

//     $DishCustomizationToDelete = new DishCustomization ("Blank");
//     $DishCustomizationToDelete->id =trim($_POST['DishCustomizationId']);
//     $result = $DishCustomizationToDelete->delete();

//     if ( $result) {
        
//         foreach($DishCustomization as $key => $value) {
//         SideDishes::Decrease_Used_by($value->SideDish_id);
//         }

//         echo json_encode (true);

//     }else{echo json_encode (false);}

// }

// function saveStaff () {
//     global $database;
//     $StaffData = new Staff ("Blank");

//     foreach($_POST as $attribute=>$value){
//         if(property_exists($StaffData,$attribute)) {
//             $StaffData->$attribute = $value;
//         }
//       }

//     //encrypting passpoerd

//     if (!$StaffData->Password) {
//         // unset($StaffData->Password );
//           unset($StaffData->Password );
//        // unset($StaffData['Password'] );
//           } else {
//             $StaffData ->Password=SHA1($database->escape_value($StaffData->Password));

//           }


//     //ensuring the Admin 1 could not  be changed.
//     if (  $StaffData ->id == 1){
//         $StaffData ->Privilege = "Admin";
//     }

 
 

//     $result =  $StaffData->save();
    
//    if ( $result) {
//        //we get all staff and uppdate client list
//        echo json_encode ( Staff::find_all("Staff") );
//    } else {
//         echo json_encode ( false );
//    }
   
  

// }

// function SaveMenuDishes (){
//     $newMenuDishes = new MenuDishes ("Blank");
//     //dynamically seeting the stock object

//     error_log(print_r($_POST,true));
//    // error_log(print_R( json_decode($_POST["Consumable"]) ,TRUE));

//     foreach($_POST as $attribute=>$value){
//         if(property_exists($newMenuDishes,$attribute)) {
//             $newMenuDishes->$attribute = $value;
//         }
//       }

//     $newMenuDishes ->CreatedDate  = date('Y-m-d H:i:s') ;

//     $result =  $newMenuDishes->save();
//     if ($result){
//         Consumables::SaveConsumables (json_decode($_POST["Consumable"]),"MenuDish", $newMenuDishes->id  );
//         DishCustomization::SaveDishCustomization (json_decode($_POST["ExtraIngredients"]),$newMenuDishes->id );
//         DishCustomization::SaveDishCustomization (json_decode($_POST["DishChoices"]),$newMenuDishes->id,"DishChoices" );
        
//         $Data = array(
//             "SideDishes"=>SideDishes::find_all_Admin("SideDishes"),
//             "StoredStock"=>Stock::find_all(),
//             "MenuDishes"=>MenuDishes::find_all_Admin("MenuDishes")
//                             );
//         echo json_encode ( $Data );
//     }else { echo json_encode (false);}
//     //echo json_encode (MenuDishes::find_all("MenuDishes"));
// }


// function SaveSideDishes () {
//     $newSideDishes = new SideDishes ("Blank");
//     //dynamically seeting the stock object

//     error_log(print_r($_POST,true));
//     error_log(print_R( json_decode($_POST["Consumable"]) ,TRUE));
//     //var_dump( $_POST["Consumable"] ); 
 
 
//     foreach($_POST as $attribute=>$value){
//      if(property_exists($newSideDishes,$attribute)) {
//          $newSideDishes->$attribute = $value;
//      }
//    }

//    $newSideDishes ->CreatedDate  = date('Y-m-d H:i:s') ;

//    //error_log(print_r($_POST,true));
 
//  //we need to set the other attributes before saving object
// //  $newSideDishes ->Stocked_Date  = date('Y-m-d H:i:s') ;
// //  $newSideDishes ->Last_Consumed =  $newStock ->Stocked_Date; 
// //  $newSideDishes ->Used_by       = '0';
// //  $newSideDishes ->Availability  = "100";
// //  $newSideDishes ->Available_Qt = $newStock ->Original_Qt;


 
//  $result =  $newSideDishes->save();
//  if ($result) {
//      //this should be done if the dish is saved
// //$Consumable =json_decode($_POST["Consumable"]) ;
// Consumables::SaveConsumables (json_decode($_POST["Consumable"]),"SideDish",$newSideDishes->id  );
// $Data = array(
//     "SideDishes"=>SideDishes::find_all_Admin("SideDishes"),
//     "StoredStock"=>Stock::find_all(),
//     "MenuDishes"=>MenuDishes::find_all_Admin("MenuDishes")
//                     );
// echo json_encode ( $Data );
//  } else { echo json_encode (false);}
  
 
//  }

// function ShowOnMenu () {
//     error_log(print_r($_POST,true));

   

//     switch (trim($_POST['class'])) {
//         case "SideDishes":
//             $objVisual = new SideDishes ("Blank");
//             foreach($_POST as $attribute=>$value){
//                 if(property_exists($objVisual,$attribute)) {
//                     $objVisual->$attribute = $value;
//                 }
//               }
//             break;
//         case "MenuDishes":
//         $objVisual = new MenuDishes ("Blank");
//         foreach($_POST as $attribute=>$value){
//             if(property_exists($objVisual,$attribute)) {
//                 $objVisual->$attribute = $value;
//             }
//           }
             
//             break;
//         case "green":
            
//             break;
//         default:
            
//     }
    
//     $result = $objVisual ->save();

//     if ($result){
//         echo json_encode (true);
//     }else{
//         echo json_encode (false);
//     }

    
   
// }

// function Refund () {
//     $staffId =$_POST ['StaffID'];
//     //we need to to Authenticate
//     if (Staff::authenticateStaff (trim( $_POST ['password']), $staffId, "Refund" )) {
//         echo json_encode (Orders::handleRefund(trim( $_POST ['orderId']), trim( $_POST ['Amount']) ) );
//     } else {
//         echo json_encode (false);
//     }
    
// }

// function ConfirmAdmin (){
//      echo json_encode (Staff::authenticateStaff (trim( $_POST ['password']),$_POST ['StaffID'], "Discount"  ) );
    
// }

// function FindCustomerInOrder (){
//     $order = trim( $_POST ['Order_ID']);
//     echo json_encode (Orders::FindYour_Customer ($order) );

// }
    
// function GetCustomer () {
//     error_log(print_r( $_POST,true));
//     $customerID = trim( $_POST ['customerID']);

//     echo json_encode (Customer::find_by_id($customerID));

// }

// function findOrder () {
//   error_log(print_r( $_POST,true));
//   $orderID = trim( $_POST ['orderID']);
  
//  // $orderFound = Orders::findOrderClass ($orderID ) ;
//   //Orders::findOrderClass (trim($_POST["orderID"]) ) ;

//     echo json_encode (Orders::findOrderClass ($orderID ));
// }


// function  EditOrder() {
//     error_log(print_r( $_POST,true));
//     global $DISHES_SERVED;
//     global $EDIT_ORDER_TOTAL;

//     $UneditableDish=0;
  
 
//     $newData = json_decode($_POST['OrderInfo']) ;

//     //UpdateOrderTotal ($Orders_ID="", $newTotal="","REDUCE")

//     $OrderToEdit = new Orders ();
//     if ($newData->Discount == 0 || $newData->Discount == 0.00 ) {
//         $OrderToEdit ->Discount = '0.00' ;
//     } else {
//         $OrderToEdit ->Discount = $newData->Discount ;

//        // Orders::UpdateOrderTotal ($newData->id , $newData->Discount,"REDUCE");
//     }
    
  

//     $OrderToEdit->id = $newData->id ;
//     $OrderToEdit->Total = $newData->Total;

//     //we need to save the new total and discount of the order
//     $OrderToEdit->save();

//     //we check if the order is open
//     //CHECK_Chef_OrderInteraction ($newData->id );
//     //error_log(print_r('GETTING VALUE OF CHECK_Chef_OrderInteraction ',true));
//     //error_log(print_r(Orders::CHECK_Chef_OrderInteraction ($newData->id ),true));

//     if (Orders::CHECK_Chef_OrderInteraction ($newData->id ) == "CLOSE") {

//         error_log(print_r(  "WE PASSED CHECK_Chef_OrderInteraction",true));
    
//     //WE WILL HAVE TO DELETE ALL INFO RELATED TO THIS ORDER
//     //TO MAKE IT EASIER WE WILL NEED TO CREATE A DELETE CASCADE IN MYSQL DATABASE
//      OrdersInfo::DeleteDishInfo ($newData->id);

//      //TO GET THE NUMBER OF UNEDITABLE ORDER WE ASK OUR 
//      //DATABASE FOR THE NUMBER OF ORDER MARKED AS PREPARING OR SERVED
 
 
//      $DISHES_SERVED=OrdersInfo::FindUneditableDishes($newData->id);
//      SaveOrderDetails (json_decode($_POST['details']) ,  $newData->id);
 
//      $TotalExtra = OrdersExtra::TotalExtrasPrice($newData->id);
//      $TotalChoices = OrdersItemChoice::TotalChoicesPrice($newData->id);
 
 
//      // error_log(print_r('TotalExtra',true));
//      // error_log(print_r($TotalExtra,true));
 
//      // error_log(print_r('TotalChoices',true));
 
//      // error_log(print_r($TotalChoices,true));
 
//      $NewTotal = OrdersInfo::TotalDishPrice($newData->id,$TotalExtra,$TotalChoices );
//      //OrdersExtra::TotalExtrasPrice($newData->id) + OrdersItemChoice::TotalChoicesPrice($newData->id);
//      //OrdersExtra::TotalExtrasPrice($newData->id);
 
//      //we  save the new New Total 
     
//      if ( Orders::UpdateOrderTotal($newData->id, $NewTotal-$newData->Discount, "EDITING")) {
//          error_log(print_r(  "order updated yyy",true));
//          error_log(print_r( $newData->id,true));
 
//          //confirm to user how the update was done
//          if (count($DISHES_SERVED) > 0) {
//              $String = "Order was updated but ".(count($DISHES_SERVED) > 1 ? "there are " : "there is ").count($DISHES_SERVED). (count($DISHES_SERVED) > 1 ? " items " : " item");
//              $String .="that could not be updated because the ".(count($DISHES_SERVED) > 1 ? "items are marked as Ready or are being Prepared." : "item is marked as Ready or is being Prepared.");
 
//              //here we check if the ORDER was served.
//              //We will need to mark the order In queue and update
//              //the time. This will change the order in the queue
//              if (Orders::CHECK_If_SERVED ($newData->id ) == "SERVED") {
//                 error_log(print_r("MAKER SERVED READY TO ACT",true));
//                 Orders::UPDATE_ORDER_STATE ($newData->id);

//              }
//              echo json_encode ($String );
//          } else {
//              echo json_encode ("This order was fully updated.");
     
//          }
 
         
//      } else {
//          //error_log(print_r(  "Order Total Could not be updated",true));
//          echo json_encode ("The order could not be updated.");
//      }
 
     
//     //since chef has the oder open we cant update
//     //and let user know 
//     } else {
//         echo json_encode ("The Order could not be updated. The Chef is currently working this order.");
//     }
    
   
   
// }

// function CancelReservation () {
//     error_log(print_r($_POST,true));

//    // Reservation::find_by_id( trim($_POST["Reservation"]));
//   $reservationToEdit =  Reservation::find_by_id( trim($_POST["Reservation"]));
//   $reservationToEdit->CancelBy_id = trim($_POST["UserID"]);
//   $reservationToEdit->CancelBy_Name =Customer::GetCustomerName(trim($_POST["UserID"]));
//   $reservationToEdit->Status ="CANCELLED";
//   $reservationToEdit->Sent_to_POS ="No";


//   if ($reservationToEdit->save()) {
//     echo json_encode (Reservation::getUserReservation (  $_POST["UserID"]));
    
//     }else{
//         echo json_encode ( false);
//     }



//     //error_log(print_r( Reservation::find_by_id( trim($_POST["Reservation"])),true));

//    // echo json_encode (false);


// }

// function getReservation() {

//     echo json_encode (Reservation::getUserReservation (  $_POST["UserID"]));

// }

// function getReservationStaff() {

//     echo json_encode (Reservation::GetReservations ());

// }


// function MakeRervation () {

//     //error_log(print_r( $_POST,true));

//     if ($_POST["UdatingReservation"] ==true && SERVER_MODE=="ONLINE") {
//         Reservation::Mark_Sent_To_POS( $_POST["ONLINE_id"] );
//     }else {
//         $Details = $_POST;

//     $reserve = new Reservation ("Blank");
//     foreach($Details as $attribute=>$value){
//         if(property_exists($reserve,$attribute)) {
//             $reserve->$attribute = trim($value);
//         }
//       }

     

//    // $reserve->Time= formatDateMysql ( $reserve->Time);

//     $reserve->Status="PENDING";


//     if(SERVER_MODE=="ONLINE"){
//          $reserve->ONLINE_id = getUniqueId() ;
//       }

//   //  error_log(print_r("MakeRervation",true));

// //   $date = new DateTime();
// //   $date->format('U = Y-m-d H:i:s') ;

// //   $date->setTimestamp(  substr($reserve->Time, 0, -3));

// //   error_log(print_r( "time passed",true) );
// //   error_log(print_r( $reserve->Time,true) );
// //   error_log(print_r( $reserve->Date,true) );

//   $HrMin = explode(":",$reserve->Time);
//  // error_log(print_r($HrMin,true) );
  
//   $MydateTime = new DateTime ( $reserve->Date);
//   $MydateTime ->setTime($HrMin [0], $HrMin [1]);
//   $MydateTime ->format('YYYY-MM-DD HH:MM:SS');

//  // error_log(print_r($MydateTime,true) );
//  error_log(print_r("check vals",true) );

//  $reserve->Time=  $MydateTime ->format('Y-m-d H:i:s');

//   error_log(print_r($MydateTime ->format('Y-m-d H:i:s'),true) );

//      error_log(print_r( $reserve,true) );
//     // error_log(print_r( Date("Y-m-d H:i:s",$reserve->Time),true) );
//    // echo json_encode ( false);
// //report
// $reportDetails=array();

// //confirming that user dont have previous reservations
// $reservation = Reservation::checkUserReservation($reserve->Customer_id, $reserve->Date);
//     if ( $reservation == false) {
//         $reserve -> save();
//         $reportDetails["status"]=$reservation ;
//         $reportDetails["stored"]=true ;
//         $reportDetails["reservations"] = Reservation::getUserReservation ($reserve->Customer_id);
//         echo json_encode ( $reportDetails);
//       } else {

//         $reportDetails["status"]=$reservation ;
//         $reportDetails["stored"]=false ;
//         $reportDetails["reservations"] = Reservation::getUserReservation ($reserve->Customer_id);
//         echo json_encode ( $reportDetails);
    
//       }
      



        
//     }

//     }

//  function  MarkOrderSent_To_POS() {
//     Orders::Mark_Sent_To_POS( trim($_POST['ONLINE_Order']));
//     echo json_encode ( $ONLINE_id);
// }

// function HandleReservation ($Reservation=""){
//     global $database;

   

//     if (  Reservation::getReservation_by_ONLINE_ID($Reservation->ONLINE_id) ) {
//         $sql = "UPDATE `Reservation` SET  `Status`='{$Reservation->Status}',`Sent_to_POS`='YES'  WHERE `ONLINE_id`='{$Reservation->ONLINE_id}' ";

//         $database->query($sql)  ;

//         $post = [
//             'action' => 'MakeRervation',
//             'UdatingReservation'=>true,
//             'ONLINE_id'=>  $Reservation->ONLINE_id
//            ];

//         ONLINE_SERVER_MARKER ($post);

//     }else{

//     }

// }



// function  RegisterSale() {
//     $dataPassed =json_decode ($_POST['OrderInfo']);
//     $orderType = $dataPassed->Type;
//     $TableNum = $dataPassed->TableNum;
//     $Total = $dataPassed->Total;
//     error_log(print_r( $dataPassed,true));
//     error_log(print_r( "checking post",true));
//     $OrderID =  Orders::FindOrderID($TableNum);
//     error_log(print_r( "inside RegisterSale",true));

//    // error_log(print_r($OrderID,true));
//    // error_log(print_r( json_decode ($_POST['OrderNote']),true));

//    //we need to check the type of order to handle and if unpaid, we merge it dishes.
//    //this will avoid inserting anoteher order if we are placing order for the same table
//     if ( $orderType =="DineIn" && !empty($OrderID)) {
//         $Total = $dataPassed->Total;

//         error_log(print_r("ready to merge order",true));
//         error_log(print_r($Total,true));
//         Orders::AddToTotal ($OrderID,$Total );
//         SaveOrderDetails (json_decode ($_POST['details']),$OrderID );


//          echo json_encode ( true);

//     } else{


//      //   error_log(print_r( "checking elseeeeeee",true));

   
//     // error_log(print_r(  $details,true));
//     $orderDetails =  json_decode ($_POST['OrderInfo']);

//     $orderInfo = new Orders ("Blank");
//     foreach($orderDetails as $attribute=>$value){
//         if(property_exists($orderInfo,$attribute)) {
//             $orderInfo->$attribute = $value;
//         }
//       }

//       error_log(print_r(  $orderInfo,true));
//       $orderInfo->Status="In Queue";
//       $orderInfo->Chef_Interaction="CLOSE";

//       $Origin = trim($_POST['Origin']);
      
//       if ( !empty($Origin) && isset($Origin) ) {

//          if(SERVER_MODE=="ONLINE"){
//              $orderInfo->Order_Origin=$Origin;
//              $orderInfo->ONLINE_id = getUniqueId() ;
//            }
//         ///****************************/////
//        // $orderInfo->Order_Origin	=$Origin;
//        // $orderInfo->ONLINE_id = getUniqueId() ;
//       ///*********ONLY SERVER ONLY****** */
//       } else {
//         $orderInfo->Order_Origin	="Local_POS";
//       }
      

     
//     //   $orderInfo->ONLINE_id	='NULL';
//       $orderInfo->Sent_to_POS='NO';
//       //we will check if are set

      
//       if($orderInfo->Payment_Method!="N/A"){
//         $orderInfo->Cash="PAID";
        
//       }else{
//         $orderInfo->Cash="UNPAID";
//       }
//     //   $orderInfo->Payment_Method="N/A";
//       $orderInfo->APEX_Staff_ID=$orderDetails->APEX_Staff_ID;

//      //unset( $orderInfo->id);

//     //unset( $orderInfo->ONLINE_id);


//       $orderInfo -> save();

//        //if the order was marked PAID and 
//       //sussesfutlly saves, now we check if 
//       //it was paid with Credit and then carge the customer
//       //by adding value in the DB 
//       if ($orderInfo->Customer_id !=0 && $orderInfo->Payment_Method=="Credit") {
//          Customer::AddCredit($orderInfo->Customer_id,$orderInfo->Total );
//       }

 

//        //error_log(print_r( json_decode ($_POST['ItemChoices']),true));
//    // $details = json_decode ($_POST['details']);
//     //error_log(print_r(  $details[0]['DishInfo'],true));
   

//     SaveOrderDetails (json_decode ($_POST['details']),$orderInfo  ->id  );

//     // foreach ($details as  $valueinfo->ItemChoices) {
//     //    OrdersItemChoice::saveOrderItemChoices($orderInfo->id,$valueinfo->ItemChoices );
//     // }


//     if ($orderInfo) {
//         if ($orderInfo->Cash=="PAID" ) {
//              PrintReceipt ($orderInfo);
//         }
//         echo json_encode ( true);

       
//     }else{
//         echo json_encode ( false);
//     }


//     }

   

// }

// function reprintreceipt () {
 
//    // Re_PrintReceipt (trim($_POST['orderID']));
//    //find order
//    //getting order
//    $order = Orders::FindOrderToPrint($_POST['orderID'],$_POST['type'] );
//     echo json_encode (  Re_PrintReceipt ( $order[0] ) );

// }

// function RefreshMenu () {

//     $serverData = array(
//         "SideDishes"=>SideDishes::find_all("SideDishes"),
//          "MenuDishes"=>MenuDishes::find_all("MenuDishes"),
//          "Reservations"=> Reservation::GetReservations ()
//                          );

//      echo json_encode ( $serverData);

// }

// function RefreshMenuReturn () {

//     $serverData = array(
//         "SideDishes"=>SideDishes::find_all("SideDishes"),
//          "MenuDishes"=>MenuDishes::find_all("MenuDishes"),
//          "Reservations"=> Reservation::GetReservations ()
//                          );

//       return $serverData;

// }


// function authenticate () {
//     //$auth_user = new Staff ("Blank");
 

//     //error_log(print_r($_POST,true));
//     $auth_user = Staff::authenticate ( trim($_POST['Username']), trim($_POST['Password']));
//     //error_log(print_r("see auth_user",true));
//     error_log(print_r("entering auth auth_user ",true));
//    // error_log(print_r($auth_user,true));
//     if ( $auth_user ) {
//         //since usher passed uath, we get all the data 
//         //neede for the entire application bases on user privilage
//     //Staff Privilege
//    // error_log(print_r( $auth_user->Privilege ,true));
     
//         // $serverData = array(
//         //     "authenticated_user"=>  $auth_user,
//         //     "Staff"=>Staff::find_all(),
//         //     "SideDishes"=>SideDishes::find_all("SideDishes"),
//         //     "StoredStock"=>Stock::find_all(),
//         //     "MenuDishes"=>MenuDishes::find_all("MenuDishes")
            
            
//         //                     );

//         switch($auth_user->Privilege ) {
//             case 'Staff' :
//             error_log(print_r($auth_user->Privilege ,true));
//             $serverData = array(
//                 "SideDishes"=>SideDishes::find_all("SideDishes"),
//                 "StoredStock"=>Stock::find_all(),
//                 "MenuDishes"=>MenuDishes::find_all("MenuDishes"),
//                 "authenticated_user"=>$auth_user,
//                 "Reservations"=> Reservation::GetReservations (),
//                 "SERVICE_CHARGE"=> SERVICE_CHARGE
//                                 );

//              echo json_encode ( $serverData);
            
//             break;

//             case 'Admin' :
//             $serverData = full_update_admin ();
//             //passing user since the function does not return it
//             $serverData["authenticated_user"] =$auth_user;
           
//             echo json_encode ( $serverData);
//             break;

//             case 'Chef' :
//             $serverData = full_update ();
//             //passing user since the function does not return it
//             $serverData["authenticated_user"] =$auth_user;
           
//             echo json_encode ( $serverData);
//             break;
        
        
//         }
        
      
//        // echo json_encode ( $serverData);
      
        
//     } else {
//         //we send false to client since the user could not be authenticate.
//         //client will handle once recieve false
//         echo json_encode(false);
//     }

//     // foreach($_POST as $attribute=>$value){
//     //     if(property_exists($newStock,$attribute)) {
//     //         $auth_user->$attribute = $value;
//     //     }
//     //   } 

   
// }


// // $newStock->Name         =  $_POST["Name"];
// // $newStock->Supplier     =  $_POST["Supplier"];
// // $newStock->Price        =  $_POST["Price"];
// // $newStock->Original_Qt  =  $_POST["Original_Qt"];
// // $newStock->Measurement  =  $_POST["Measurement"];
// // $newStock->Image        =  $_POST["Image"];
// // $newStock->Availability =  "100";
// // $_POST["Name"] = "NAme";
// // $_POST["Supplier"]="NAme";
// // $_POST["Price"]="NAme";
// // $_POST["Original_Qt"]="NAme";
// // $_POST["Measurement"]="NAme";
// // $_POST["Image"]="NAme";
// //$otherSotck = DatabaseObject::instantiate($_POST);




//  // echo json_encode ($newStock);



// // [Name] => rew
// // [Supplier] => ewr
// // [Price] => 3214
// // [Original_Qt] => 1234
// // [Measurement] => kilogram
// // [Image] => this.name




// //$createStaff ->okte="This is oke";

// //echo $createStaff ->okte;

// //print_R(get_object_vars ($createStaff));
// //var_dump(get_object_vars($createStaff));
// //echo $createStaff ->$createStaff ->$okte;
// //$firStaff = Staff::Get_Object_Fields();


// //$jhon ->First_Name = "Julio";
// //echo $jhon ->Privilege = "son";;
// //$jhon ->save();
// //error_log( print_R($jhon,FALSE) );
// //echo $jhon->First_Name;

// // foreach(get_object_vars($createStaff) as $field=>$val ) {
// //     echo $field . " = ".$val."<br/>";
// // }  


// //$createStaff ->save();
// // $jhon = Staff::find_all();
// // echo "<pre>";
// // error_log( print_R($jhon ,FALSE) );
// // error_log(get_object_vars($createStaff));
// // //echo $jhon ;
// // error_log( print_R($createStaff,FALSE) );
// // error_log( print_R(Staff::testGetField (),FALSE) );
// // //$jhon = Staff::find_by_id(1);
// // echo "</pre>"

// //error_log( print_R(get_object_vars ($createStaff),FALSE) );

// // Staff::$setGetField("jojojo");
// // error_log( print_R(Staff::Get_Object_Fields(),FALSE) );
// //echo $firStaff->full_name();

// function Accredit () {
//     echo json_encode ( Customer::Accredit(trim( $_POST['id']), trim( $_POST['State'])));

// }

// function SetCredits () {}

// function RegisterPayment () {
//     echo json_encode ( Customer::RegisterPayment(trim( $_POST['CustomerID']), trim( $_POST['Amount'])));

// }

// function setCustomerBlock () {
//   //  error_log(print_r($_POST,true));
//     echo json_encode ( Customer::SetBlock(trim( $_POST['id']), trim( $_POST['State'])));
// }

// function blockStaff () {
//     echo json_encode ( Staff::block_Staff(trim( $_POST ['Uid'])) );

// }

// function full_update () {
//     $serverData = array(
//         "Staff"=>Staff::find_all(),
//         "SideDishes"=>SideDishes::find_all_Admin("SideDishes"),
//         "StoredStock"=>Stock::find_all_Admin(),
//         "Expenses"=>Expenses::find_all(),
//         "MenuDishes"=>MenuDishes::find_all_Admin("MenuDishes"));

//   return $serverData;

// }

// function full_update_admin () {
//     $serverData = array(
//         "Staff"=>Staff::find_all("Staff"),
//         "SideDishes"=>SideDishes::find_all_Admin("SideDishes"),
//         "StoredStock"=>Stock::find_all_Admin(),
//         "Expenses"=>Expenses::find_all(),
//         "MenuDishes"=>MenuDishes::find_all_Admin("MenuDishes"),
//         "Customers"=> Customer::find_all_Admin("Customer"));

//   return $serverData;

// }






// function testWhy () {

//     $i=0;
//     while ($i<=2) {
    
//        // echo ("sleeping");
    
//        // sleep(15);
    
    
//     $post = [
//        'action' => 'TEST_cURL'
//     ];
    
    
//     $ch = curl_init();
//     curl_setopt($ch, CURLOPT_URL, ONLINE_ORDER_CURL);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000);
//     curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

//     $response = json_decode (curl_exec($ch));
//     // echo ("after executing curl");
//     // close the connection, release resources used
//     // echo curl_error($ch);
//     //echo curl_error($ch);
//     curl_close($ch);
    
//     //var_export($response);
//     //in here we handle the response  and we shoul store it in our local server
    
//     //$resutl = $response;
     
     
    
    
//     //storing new customers
//     $customerOnServer = $response->Customers ;
    
//     foreach( $customerOnServer as $key=>$value) {
//        $Customer = new Customer ("Blank");
    
//        foreach( $customerOnServer[$key] as $attribute=>$value){ 
//             if(property_exists($Customer,$attribute)) {
//                 $Customer->$attribute =trim($value) ;
//             }
//           }
    
//           //we need to set the other attributes before saving object
//          $Customer->Sent_to_POS  = "YES";
//         // $Customer->Interactive_date  =  date('Y-m-d');

//       ////*******LOCAL SERVER ONLY **********//////

//       if (SERVER_MODE=="LOCAL") {
//          //error_log( print_R("before saving ",true) );
//          //error_log( print_R($Customer,true) );
//          //we should not trust this since it coming from extanl source
//          unset($Customer->Interactive_date);
//          unset($Customer->Points);
//          unset($Customer->Blocked);
//          unset($Customer->Accredited);
//          unset($Customer->Credits);

//         // error_log( print_R($Customer,true) );
//       }
     
    
         
       
//           //we need to sent the updated customer to the server
//          if ($Customer->verifyCustomer()) {
//             $updatedCustomer = Customer::find_by_id($Customer->id);

//             $post = [
//                 'action' => 'updateCustomer_Credit',
//                 'CustomerUdating'=>true,
//                 'updatedCustomer'=>  $updatedCustomer
//                ];

//             ONLINE_SERVER_MARKER ($post);
          
            
//          }
//         //////*************************///////////
        
    
       
//     }
    
    
//     foreach( $response->Orders as $index=>$value) {
//         RegisterONLINE_Sales($value);
       
//     }
    
    
    
//     //Tell server to Mark Users//dont waste resourse
//    // Ask_ONLINE_To_Mark_Customer ( $customerOnServer);

//    //*** Storing Reservation ***//
//    $ONLINE_Reservation= $response->Reservation ;

//    foreach( $ONLINE_Reservation as $key=>$value) {
//     $Reserve = new Reservation ("Blank");

//         foreach( $ONLINE_Reservation[$key] as $attribute=>$value){ 
//             if(property_exists($Reserve,$attribute)) {
//                 $Reserve->$attribute =trim($value) ;
//             }
//         }

//         $Reserve->Sent_to_POS ="Yes";
//         if (SERVER_MODE=="LOCAL") {
//             unset($Reserve->id);
//           }
        
//     //before saving we need to make sure that is not store locally
//    // $found = Reservation::getReservation_by_ONLINE_ID($Reserve->ONLINE_id);


//     if (  Reservation::getReservation_by_ONLINE_ID($Reserve->ONLINE_id) ) {
//         global $database;
//         $sql = "UPDATE `Reservation` SET  `Status`='{$Reserve->Status}',`Sent_to_POS`='YES'  WHERE `ONLINE_id`='{$Reserve->ONLINE_id}' ";
//         $database->query($sql)  ;
//         $post = [
//             'action' => 'MakeRervation',
//             'UdatingReservation'=>true,
//             'ONLINE_id'=>  $Reserve->ONLINE_id
//            ];

//         ONLINE_SERVER_MARKER ($post);

//     }else{


//         if ( $Reserve ->save()) {
//             $post = [
//                 'action' => 'MakeRervation',
//                 'UdatingReservation'=>true,
//                 'ONLINE_id'=>  $Reserve->ONLINE_id
//                ];

//             ONLINE_SERVER_MARKER ($post);
//         }
  
        

//     }
    

// }
//      //*** END Storing Reservation ***//
    
    
//     $i++;
//     }
    
//     echo json_encode ( $response);
    
    
//     }
      
// /* A wrapper to do organise item names & prices into columns */
// class itemLeft 
// {
//     private $name;
//     private $price;
//     private $dollarSign;

//     public function __construct($name = '', $price = '', $dollarSign = true)
//     {
//         $this -> name = $name;
//         $this -> price = $price;
//         $this -> dollarSign = $dollarSign;
//     }
    
//     public function __toString()
//     {
//         $rightCols = 25;
//         $leftCols = 7;
//         if ($this -> dollarSign) {
//             $leftCols = $leftCols / 2 - $rightCols / 2;
//         }
//         $left = str_pad($this -> name, $leftCols) ;
        
//         $sign = ($this -> dollarSign ? '$ ' : '');
//         $right = str_pad($sign . $this -> price, $rightCols, ' ', STR_PAD_LEFT);
//         return "$left$right\n";
//     }
// }

// /* A wrapper to do organise item names & prices into columns */
// class item
// {
//     private $name;
//     private $price;
//     private $dollarSign;

//     public function __construct($name = '', $price = '', $dollarSign = true)
//     {
//         $this -> name = $name;
//         $this -> price = $price;
//         $this -> dollarSign = $dollarSign;
//     }
    
//     public function __toString()
//     {
//         $rightCols = 7;
//         $leftCols = 25;
//         if ($this -> dollarSign) {
//             $leftCols = $leftCols / 2 - $rightCols / 2;
//         }
//         $left = str_pad($this -> name, $leftCols) ;
        
//         $sign = ($this -> dollarSign ? '$ ' : '');
//         $right = str_pad($sign . $this -> price, $rightCols, ' ', STR_PAD_LEFT);
//         return "$left$right\n";
//     }
// }







?>