<?php
// If it's going to need the database, then it's 
// probably smart to require it before we start.
//error_reporting(0);
require_once("initializer.php");
 
class OrdersInfo  extends DatabaseObject {
	
  protected static $table_name="OrderDishInfo";
 
  
  //we will populate this array of attribure dynamically
	//protected static $db_fields = array('id','Username','Privilege','First_Name','Last_Name','Password');
  
  protected static $db_fields;
  protected static $exclu_fields = array ("");

	// public  $id;
	// public $Username;
	// public $Privilege;
	// public $Last_Name;
  // public $First_Name;
  // public $Password;

  public function __construct($options=""){
    if ($options=="Blank") {
      $myFields = static::Get_Object_Fields ();
      foreach($myFields as $field) {
        $this->{$field} = "";
      }
    }

   // unset ($this->id);
    
  }

  public static function MarkDishReady ($OrderDishInfo_id="", $Orders_ID="") {
    global $database;
    // error_log(print_r("ALL DEKE IN MAREKR",true));
    // error_log(print_r($Orders_ID,true));

 
   $sql = "UPDATE `OrderDishInfo` SET `interactiveDate`=NOW(), `Dish_Status`='READY' WHERE `OrderDishInfo_id`='".$OrderDishInfo_id."' ";

   $result =  $database->query($sql) ; 

   if ($result ) {
     //we alert about this dish ready
     //alerting user
      //2nd: we need to get the user id based on Order_ID
      $order = Orders::find_by_id($Orders_ID);
      //error_log(print_r( Orders::find_by_id($item->Orders_ID),true));
 
      if ($order->Order_Origin == "Mobile_App" && SERVER_MODE=="LOCAL") {

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

        $OrderDish = self::getDishInfo ($OrderDishInfo_id);  

        $post = [
          'action' => 'MarkReady',
          'MarkingOnlineDish'=>true,
          'DishInfo_ONLINE_ID'=> $OrderDish->DishInfo_ONLINE_ID
         ];
  
         ONLINE_SERVER_MARKER ( $post);
       ////***********************************///////////////////

 
      }

      if ( SERVER_MODE=="ONLINE") {
           //3rd: we get user details
           error_log(print_r( Customer::find_by_id($order->Customer_id),true));
           $CustomerDB = Customer::find_by_id($order->Customer_id);
   
           $msg ="An item in your order #".$order->id." is READY.";
   
           $CustomerData =array(
             "token"=>$CustomerDB->OneSignal_id,
             "Msg"=>$msg,
             'header'=>'ITEM READY',
             'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
          );
   
         OneSignalsendMessage($CustomerData);
      }


   }

   

   if (self::FindOrderDishesState($Orders_ID, "Chef")==0) {
    //Marking the order as SERVED Since we don't have dishes pending
     Orders::MarkOderAsReady($Orders_ID, "Chef");
   }

   //we need to reduce consumable
   Stock::ReduceStock ($OrderDishInfo_id);
    return $result ; 

  }

  public static function FindDishItemType ($OrderDishInfo_id="") {
    global $database;

    $sql = "SELECT `ItemType`,`ItemType_id` FROM `OrderDishInfo` WHERE `OrderDishInfo_id` = '".$OrderDishInfo_id."' ";

    return $database->query($sql);



  }


  



  public static function findDishInfoForChef ($Orderid="") {

  }

  //we may need to create an special function 
  ///that will change ItemType_id to id


  public static function  getDishforUser ($Orderid="") {

   return $infodishes = self::find_by_sql('SELECT * FROM `OrderDishInfo` WHERE  `Dish_Status`= "READY" AND `Orders_ID` ="'.$Orderid.'"  ORDER BY `Dish_Status` ASC',"" )  ;



  }

  public static function findDishInfo ($Orderid="", $ChefFlag="") {

    $finalOrder = [];

    if ($ChefFlag=="Chef") {
      $infodishes = self::find_by_sql('SELECT * FROM `OrderDishInfo` WHERE `Orders_ID` ="'.$Orderid.'" AND (`Dish_Status`="IN QUEUE" AND `Dish_Status`="PREAPARING" AND `Dish_Status`!="SERVED" OR `Dish_Status`!="READY") ORDER BY `Dish_Status` ASC ',"")  ;

    } else {
      
      $infodishes = self::find_by_sql('SELECT * FROM `OrderDishInfo` WHERE `Orders_ID` ="'.$Orderid.'" ORDER BY `Dish_Status` ASC',"" )  ;

  }
    

    //we need to change the ItemType_id to just id
    //error_log(print_r( "OrderDishInfo_id fron inside infodishes"  ,true));
    //error_log(print_r($infodishes,true));
    $a=[];

    foreach(  $infodishes as $attribute =>$value){
      // error_log(print_r("inside loppp"  ,true));
      // error_log(print_r( $infodishes [$attribute ] ,true));
      // //  if(  $attribute == "ItemType_id" ) {
      // //   error_log(print_r("inside loppp"  ,true));
      // //   error_log(print_r($value ,true));
   
      $value ->id =  $value ->ItemType_id;
       unset($value ->ItemType_id);  
      // error_log(print_r(  $infodishes [$attribute ]  ,true));
       $finalOrder->DishInfo = $infodishes [$attribute ] ;
       //error_log(print_r($finalOrder ,true));

      //  if(  $attribute == "OrderDishInfo_id" ) {
           $dish_OrderDishInfo_id =  $value->OrderDishInfo_id ;
       //}

       $noteVar = $value->OrderDishInfo_id ;


       $orderDetails=array("DishInfo"=>$infodishes [$attribute ] ,
                            "Extra"=>OrdersExtra::FindOrderExtra($Orderid, $dish_OrderDishInfo_id ),
                            "ItemChoices"=>OrdersItemChoice::FindOrderChoices($Orderid, $dish_OrderDishInfo_id ),
                            "OrderNote" => OrderNotes::GetNotes($noteVar)
                          );
//
array_push($a,$orderDetails);
//error_log(print_r($a ,true));

    }
    //error_log(print_r( $infodishes  ,true));

    return $a;



  }

  public static function TotalDishPrice ($orderID="", $TotalExtra="",$TotalChoices="") {
    //error_reporting(-1);
    global $database;
    $NewTotal = 0;
     
     $sql = "SELECT `OrderDishInfo_id`,`Price`,`Qty` FROM `OrderDishInfo` WHERE `Orders_ID`='".$orderID."' ";

     $DishesPrices =  $database->query($sql) ; 

     foreach (mysqli_fetch_all($DishesPrices,MYSQLI_ASSOC) as $key=>$DishesPrices) { 
     // $Total = ($value['Price']* $value['Qty']) + $Total;

    //  error_log(print_r('TotalChoices loop in DishesPrices',true));
    //   error_log(print_r($DishesPrices,true));

          //loop to add EXTRAS 
          foreach ($TotalExtra as $key => $Extravalue) {
            if ( $DishesPrices['OrderDishInfo_id'] == $Extravalue['OrderDishInfo_id'] ) {
                $NewTotal = number_format($Extravalue['Price']+ $NewTotal ,2,'.', '' );
            }
              //error_log(print_r($value,true));
          }

           //loop to add CHOICES 
           foreach ($TotalChoices as $key => $Choicevalue) {
            if ( $DishesPrices['OrderDishInfo_id'] == $Choicevalue['OrderDishInfo_id'] ) {
              $NewTotal = number_format($Choicevalue['Price']+ $NewTotal ,2,'.', '' );
            }
              //error_log(print_r($value,true));
          }


           //now we add the Dish Price and multiply by the Qty
          $NewTotal = number_format(($DishesPrices['Price']+ $NewTotal)*$DishesPrices['Qty'],2,'.','' );
          //error_log(print_r($NewTotal ,true));





  
     }
     
    // error_log(print_r('Total Price',true));
  
     
     
     return $NewTotal;
  
   
  
  
     
  
  }

  public static function FindOrderDishesStateForStaff ($StaffID="") {
    global $database;
 
    $sql = "SELECT `Orders_ID`,`Dish_Status`,`Qty` FROM `OrderDishInfo` WHERE `Dish_Status`='READY' OR `Dish_Status`='DECLINED' AND	`APEX_Staff_ID`='".$StaffID."' ";
     //$OrderDishState = $database->query($sql);
  

    return mysqli_fetch_all($database->query($sql),MYSQLI_ASSOC);
  }

  public static function DeclindedByChef () {
    global $database;
    $sql = 'SELECT `Dish_Status` FROM `OrderDishInfo` WHERE DATE(`interactiveDate`)=CURDATE() AND `Dish_Status`!="PREPARING" AND `Dish_Status`!="IN QUEUE" AND `Dish_Status`="DECLINED" ';

    $interacted = $database->query($sql);
    return $interacted->num_rows;

  }

  public static function PraparedByChef () {
    global $database;
    $sql = 'SELECT `Dish_Status` FROM `OrderDishInfo` WHERE DATE(`interactiveDate`)=CURDATE() AND `Dish_Status`!="PREPARING" AND `Dish_Status`!="IN QUEUE" AND `Dish_Status`!="DECLINED" ';

    $interacted = $database->query($sql);
    return $interacted->num_rows;

  }



  public static function Dishes_chef_Interact () {
    global $database;
    $sql = 'SELECT * FROM `OrderDishInfo` WHERE DATE(`interactiveDate`)=CURDATE() AND `Dish_Status`!="PREPARING" AND `Dish_Status`!="IN QUEUE" ';

    return  mysqli_fetch_all( $database->query($sql),MYSQLI_ASSOC);
    //return $interacted;
  }


  

  public static function NumberOfOrder_chef_Interact () {
    global $database;
    $sql = 'SELECT `Dish_Status` FROM `OrderDishInfo` WHERE DATE(`interactiveDate`)=CURDATE() AND `Dish_Status`!="PREPARING" AND `Dish_Status`!="IN QUEUE" ';

    $interacted = $database->query($sql);
    return $interacted->num_rows;
  }


  public static function FindOrderDishesStateUSER ($Orders_ID="") {
    global $database;
 
      $sql = 'SELECT * FROM `OrderDishInfo` WHERE `Orders_ID`="'.$Orders_ID.'" AND (`Dish_Status`="PREPARING" OR `Dish_Status`="READY")';

     $OrderDishState = $database->query($sql);
    error_log(print_r("FindOrderDishesState before return",true));
   error_log(print_r( $OrderDishState,true));

    return $OrderDishState->num_rows;
  }

 

  public static function FindOrderDishesState ($Orders_ID="",$ChefFlag="") {
    global $database;

    if ($ChefFlag=="Chef") {
      $sql = 'SELECT * FROM `OrderDishInfo` WHERE `Orders_ID`="'.$Orders_ID.'" AND `Dish_Status`!="SERVED" AND `Dish_Status`!="READY"  AND `Dish_Status`!="DECLINED"';

    } else {
      $sql = 'SELECT * FROM `OrderDishInfo` WHERE `Orders_ID`="'.$Orders_ID.'" AND (`Dish_Status`="IN QUEUE" OR `Dish_Status`="READY")';

    }
    
 
     $OrderDishState = $database->query($sql);
    error_log(print_r("FindOrderDishesState before return",true));
   error_log(print_r( $OrderDishState,true));

    return $OrderDishState->num_rows;
  }

  public static function DeclineByChef ($OrderDishInfo_id="", $OrderID=""){
    global $database;
    $sql = "UPDATE `OrderDishInfo` SET  `interactiveDate`=NOW(), `Dish_Status`='DECLINED' WHERE `OrderDishInfo_id`='".$OrderDishInfo_id."' ";
    $dishMarked =  $database->query($sql);

    //IMPORTANT NOTE.
    //WE WILL HAVE TO SUBCTRACT 
    //THE AMOUNT OF THE DECLINED DISH
    //INCLUDING EXTRA OR CHOICES

    //If dishmarked

    if ($dishMarked) {
      //1st we get the total of dish amoun and 
      $sql = "SELECT `Price`,`Qty` FROM `OrderDishInfo` WHERE `OrderDishInfo_id`='".$OrderDishInfo_id."'  AND `Orders_ID`='".$OrderID."' ";

      $DISH_Price_QTY = mysqli_fetch_all( $database->query($sql),MYSQLI_ASSOC);

      //  error_log(print_r("SHOW ME THE total",true));
      //  error_log(print_r($DISH_Price_QTY[0]['Price']*$DISH_Price_QTY[0]['Qty'],true));

       //number_format(round((float)$FINAL_TOTAL,2),2) 


      //2nd we get the total extra
      $TOTAL_Of_EXTRA = OrdersExtra::GetDishExtras_TOTAL($OrderDishInfo_id,$OrderID);

      // //3rd 
       $TOTAL_Of_CHOICES = OrdersItemChoice::GetDishChoices_TOTAL($OrderDishInfo_id,$OrderID);

       $AMOUNT_TO_REDUCE =  number_format(round((float)  $DISH_Price_QTY[0]['Qty']*($TOTAL_Of_EXTRA+$TOTAL_Of_CHOICES+$DISH_Price_QTY[0]['Price']),2),2);
      //  error_log(print_r( "AMOUNT_TO_REDUCE before calling UpdateOrderTotal " ,true));
      //  error_log(print_r( $AMOUNT_TO_REDUCE ,true));

      //  error_log(print_r( "value for UpdateOrderTotal " ,true));
      //  error_log(print_r( $OrderID,true));
       
       Orders::UpdateOrderTotal ($OrderID, $AMOUNT_TO_REDUCE, "REDUCE");

                 //alerting user
      //2nd: we need to get the user id based on Order_ID
      $order = Orders::find_by_id($OrderID);
      //error_log(print_r( Orders::find_by_id($item->Orders_ID),true));
 
      if ($order->Order_Origin == "Mobile_App") {


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

         if (SERVER_MODE=="LOCAL") {
           
           $OrderDish = self::getDishInfo ($OrderDishInfo_id);  

         $post = [
           'action' => 'MarkDecline',
           'MarkingOnlineDish'=>true,
           'DishInfo_ONLINE_ID'=> $OrderDish->DishInfo_ONLINE_ID
          ];
   

          ONLINE_SERVER_MARKER ( $post);
         }


        ////***********************************///////////////////

        if (SERVER_MODE=="ONLINE") {


                //3rd: we get user details
              error_log(print_r( Customer::find_by_id($order->Customer_id),true));
              $CustomerDB = Customer::find_by_id($order->Customer_id);
      
              $msg ="An item in your order #".$order->id." has been DECLINED.";
      
              $CustomerData =array(
                "token"=>$CustomerDB->OneSignal_id,
                "Msg"=>$msg,
                'header'=>'ITEM DECLINED',
                "data" => array(
                  "route" => "Order"
              ),
                'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
            );
      
            OneSignalsendMessage($CustomerData);
           
          
        }


 
 
      }

 
     }

    //similar to FindOrderDishesState and MarkOderAsReady
    //we run MarkOrderAsDeclined which will
    //mark the order as declined if needed
    self::MarkOrderAsDeclined($OrderDishInfo_id, $OrderID);



    return $dishMarked;

  }

  public static function MarkOrderAsDeclined ($OrderDishInfo_id="", $OrderID=""){
    global $database;
    error_log(print_r("ORDER WHATTT",true));
    error_log(print_r( $OrderID,true));

    $sql = "SELECT COUNT(1) FROM `OrderDishInfo` WHERE `Orders_ID`='".$OrderID."' ";

    $sql_DECLINED = "SELECT COUNT(1) FROM `OrderDishInfo` WHERE `Orders_ID`='".$OrderID."' AND `Dish_Status`='DECLINED'";


    $TOTAL_ITEMS =$database->query($sql);

    $TOTAL_DECLINED=$database->query($sql_DECLINED) ;
 

     

    if ( mysqli_fetch_array($TOTAL_ITEMS)['0'] === mysqli_fetch_array($TOTAL_DECLINED)['0']) {
      error_log(print_r("before we maked declined",true));

      //now we will ask Order to MArk as Declined
      //and fix chef not to show declined orders

      Orders::MarkOderAsDeclined ($OrderID);
    

    } else {
      //we check if order ready????

      error_log(print_r("ELSE DECLINED",true));

      if (self::FindOrderDishesState($OrderID, "Chef")==0) {
         Orders::MarkOderAsReady($OrderID, "Chef");
       }
     

    }
    
    


  }

  public static function MarkPreparing ($OrderDishInfo_id=""){
    global $database;
    $sql = "UPDATE `OrderDishInfo` SET  `interactiveDate`=NOW(),`Dish_Status`='PREPARING' WHERE `OrderDishInfo_id`='".$OrderDishInfo_id."' ";
    $dishMarked =  $database->query($sql);

    if ( $dishMarked) {
      //we alert user and mark order

       //alerting user
      //2nd: we need to get the user id based on Order_ID
      $OrderDish = self::getDishInfo ($OrderDishInfo_id);  
       error_log(print_r( $OrderDishInfo ,true));
      //error_log(print_r( Orders::find_by_id($item->Orders_ID),true));
      $order = Orders::find_by_id( $OrderDish->Orders_ID);

 
       error_log(print_r($order,true));
      //  if ($order->Order_Origin == "Mobile_App" ) {
      //   //WE EXECUTE ONLINE CURL WHICH WILL NOTIFY
      //   //USER ACCORDINDLY
      //  // error_log(print_r( "SERVER WILL TAKES CARE OF PNS" ,true));
      //  // MarkOrderPreparing_ONLINE ($OrderDishInfo_id); 
      //  }

       Orders::MarkOrderPreparing( $order->id);

    }


    ////*****COMMENT THIS ON SERVER*******///////
    ////before returning check of this 
    //is an online order and mark on server to avoid
    //user from cacelling
    if ($order ->Order_Origin == "Mobile_App" && SERVER_MODE=="LOCAL") {

      $post = [
        'action' => 'MarkPreparing',
        'MarkingOnlineDish'=>true,
        'DishInfo_ONLINE_ID'=> $OrderDish->DishInfo_ONLINE_ID
       ];

      //  $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 =curl_exec($ch) ;
     
      //  error_log( print_R( $response ,true) );
    
    
      // // close the connection, release resources used
      // curl_close($ch);

      ONLINE_SERVER_MARKER ( $post);

     }
    
 ////********************************///////
 
    return $dishMarked;
  }

  public static function getDishInfo($id=0) {
    //self::Get_Object_Fields ()
    $result_array = self::find_by_sql("SELECT * FROM `OrderDishInfo` WHERE `OrderDishInfo_id`={$id} LIMIT 1","");
        return !empty($result_array) ? array_shift($result_array) : false;
  }

  public static function getDishInfo_ONLINE_ID($ONLINE_ID=0) {
    //self::Get_Object_Fields ()
    $result_array = self::find_by_sql("SELECT * FROM `OrderDishInfo` WHERE `DishInfo_ONLINE_ID`='{$ONLINE_ID}' LIMIT 1","");
        return !empty($result_array) ? array_shift($result_array) : false;
  }




  
  public static function MarkServed ($OrderDishInfo_id="",$Orders_ID=""){
    global $database;
    $sql = "UPDATE `OrderDishInfo` SET `Dish_Status`='SERVED' WHERE `OrderDishInfo_id`='".$OrderDishInfo_id."' ";
    $dishMarked =  $database->query($sql);

    $sqlMark = "SELECT * FROM `OrderDishInfo` WHERE `OrderDishInfo_id`='".$OrderDishInfo_id."' AND `Orders_ID` ='".$Orders_ID."' ";
    $marRes = self::find_by_sql($sqlMark,"");

    $findItem =$marRes[0];
    if ( $findItem->ItemType =="Menu_Dishes") {
      $sqlMenu = "UPDATE `MenuDishes` SET `Served`=`Served`+1 WHERE `id`='{$findItem->ItemType_id}'";
      $database->query($sqlMenu);
    } else {
      $sqlDish = "UPDATE `SideDishes` SET `Served`=`Served`+1 WHERE `id`='{$findItem->ItemType_id}'";
      $database->query($sqlDish);
    }
    

    //SELECT * FROM `OrderDishInfo` 
    //before returning we need to make sure that
    //The order dont have any other dishes pending or 
    //preapare and them marked the other as served

     //error_log(print_r("FindOrderDishesState",true));
     //error_log(print_r( self::FindOrderDishesState ($Orders_ID) ,true));

 
     if (self::FindOrderDishesState($Orders_ID)==0) {
     //Marking the order as SERVED Since we don't have dishes pending
     Orders::MarkOderAsReady($Orders_ID);
    }

    return  $dishMarked ;
  }
  

  public static function DeleteDishInfo ($orderID="") {
    global $database;
    
    $sql = 'DELETE FROM `OrderDishInfo` WHERE `Orders_ID`="'.$orderID.'" AND `Dish_Status`="IN QUEUE" ';
    $OrderReadyCount =   $database->query($sql);
    
  }


  public static function FindUneditableDishes($orderID="") {
    global $database;

    //$sql = 'SELECT `id` FROM `Orders` WHERE `Orders_ID`="'.$orderID.'" AND `Dish_Status`!="IN QUEUE" ';
    $sql = 'SELECT `OrderDishInfo_id`, `Qty`,`Price`  FROM `OrderDishInfo` WHERE `Orders_ID`="'.$orderID.'" AND `Dish_Status`!="IN QUEUE" ';
    $UneditableDishes = $database->query($sql);
     //$result = $database->query($sql);

     //error_log(print_r("is this an array??????",true));
    // error_log(print_r(mysqli_fetch_all($UneditableDishes) ,true));
     //return $UneditableDishes->num_rows;
    // mysqli_fetch_all($restult_set , MYSQLI_ASSOC)
     return mysqli_fetch_all($UneditableDishes,MYSQLI_ASSOC);
   }




  public static function saveOrderDishInfo ($orderID="",$object="") {
    //error_log(print_r(  "inside saveOrderDishInfo",true));

     error_log(print_r(  $object,true));

    $Info = new self ("Blank");
         foreach(  $object as $attribute =>$value){
            if(property_exists($Info,$attribute) && $attribute != "id" ) {
              $Info->$attribute = $value;
            }  
         }
      
       // $Info->Status="In Queue";

       //unset( $Info->OrderDishInfo_id);
       //unset( $Info->id);
       $Info->Dish_Status = "IN QUEUE";	
      
        if ($object->StoringAppOrder==true) {
        unset( $Info->OrderDishInfo_id);
        unset( $Info->interactiveDate);
        $Info->ItemType_id = $object->id;
       }else{
        $Info->ItemType_id = $object->id;
       }

       $Info->Orders_ID =  $orderID;
       //*******COMMENT ON LOCAL SERVER ********/
       if (SERVER_MODE=="ONLINE") {
        $Info->DishInfo_ONLINE_ID = getUniqueId();
       }
      // $Info->DishInfo_ONLINE_ID = getUniqueId();
       /////*******************//////////////// */
 
  
       $Info->save();
      return $Info ;

    // error_log(print_r("seee info here",true));

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

}

public static function find_by_OrderDishInfo_id($id=0) {
  //self::Get_Object_Fields ()
  $result_array = static::find_by_sql("SELECT ".static::Columns_Select()." FROM ".static::$table_name." WHERE OrderDishInfo_id={$id} LIMIT 1");
      return !empty($result_array) ? array_shift($result_array) : false;
}



  public static function createProperty( $name, $value ){
     $this->{$name} = $value;
}

  public static function setGetField ($idf) {
    return self::$db_fields['id'] = $idf;
  }
	
  public function full_name() {
    if(isset($this->First_Name) && isset($this->Last_Name)) {
      return $this->First_Name . " " . $this->Last_Name;
    } else {
      return "";
    }
  }

  



}

?>