<?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 Messages extends DatabaseObject {

  protected static $table_name="BVIS_Messages";

  //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 findOrderClass ($order_ID="") {
    //we create an and return the order details here
    //error_log(print_r( "inside findOrder",true));

    //error_log(print_r( $_POST,true));
   return  OrdersInfo::findDishInfo($order_ID,"")  ;




  }

  


  public static function testGetField () {
    return self::$db_fields;
  }

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

  public static function setGetField ($idf) {
    return self::$db_fields['id'] = $idf;
  }

 
 
  public static function  GetPackCost ($id) {
    $pack= self::find_by_id ($id);
    return  $pack->Cost;
  } 
  

  public static function   FindPackName ($id) {
    $pack= self::find_by_id ($id);
    return  $pack->Name;
  } 

  public static function   FindCategory ($id) {
    $pack= self::find_by_id ($id);
    return  $pack->Category;
  } 



  function sortByName($a, $b)
  {
      $a = $a['id'];
      $b = $b['id'];

      if ($a == $b) return 0;
      return ($a < $b) ? -1 : 1;
  }
 
  public static function MarkOderAsDeclined ($Orders_ID=""){
    global $database;


    $sql = "UPDATE `Orders` SET `Status`='DECLINED' WHERE `id`='".$Orders_ID."' ";
    $UPdate_Order =   $database->query($sql);

      //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=="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 ="Your order #".$order->id." has been DECLINED.";

         $CustomerData =array(
           "token"=>$CustomerDB->OneSignal_id,
           "Msg"=>$msg,
           'header'=>'ORDER DECLINED',
           "data" => array(
            "route" => "Order"
        ),
           'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
       );

       OneSignalsendMessage($CustomerData);


      }


  }

  public static function MarkOrderPreparing($Orders_ID=""){
    global $database;


    $sql = "UPDATE `Orders` SET `Status`='PREPEARING' WHERE id='".$Orders_ID."' ";
    $UPdate_Order =   $database->query($sql);

    //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" && $order->Status != "PREPEARING") {
           //3rd: we get user details
        // error_log(print_r( Customer::find_by_id($order->Customer_id),true));


         ////before returning check of this 
        //is an online order and mark on server to avoid
        //user from cacelling
 

       // error_log(print_r( "SERVER SHOULD TAKE CARE OF NOTIFIYING USER",true));

      
        // ********* COMMENT ON LOCAL SERVER ****** //

        if (SERVER_MODE=="ONLINE") {

             $CustomerDB = Customer::find_by_id($order->Customer_id);

              $msg ="Your order #".$order->id." is  being prepared .";

              $CustomerData =array(
                "token"=>$CustomerDB->OneSignal_id,
                "Msg"=>$msg,
                'header'=>'PREPARING ORDER',
                'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
            );

            OneSignalsendMessage($CustomerData);

        }

      

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


      }else {


 
         // ********* COMMENT OUT ONLINE SERVER ****** //

         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  being prepared .";

          $CustomerData =array(
            "token"=>$CustomerDB->OneSignal_id,
            "Msg"=>$msg,
            'header'=>'PREPARING ITEM',
            'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
        );


       //let the server to handle pushNotification
       ///this will avoid executing 2 cURL
        OneSignalsendMessage($CustomerData);
         }
        

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


      }


  }

  // public static function MarkOderAsReady ($Orders_ID="", $requestBy=""){
  //   global $database;

  //   if ($requestBy=="Chef") {
  //       $MARK="READY";
  //   } else {
  //     $MARK="SERVED";
  //   }

  //   $sql = "UPDATE `Orders` SET `Status`='".$MARK."' WHERE id='".$Orders_ID."' ";
  //   $UPdate_Order =   $database->query($sql);

  //   //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" ) {
  //          //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 ="Your order #".$order->id." is READY.";

  //        $CustomerData =array(
  //          "token"=>$CustomerDB->OneSignal_id,
  //          "Msg"=>$msg,
  //          'header'=>'READY',
  //          'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
  //      );

  //      OneSignalsendMessage($CustomerData);


  //     }


  // }



  public static function MarkOderAsReady ($Orders_ID="", $requestBy=""){
    global $database;
   $ending;
    if ($requestBy=="Chef") {
        $MARK="READY";
        $ending = "is READY.";
    } else {
      $MARK="SERVED";
      $ending = "was SERVED.";

    }

    $sql = "UPDATE `Orders` SET `Status`='".$MARK."' WHERE id='".$Orders_ID."' ";
    $UPdate_Order =   $database->query($sql);

    //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=="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 ="Your order #".$order->id." ".$ending ;

         $CustomerData =array(
           "token"=>$CustomerDB->OneSignal_id,
           "Msg"=>$msg,
           'header'=> $MARK,
           'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
       );

       OneSignalsendMessage($CustomerData);


      }


  }

  public static function  MarkOderAsPaid ($data="") {

    error_log(print_r( $data,true));

    //1st get the order
    $order = Orders::find_by_id($data["Id"]);
    error_log(print_r( $order , true));

    $order ->Payment_Method = $data["Payment_Method"];
    $order ->Reference = $data["Reference"];
    $order ->Cash = "PAID";
    $order ->Tip = $data["Tip"];

    $result = $order->save();

    ///we need to mark online

    //2nd granting points
    Customer::addPoints($order->Customer_id, $order->Total );

    if ($order->Customer_id !=0 && $order->Payment_Method=="Credit") {
      Customer::AddCredit($order->Customer_id,$order->Total );
   }



    if ( $result){
      //we should print received
     // PrintReceipt ($order);
     $ordertoP = self::FindOrderToPrint($order->id,$order->type );
     PrintReceipt ( $ordertoP[0]);

     //wee need to mark on server

     if (SERVER_MODE=="LOCAL" && $order->ONLINE_id !=NULL ) {
      $post = [
          'action' =>'MarkPaid',
          'OnlinePayment'=>true,
          'order'=>$order
         ];
      ONLINE_SERVER_MARKER ($post);    
     }

    //  self::FindOrderToPrint($order->id, $order->type);
    //    PrintReceipt ($order->id);
 
      
    return true;
  }else{
    return false;
  }



  }


  public static function GetOnlineOrders () {
    global $database;
    $sql = "UPDATE `Orders` SET `Chef_Interaction`='".$State."' WHERE id='".$Orders_ID."' ";
    $UPdate_Order =   $database->query($sql);

  }

  public static function Chef_OrderInteraction ($Orders_ID="", $State="") {
    global $database;
    $sql = "UPDATE `Orders` SET  `Chef_Interaction`='".$State."' WHERE id='".$Orders_ID."' ";
    $UPdate_Order =   $database->query($sql);

    //we will have to set ONLINE to avoid 
    //users from cancelling order while chef interaction
    
    $DB_Order = Orders::find_by_id($Orders_ID);

    if ($DB_Order->Order_Origin =="Mobile_App" && SERVER_MODE=="LOCAL") {
      //get Online_Id of this order
      
      $post = [
        'action' => 'Chef_OrderInteraction',
        'MarkingOnlineDish'=>true,
        'StatePassed'=>$State,
        'Order_ONLINE_ID'=> $DB_Order->ONLINE_id
       ];
       ONLINE_SERVER_MARKER ($post);
      
    }
  }

  public static function FindYour_Customer ($orderID=""){
    global $database;
    $sql = "SELECT `Customer_id` FROM `Orders` WHERE `id`='{$orderID}'"  ;

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

    if ($result) {
      $customerInOrder = $result->fetch_array(MYSQLI_ASSOC);
      ///showing category
     // error_log(print_r( $Categoryrow["Category"]  ,true));
      $customerID = $customerInOrder["Customer_id"] ;
      return Customer::find_by_id($customerID );

    } else {
      return false;
    }
    


    
  }

  public static function FindOrders_Chef () {
   //error_log(print_r( " inside ()"));

      $Delivery = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "Delivery" AND `Status`="In Queue" OR `Status`="PREPEARING"';
      $TakeOut = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "TakeOut" AND `Status`="In Queue" OR `Status`="PREPEARING"';
      $DineIn = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "DineIn" AND `Status`="In Queue" OR `Status`="PREPEARING"';


    //in here we get the online orders and place it
    //in the same array

     $ordersList = array (
       "LOWStock" => Stock::GetmyLowStock (),
      "Delivery"=> self::find_by_sql($Delivery, 'Delivery_Chef'),
      "TakeOut"=> self::find_by_sql($TakeOut, 'TakeOut_Chef'),
      "DineIn"=> self::find_by_sql($DineIn,'DineIn_Chef')
     ) ;

     $ALL = array_merge ( $ordersList["TakeOut"],  $ordersList["DineIn"],  $ordersList["Delivery"]);
     //usort($ALL, 'sortByName');

     array_multisort( array_column($ALL, "Date"), SORT_ASC, $ALL );

     $ordersList ['ALL'] = $ALL;


     //usort( $ALL, function ($a, $b) {return $a['Date'] < $b['Date'];});

     //usort( $ALL, function ($a, $b) {return $a['Date'] < $b['Date'];});

    //  usort($ordersList ["ALL"] , function ($a, $b) {
    //     return $a["Date"] - $b["Date"];
    // });


     //return self::find_by_sql($sql)  ;
    // error_log(print_r( "redady to return"  ,true));
    //  usort($ALL, function($a,$b) {
    //     if($a['Date']== $b['Date']) return 0;
    //     return ($a['Date']< $b['Date']) ? -1 : 1;
    // });

     //error_log(print_r(sort_array_of_array($ALL, 'Date'),true));
    //  error_log(print_r( "before return"));
    //  error_log(print_r( $ordersList));
    return $ordersList  ;
  }

 
 
  public static function FindActivePackages () {
      // error_log(print_r( " inside ()"));

      $packagesSQL = 'SELECT * FROM `BVIS_Packages` WHERE `Valid_Until` > CURDATE() AND `Active` !="false"  ' ;
 
      

      $Bus_packages =   self::find_by_sql($packagesSQL, 'FormatPackages')  ;

       //return self::find_by_sql($sql)  ;
      //error_log(print_r( "redady to return ONLINEEEEEE ORDERS"  ,true));
      //error_log(print_r( $ordersList  ,true));
 
 
 
     return   $Bus_packages  ;

  }

 
 
 

  

 
 

 

 

  //  public static function FindRepeatCustomers ($datePassed="") {
  //   global $database;

  //    //fix for mysql 5.7
  //    $FIX_ONLY_FULL_GROUP_BY = "SET sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''))";

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


  //   $sql = "SELECT `Date` FROM `Orders`  WHERE `Date` LIKE '{$datePassed}%' AND `Customer_id` != 0  GROUP BY `Customer_id`";


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

  //   return  $dataBaseResult->num_rows;
  // }







  public function full_name() {
    if(isset($this->First_Name) && isset($this->Last_Name)) {
      return $this->First_Name . " " . $this->Last_Name;
    } else {
      return "";
    }
  }





}

?>