<?php 
// require_once("config.php");
// require_once('database.php');
// require_once('database_object.php');

// //DB classes
// require_once('Classes/staff.php');
// require_once('Classes/orders.php');
// require_once('Classes/orders_info.php');
// require_once('Classes/OrderDishNotes.php');
// require_once('Classes/orders_Extra.php');
// require_once('Classes/orders_ ItemChoices.php');
// require_once('Classes/stock.php');
// require_once('Classes/Consumables.php');
// require_once('Classes/SideDishes.php');
// require_once('Classes/DishCustomization.php');
// require_once('Classes/MenuDishes.php');
// require_once('Classes/Expenses.php');
// require_once('Classes/customers.php');
// require_once('Classes/reservations.php');

require_once("config.php");
require_once('database.php');
require_once('database_object.php');

//DB classes
require_once('Business.php');
require_once('packages.php');
require_once('packagesIMG.php');
require_once('customers.php');
require_once('categories.php');
require_once('myItinerary.php');
require_once('reviews.php');
require_once('Messages.php');
require_once('secureReply.php');
require_once('suggestion.php');
require_once('highlights.php');











///////////////////
// require_once('orders.php');
// require_once('orders_info.php');
// require_once('OrderDishNotes.php');
// require_once('orders_Extra.php');
// require_once('orders_ ItemChoices.php');
// require_once('stock.php');
// require_once('Consumables.php');
// require_once('SideDishes.php');
// require_once('DishCustomization.php');
// require_once('MenuDishes.php');
// require_once('Expenses.php');
// require_once('reservations.php');
// require_once('DB_BackUP.php');
//require_once('R_items.php');
//require_once('qr-code.php');

 

define("RESOURCE_URL", "https://bvistaycationdeals.com/BVI_Staycation-DB/"); 
define("APP_ID", "558d02f0-06ab-47b6-a5bf-ada58ff8a5a4");  



date_default_timezone_set('America/Tortola');

//this will turn off warning and notice on server.
//this may the server slow
//activate when needes
//error_reporting(E_ALL & ~E_NOTICE);
//error_reporting(0);
//error_reporting(E_ALL);


///////******** General Functions ********////////

function OneSignalsendMessage($objPassed=""){
  // error_log( print_R("CancelReservationStaff 222222" ,true) );
  // error_log( print_R($objPassed["token"] ,true) );
 


		$content = array(
			"en" => $objPassed["Msg"]
      );
      
      $header = array(
        "en" => $objPassed["header"]
        );
		
		$fields = array(
			'app_id' => APP_ID,
       'include_player_ids' => $objPassed["Players"], //'include_player_ids' => array("42f0770b-8511-4ed7-8f59-a604cdd51f91"),
       'data' => $objPassed["OneSignalData"],
       'headings'=> $header,
			'contents' => $content
		);
		
	    error_log( print_R("ONESIGNAL fields" ,true) );
	      error_log( print_R($fields ,true) );
		
		$fields = json_encode($fields);
     
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

		$response = curl_exec($ch);
    curl_close($ch);
    
    error_log( print_R("ONESIGNAL SEETING THIS HERE" ,true) );
      error_log( print_R($fields ,true) );
     error_log( print_R($response ,true) );
     error_log( print_R($response ,true) );
    error_log( print_R($response ,true) );
		
		return $response;
}

function max_attribute_in_array($array, $prop) {
  return max(array_map(function($o) use($prop) {
                          return $o->$prop;
                       },
                       $array));
}

function formatDateMysql($timestamp = false) {
  if ($timestamp === false) {
      $timestamp = time();
  }
  return date('Y-m-d H:i:s', $timestamp);
}


function getUniqueId(){
    // will return 22 characters Unique string eg "5bcc2342652c2630171474"
    return str_replace('.', '', uniqid('',true));
  }

  
function EditOrderDetails ($details="", $OrderInfoID="") {
    foreach ($details as  $valueinfo) {
        //saving dish info/
        //we will have to check if the dish has been served or prepeared
        $dishinfosaved=OrdersInfo::saveOrderDishInfo($OrderInfoID,$valueinfo->DishInfo );



    }

}

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
             return true;
            
        }
    }
     return false;
}

function SaveOrderDetails ($details="", $OrderInfoID="") {
global $DISHES_SERVED;
global $EDIT_ORDER_TOTAL;

    foreach ($details as  $valueinfo) {
        //we will have to do it from a function in OrdersInfo class 
        // error_log(print_r( "dishingooo",true));
        // error_log(print_r( $valueinfo->DishInfo->OrderDishInfo_id,true));


     
    //$OrderDishInfo_id=;
    // error_log(print_r( "post value DISHES_SERVED",true));
    // error_log(print_r($DISHES_SERVED,true));
   // error_log(print_r("valueinfo",true));
      // error_log(print_r($valueinfo->DishInfo,true));

    if ( in_array_r($valueinfo->DishInfo->OrderDishInfo_id, $DISHES_SERVED)== false ) {

    
       $dishinfosaved=OrdersInfo::saveOrderDishInfo($OrderInfoID,$valueinfo->DishInfo );
       OrderNotes::saveOrderNote($dishinfosaved->id,$valueinfo->OrderNote );
       $EDIT_ORDER_TOTAL = number_format($valueinfo->DishInfo->Price*$valueinfo->DishInfo->Qty,2,'.', '' ); 
    // error_log(print_r("EDIT_ORDER_TOTAL",true));
    //    error_log(print_r($valueinfo->OrderDishInfo_id,true));
    //    error_log(print_r($valueinfo->OrderDishInfo_id->Price,true));
    //    error_log(print_r($valueinfo->OrderDishInfo_id->Qty,true));
    //    error_log(print_r($EDIT_ORDER_TOTAL,true));


    //  //      OrdersItemChoice::saveOrderItemChoices($orderInfo->id,$valueinfo->ItemChoices );
     foreach ($valueinfo->Extra as  $Extrap) {
        // error_log(print_r("extra passed here",true));
        //  error_log(print_r($Extrap,true));

        // if ($valueinfo->DishInfo->StoringAppOrder == true) {
        //   //wee need to unset OrdersExtraI_id:
        //   unset($Extrap->OrdersExtraI_id);
        //   # code...
        // }
       OrdersExtra::saveOrderExtra($OrderInfoID,$Extrap,$dishinfosaved->id );

      //we can ask the function to return te amount they stored
    //   if ($storedExtra->checked !=false) {
    //     $EDIT_ORDER_TOTAL = number_format($storedExtra->Price + $EDIT_ORDER_TOTAL,2,'.', '' ); 
    //   }
    


     }

    //  error_log(print_r("before entering choices loop",true));
    //  error_log(print_r($valueinfo->ItemChoices ,true));
 
      foreach ($valueinfo->ItemChoices as  $choices) {
        // if ($valueinfo->DishInfo->StoringAppOrder == true) {
        //   //wee need to unset OrdersExtraI_id: 
        //   $choices->StoringAppOrder =true;
           
        // }
       //error_log(print_r(  $choices,true));
       OrdersItemChoice::saveOrderItemChoices($OrderInfoID,$choices ,$dishinfosaved->id );

        // if ($storedChoices->checked !=false) {
        //     $EDIT_ORDER_TOTAL = number_format($storedChoices->Price + $EDIT_ORDER_TOTAL,2,'.', '' ); 
        
      }

    } else {
        // error_log(print_r(  "marked as served",true));
       // $EDIT_ORDER_TOTAL = number_format($valueinfo->DishInfo->Price*$valueinfo->DishInfo->Qty,2,'.', '' ); 


    }
   

  

    }
    
}




function MaronOnServer ($ONLINE_id) {


  $post = [
      'action' => 'MarkOrderSent_To_POS',
      'ONLINE_Order'=> $ONLINE_id
  ];

//    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));
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
  curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_TIMEOUT, 1);

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


  // close the connection, release resources used
  curl_close($ch);
  

}




function MarkOrderPreparing_ONLINE ($DishId) {

  //MAKE MORE RESUSABLE BY PASSING POST ARRAY

  $post = [
      'action' => 'MarkPreparing',
      'DishId'=> $DishId
  ];

//    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));
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
  curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_TIMEOUT, 1);

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


  // close the connection, release resources used
  curl_close($ch);
  

}

function ONLINE_SERVER_MARKER ($postArray=0) {

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, ONLINE_ORDER_CURL);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
  curl_setopt($ch, CURLOPT_TIMEOUT, 2);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postArray));

   //$response=curl_exec($ch) ;

 curl_exec($ch) ;

 // error_log( print_R( $response ,true) );
  
 // close the connection, release resources used
 curl_close($ch);


}



function  RegisterONLINE_Sales($ONLINE_Order="") {

  global $database;

  if ( Orders::findOnlineOrder ($ONLINE_Order->ONLINE_id) ) {
 
    
    // Orders::Mark_Sent_To_POS($ONLINE_Order->ONLINE_id);
    //we need to save the orderInfo since the user should not be able to change orderDetails
    $sql = "UPDATE `Orders` SET  `Status`='{$ONLINE_Order->Status}',`Sent_to_POS`='YES'  WHERE `ONLINE_id`='{$ONLINE_Order->ONLINE_id}' ";

          $database->query($sql)  ;
              MaronOnServer ($ONLINE_Order->ONLINE_id);
         


   


  } else {
   
  error_log(print_r( "false",true));


  $dataPassed = $ONLINE_Order;
  $orderType = $dataPassed->Type;
  $TableNum = $dataPassed->TableNum;
  $Total = $dataPassed->Total;
  error_log(print_r( $dataPassed,true));
  error_log(print_r( "checking post",true));
   error_log(print_r( "inside RegisterSale",true));

 // error_log(print_r($OrderID,true));
 // error_log(print_r( json_decode ($_POST['OrderNote']),true));
 //$detailsToStore = $ONLINE_Order->OrderDetails;

 //this flag will determ to remove or add id when saving


 
  // error_log(print_r(  $details,true));
  $orderDetails =  $ONLINE_Order;

  $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) ) {
  //     $orderInfo->Order_Origin	=$Origin;
  //     $orderInfo->ONLINE_id = getUniqueId() ;

  //   } else {
  //     $orderInfo->Order_Origin	="Local_POS";
  //   }
    

   
  //   $orderInfo->ONLINE_id	='NULL';
    $orderInfo->Sent_to_POS='YES';
    unset( $orderInfo->id);
    unset( $orderInfo->Interactive_date);
    
    //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);

//we should save once all provess is completed to avoid missing the order
    $orderInfo -> save();

     //error_log(print_r( json_decode ($_POST['ItemChoices']),true));
 // $details = json_decode ($_POST['details']);
  //error_log(print_r(  $details[0]['DishInfo'],true));
 
  //$detailsToStore = $ONLINE_Order->OrderDetails;

  //this flag will determ to remove or add id when saving
  $detailsToStore = $ONLINE_Order->OrderDetails;

  foreach ($detailsToStore  as $key => $value) {
     // DishInfo->StoringAppOrder = true;
     $detailsToStore [$key]->DishInfo->StoringAppOrder = true;

     unset ($detailsToStore [$key]->DishInfo->OrderDishInfo_id);

     //unsetting extraID
     foreach ($detailsToStore [$key]->Extra  as $Extra_key => $Extra_value) {
      //unset($detailsToStore [$key]->Extra[$Extra_key]);
      unset ($detailsToStore [$key]->Extra[$Extra_key]->OrdersExtraI_id);
      $detailsToStore [$key]->Extra[$Extra_key] ->StoringAppOrder= true;
     
     }

     //unsetting optionsID
     foreach ($detailsToStore [$key]->ItemChoices  as $Choices_key => $Choices_value) {
      //unset($detailsToStore [$key]->Extra[$Extra_key]);
    
      //unsetting getting ready to unsetoptionsID
        foreach ($detailsToStore [$key]->ItemChoices[$Choices_key ]->Options as $Option_key => $Option_value) {
          unset ($detailsToStore [$key]->ItemChoices[$Choices_key ]->Options[$Option_key]->ItemChoices_Opt_id);
          $detailsToStore [$key]->ItemChoices[$Choices_key ]->Options[$Option_key]->StoringAppOrder= true;
        }
     
     }

    
    
     $detailsToStore [$key]->StoringAppOrder = true;
      // error_log(print_r( $key ,true));
      // error_log(print_r( $value ,true));


  }

  error_log(print_r( $detailsToStore ,true));

   //this flag will determ to remove or add id when saving
 // $detailsToStore[0]->DishInfo->StoringAppOrder = true;
  //unset($detailsToStore[0]->DishInfo->id);
  

  SaveOrderDetails ($detailsToStore , $orderInfo ->id  );

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


  if ($orderInfo) {
      MaronOnServer ($ONLINE_Order->ONLINE_id);
     //return true;
  }else{
    //return false;
  }





  }


 

}




?>