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

  protected static $table_name="Orders";


  //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 UpdateOrderTotal ($Orders_ID="", $newTotal="",$IntrucFlag="") {

    global $database;
    error_log(print_r( "AMOUNT_TO_REDUCE in UpdateOrderTotal working" ,true));

    //removing , Commma

    $num = number_format($newTotal,2,'.','') ;


    //getting order

    $Order= self::find_by_id ($Orders_ID);
    $storedTotal = $Order->Total ;

    $Ordertotal  =  number_format($Order->Total-$num ,2,'.','') ;

     error_log(print_r($num ,true));

     error_log(print_r( number_format($Order->Total-$num ,2,'.','')  ,true));

   error_log(print_r( "AMOUNT_TO_REDUCE in valllllllll" ,true));
    // error_log(print_r( $Ordertotal ,true));




    if ($IntrucFlag=="REDUCE") {
      $sql = "UPDATE `Orders` SET `Total`='".$Ordertotal."' WHERE `id`='".$Orders_ID."' ";

      $Order->Total = number_format($Order->Total-$num ,2,'.','');

    } else {
      $sql = "UPDATE `Orders` SET `Total`='".$newTotal."' WHERE `id`='".$Orders_ID."' ";
    }
     error_log(print_r( $sql ,true));


    //$sql = "UPDATE `Orders` SET `Total`='".$newTotal."' WHERE id='".$Orders_ID."' ";
  $UPdate_Order =   $database->query($sql);
//$UPdate_Order =  $Order->save();

    if ($UPdate_Order) {
      return true;
    } else {
     return false;
    }


  }

  public static function CHECK_Chef_OrderInteraction ($Orders_ID="") {

    global $database;
    $sql = "SELECT `Chef_Interaction` FROM `Orders` WHERE `id`='".$Orders_ID."' ";
    $State =   $database->query($sql);

    $row=$State->fetch_assoc();
    $FinalState= $row['Chef_Interaction'];

    return $FinalState;

  }

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

  public static function Mark_Sent_To_POS ($ONLINE_id=""){ 
    global $database;
 
    $sql = "UPDATE `Orders` SET `Sent_to_POS`='YES' WHERE `ONLINE_id`='{$ONLINE_id}' " ;
    $database->query($sql);

  }

  public static function findOnlineOrder ($orderOnlineID=""){
    global $database;
    $sql = "SELECT `Status` FROM `Orders` WHERE `ONLINE_id`='{$orderOnlineID}' ";


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

    error_log(print_r( $result->num_rows ,true));
    
    if ($result->num_rows > 0 ) {
       return true;
    } else {
       return false;
    }
    

    
  }

  public static function CHECK_If_SERVED ($Order_ID="") {

    global $database;
    $sql = "SELECT `Status` FROM `Orders` WHERE `id`='".$Order_ID."' ";
    $State =   $database->query($sql);

    $row=$State->fetch_assoc();
    $FinalState= $row['Status'];

    return $FinalState;

  }

  public static function UPDATE_ORDER_STATE ($Order_ID="") {

    global $database;
    $sql = "UPDATE `Orders` SET `Date`=NOW(),`Status`='In Queue' WHERE `id`='".$Order_ID."' ";

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

  }



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

      if ($a == $b) return 0;
      return ($a < $b) ? -1 : 1;
  }

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

    $orderFound = Orders::find_by_id($Orders_ID);

    if ($orderFound->Status == 'In Queue' && $orderFound->Chef_Interaction =='CLOSE') {

      $orderFound->Status = 'DECLINED';
      $orderFound->Sent_to_POS = 'NO';

      if ($orderFound->save()) {
        return self::UserOders ($orderFound->Customer_id);
      } else {
       return false;
      }
     } else {
       return false;
    }
    

  }

  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 ConfirmDecline ($order_ID="") {
    global $database;

    $sql = "UPDATE `Orders` SET `Chef_Interaction`='DECLINED' WHERE id='".$order_ID."' ";
    return $database->query($sql);

  }

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

      $Delivery = 'SELECT * FROM `Orders` WHERE `Order_Origin`="Mobile_App" AND `Sent_to_POS`="NO" AND Type = "Delivery" ' ;
      $TakeOut = 'SELECT * FROM `Orders` WHERE `Order_Origin`="Mobile_App" AND `Sent_to_POS`="NO" AND Type = "TakeOut"  ';

      

      $DeliveryArray =   self::find_by_sql($Delivery, 'Delivery')  ;

      $TakeOutArray = self::find_by_sql($TakeOut, 'TakeOut') ;
      //return self::find_by_sql($sql)  ;
      //error_log(print_r( "redady to return ONLINEEEEEE ORDERS"  ,true));
      //error_log(print_r( $ordersList  ,true));
 
 
 
     return array_merge( $DeliveryArray,$TakeOutArray )  ;

  }

    public static function  FindOrderToPrint ($order_ID="", $type="") {
      $findOrder = "SELECT * FROM `Orders` WHERE `id` ='".$order_ID."' ";

      return self::find_by_sql($findOrder, $type);

    }


  public static function FindOrderByID ($order_id="") {

    $findOrder = "SELECT * FROM `Orders` WHERE `id` ='".$order_id."' ";

    return self::find_by_sql($findOrder, 'TakeOut');

  }

  public static function UserOders ($userID="") {


    $Delivery = 'SELECT * FROM `Orders` WHERE `Date` >= (CURDATE() - INTERVAL 3 DAY ) AND `Cash` = "UNPAID" AND Type = "Delivery" AND `Chef_Interaction` != "DECLINED" AND `Customer_id` ="'.$userID.'"' ;
    $TakeOut = 'SELECT * FROM `Orders` WHERE `Date` >= (CURDATE() - INTERVAL 3 DAY ) AND `Cash` = "UNPAID" AND Type = "TakeOut" AND `Chef_Interaction` != "DECLINED" AND `Customer_id` ="'.$userID.'"' ;

    $DeliveryPAID = 'SELECT * FROM `Orders` WHERE `Date` >= (CURDATE() - INTERVAL 10 DAY ) AND `Cash` = "PAID" AND Type = "Delivery" AND `Chef_Interaction` != "DECLINED" AND `Customer_id` ="'.$userID.'"' ;
    $TakeOutPAID = 'SELECT * FROM `Orders` WHERE `Date` >= (CURDATE() - INTERVAL 10 DAY ) AND `Cash` = "PAID" AND Type = "TakeOut" AND `Chef_Interaction` != "DECLINED" AND `Customer_id` ="'.$userID.'"' ;

    $ordersList = array (
      "Delivery"=> self::find_by_sql($Delivery, "Delivery"),
      "TakeOut"=> self::find_by_sql($TakeOut, "TakeOut"),
           ) ;

    $PaidsList = array (
            "Delivery"=> self::find_by_sql($DeliveryPAID, "Delivery"),
            "TakeOut"=> self::find_by_sql($TakeOutPAID, "TakeOut"),
                 ) ;

   

     return  array (
                  "Unpaid"=> array_merge($ordersList["Delivery"] , $ordersList["TakeOut"]),
                  "Paid"=> array_merge($PaidsList["Delivery"] , $PaidsList["TakeOut"]),
                      ) ; 
          }

 public static function  GetTotalUnpaidOrder () {
   global $database;
   $sql = "SELECT COUNT(*) FROM `Orders` WHERE `Cash` ='UNPAID' AND `Chef_Interaction`!='DECLINED'";
   $result = $database->query($sql);
   $total = mysqli_fetch_assoc($result);
   return  $total ['COUNT(*)'];


  }

  public static function  GetMoreUnpaidOrder ($Table="",$pageNum="" ){
    global $database;
    $no_of_records_per_page = 5;
    $offset = ($pageNum-1) * $no_of_records_per_page; 

    //we get the total of page
    //and use to make sure with get last set

    $total_pages_sql = "SELECT COUNT(*) FROM `Orders` WHERE  Type = '{$Table}' AND `Chef_Interaction` != 'DECLINED'";
    $result = $database->query($total_pages_sql); 
    //mysqli_query($conn,$total_pages_sql);
    
    $total_rows = mysqli_fetch_array($result)[0];
    $total_pages = ceil($total_rows / $no_of_records_per_page);

    // if ($pageNum > $total_pages) {
    //    $offset  =$total_pages+1;
    // }


    $sql = "SELECT * FROM `Orders` WHERE `Cash` = 'UNPAID' AND Type = '{$Table}' AND `Chef_Interaction` != 'DECLINED' LIMIT {$offset}, {$no_of_records_per_page}"; 


    switch ($Table) {
      case "Delivery":
      return  array ("Value"=>self::find_by_sql($sql, "Delivery"),
                    "offset"=>$total_pages
                );
    
           break;
      case "TakeOut":
        return  array ("Value"=>self::find_by_sql($sql, "TakeOut"),
        "offset"=>$total_pages
    );
      
           break;
      case "DineIn":
      return  array ("Value"=>self::find_by_sql($sql, "DineIn"),
      "offset"=>$total_pages);
            break;
    
  }




  }

  public static function FindUnpaidDineInOrders () {
    $DineIn = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "DineIn" AND `Chef_Interaction` != "DECLINED" AND `Order_Origin` !="ONLINE"'; 
   return array (  "DineIn"=> self::find_by_sql($DineIn,"DineIn"));

  }

  public static function FindUnpaidOrders () {
     error_log(print_r( "inside FindUnpaidOrders" ,true));

      $Delivery = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "Delivery" AND `Chef_Interaction` != "DECLINED"  LIMIT 5' ;
      $TakeOut = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "TakeOut" AND `Chef_Interaction` != "DECLINED"  LIMIT 5';
      $DineIn = 'SELECT * FROM `Orders` WHERE `Cash` = "UNPAID" AND Type = "DineIn" AND `Chef_Interaction` != "DECLINED" AND `Order_Origin` !="ONLINE"  LIMIT 5'; 

     $ordersList = array (
      "Delivery"=> self::find_by_sql($Delivery, "Delivery"),
      "TakeOut"=> self::find_by_sql($TakeOut, "TakeOut"),
      "DineIn"=> self::find_by_sql($DineIn,"DineIn")
     ) ;
     //return self::find_by_sql($sql)  ;
    // error_log(print_r( "redady to return"  ,true));
    // error_log(print_r( $ordersList  ,true));
    return $ordersList  ;
  }

  public static function FindOrderID($TableNum="") {
    $sql = "SELECT `id` FROM `Orders` WHERE `TableNum` ='".$TableNum."' AND `Cash`='UNPAID' AND `Type`='DineIn' AND `TableNum`!='N/A'  LIMIT 1 ";
     $Orderid =  self::find_by_sql( $sql,"");
    return $Orderid[0]->id;
  }

  public static function ReportOrder($StaffID="") {
    //$sql = "SELECT * FROM `Orders` WHERE  `Interactive_date`>= DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND `APEX_Staff_ID`='".$StaffID."' AND `Cash`='PAID' ORDER BY `Date` DESC LIMIT 20";
    $sql = "SELECT * FROM `Orders` WHERE  `Interactive_date`>= DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND `Cash`='PAID' ORDER BY `Date` DESC LIMIT 20";

    $Orderid =  self::find_by_sql( $sql,"");
    return $Orderid;
  }

  public static function handleRefund($orderID="", $Amount=""){
    global $database;
    $sql = "UPDATE `Orders` SET `Refund`=`Refund`+'{$Amount}', `Total`= GREATEST(0, `Total`-'{$Amount}')  WHERE `id`='{$orderID}' ";
    return $database->query($sql);

  }

  public static function FindOrderReady() {

    global $database;

    $sql = "SELECT `Cash`  FROM `Orders` WHERE `Status` = 'Ready' AND `Cash` = 'UNPAID' ";
     $OrderReadyCount =   $database->query($sql);
     //$result = $database->query($sql);

     //error_log(print_r($OrderReadyCount->num_rows,true));
     return $OrderReadyCount->num_rows;
   }


   public static function soldDishes () {
    global $database;

    $SideDishes = "SELECT * FROM `SideDishes`";
    $SideDishesRes= $database->query($SideDishes);

    $SideDishesArray=[];
 
    while ($row = mysqli_fetch_array( $SideDishesRes , MYSQLI_ASSOC)) {
  
        $SideDishesArray[$row["Name"]] = $row["Served"];
 
      
    
    }


    $MenuDishes = "SELECT * FROM `MenuDishes`";
    $MenuDishesRes=  $database->query($MenuDishes);

    $MenuDishesArr=[];

     while ($row = mysqli_fetch_array( $MenuDishesRes , MYSQLI_ASSOC)) {
 
        $MenuDishesArr [$row["Name"]] = $row["Served"];
    
    
     }
    
    $report =(array_merge($SideDishesArray,$MenuDishesArr));

    return  [
      "Keys"=> array_keys($report),
      "Values" =>  array_values($report),
      "Sum" => array_sum(array_values($report))

   ];


     
   }


   public static function CashBreakDown_Staff ($PassedDate="", $StaffID="") {
    global $database;

    $BreakDown =[];

    $sql = "SELECT * FROM `Orders`  WHERE `Date` LIKE '{$PassedDate}%' AND `APEX_Staff_ID`='{$StaffID}' AND `Cash`='PAID'";

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

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

    while ($row = mysqli_fetch_array( $Orders , MYSQLI_ASSOC)) {

      $PayMethod = $row["Payment_Method"] ;

      if (array_key_exists(  $PayMethod, $BreakDown)) {
      // error_log(print_r("does exsist"  ,true));
       $BreakDown[$PayMethod]= number_format((float)$BreakDown[$PayMethod ]+$row["Total"] , 2, '.', '');


      } else {
      // error_log(print_r("does not exsist"  ,true));

       $BreakDown[$PayMethod ]=$row["Total"] ;
      }




    }

           ///showing category
      //    error_log(print_r("Final data"  ,true));
      // error_log(print_r( $BreakDown   ,true));

      return  [
        "Keys"=> array_keys($BreakDown),
        "Values" =>  array_values($BreakDown),
        "Sum" => array_sum(array_values($BreakDown))

     ];

   }



   public static function CashBreakDown ($PassedDate="") {
    global $database;

    $BreakDown =[];

    $sql = "SELECT * FROM `Orders`  WHERE `Date` LIKE '{$PassedDate}%' AND `Cash` = 'PAID' ";

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

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

    while ($row = mysqli_fetch_array( $Orders , MYSQLI_ASSOC)) {

      $PayMethod = $row["Payment_Method"] ;

      if (array_key_exists(  $PayMethod, $BreakDown)) {
      // error_log(print_r("does exsist"  ,true));
       $BreakDown[$PayMethod]= number_format((float)$BreakDown[$PayMethod ]+$row["Total"] , 2, '.', '');


      } else {
      // error_log(print_r("does not exsist"  ,true));

       $BreakDown[$PayMethod ]=$row["Total"] ;
      }




    }

           ///showing category
      //    error_log(print_r("Final data"  ,true));
      // error_log(print_r( $BreakDown   ,true));

      return  [
        "Keys"=> array_keys($BreakDown),
        "Values" =>  array_values($BreakDown),
        "Sum" => array_sum(array_values($BreakDown))

     ];

   }


   public static function GetTotalSales ($PassedDate="") {
    global $database;

    //$today = Date("Y-m-d");

    //error_log(print_r( $today ,true));
    $sql = "SELECT   SUM(`Total`) FROM `Orders` WHERE `Date` LIKE '".$PassedDate."%'  AND `Cash` ='PAID'";
    error_log(print_r( $sql ,true));
    // error_log(print_r("TOTALLLLLL ORDER",true));
    // error_log(print_r(mysqli_fetch_all($database->query($sql),MYSQLI_ASSOC)[0]["SUM(`Total`)"],true));
    //mysqli_fetch_all($database->query($sql),MYSQLI_ASSOC);
    return mysqli_fetch_all($database->query($sql),MYSQLI_ASSOC)[0]["SUM(`Total`)"];

   }



  


   public static function MonthtlyProgress ( ) {
     global $database;

    $ProgressData = [];

     //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` > DATE_SUB(NOW(),Interval 12 month) AND `Cash`='PAID' GROUP BY  MONTH(`Date`) ORDER BY `Date` ASC";
     $dataBaseResult = $database->query($sql);

     while ($row = mysqli_fetch_array( $dataBaseResult , MYSQLI_ASSOC)) {


      $Month=  date("M-y", strtotime($row['Date']))  ;

      $ProgressData [$Month] = 0;

      $dataPasseed = $row['Date'];

      $MonthOrder = "SELECT `Total` FROM `Orders` WHERE YEAR(`Date`) = YEAR('{$dataPasseed}') AND MONTH (`Date`)= MONTH('{$dataPasseed}' )";
      error_log(print_r(  $MonthOrder ,true));

      $getMonthOrder = $database->query($MonthOrder);

       while ($OrterTotal = mysqli_fetch_array( $getMonthOrder, MYSQLI_NUM)) {
          // error_log(print_r( $OrterTotal[0],true));
          $ProgressData [$Month] =  number_format((float)$ProgressData[$Month] + $OrterTotal[0]  , 2, '.', '');
        }

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


     }

     return [
      "Keys"=> array_keys($ProgressData),
      "Values" =>  array_values($ProgressData),
      "Sum" => array_sum(array_values($ProgressData))

   ];



   }


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

    $sql = "SELECT `Date` FROM `Orders`  WHERE `Date` LIKE '{$datePassed}%' ";


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

    return  $dataBaseResult->num_rows;

   }

  //  public static function StaffTotalSells ($datePassed="", $StaffID="") {
  //   global $database;
  //   $totalOrders=0;
  //   $ChartData =[];
  //   $CatTotals =[];
  //   $Gross_Total=0;
  //   $Discount_Given=["Qty"=>0, "Total"=>0];

  //   $staffName =Staff::getFullName ($StaffID);
  //   $sql = "SELECT `id`,`Discount` FROM `Orders`  WHERE `Date` LIKE '{$datePassed}%' AND `APEX_Staff_ID`='{$StaffID}' AND `Cash`='PAID' ";


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

  //   while ($row = mysqli_fetch_array( $dataBaseResult , MYSQLI_ASSOC)) {
  //    // error_log(print_r(  $row['id'] ,true));
  //    $totalOrders++;
  //     $Order_id=$row['id'] ;
  //    // $Discount= ;

  //     if ($row['Discount'] >0) {
  //       //$Discount_Given=["Qty"=>+1, "Total"=>""];
  //       $Discount_Given["Qty"]=$Discount_Given["Qty"]+1;
  //       $Discount_Given["Total"]= number_format((float)($Discount_Given["Total"]+$row['Discount']), 2, '.', '') ;
  //     }

  //     $OrderDishInfo = "SELECT `ItemType`,`ItemType_id`,`Qty`,`Price` FROM `OrderDishInfo` WHERE `Orders_ID`='{$Order_id}' ";

  //     //now we loop based on OrderId
  //     $OrderDishInfoResult = $database->query($OrderDishInfo);

  //      while ($row = mysqli_fetch_array( $OrderDishInfoResult , MYSQLI_ASSOC)) {
       
  //       //$OrderDishInfo = "SELECT `ItemType`,`ItemType_id` FROM `OrderDishInfo` WHERE `Orders_ID`='{$Order_id}' AND `Dish_Status` !='IN QUEUE' OR `Dish_Status` !='DECLINED' ";

  //        $type =  $row['ItemType'] == "Menu_Dish" || $row['ItemType'] == "Menu_Dishes" ? 'MenuDishes':'SideDishes' ;
  //        $typeId =  $row['ItemType_id'] ;
  //        $Dish_Qty = $row['Qty'];
  //        $CategoryPrice = $row["Price"] ;

  //        $dynamicSQL = "SELECT `Category` FROM `{$type}` WHERE `id`='{$typeId}' ";

  //        //now finding
  //        $Category = $database->query($dynamicSQL);

  //        $Categoryrow = $Category->fetch_array(MYSQLI_ASSOC);

  //        ///showing category
  //       // error_log(print_r( $Categoryrow["Category"]  ,true));
  //        $CategoryValue = $Categoryrow["Category"] ;
  //        //$CategoryPrice = $Categoryrow["Price"] ;

  //        $Gross_Total = number_format((float)($Gross_Total +($Dish_Qty*$CategoryPrice )), 2, '.', '') ;


  //        if (array_key_exists(  $CategoryValue , $ChartData)) {
  //        // error_log(print_r("does exsist"  ,true));
  //         $ChartData[$CategoryValue ]= $ChartData[$CategoryValue ]+1 ;

  //         $CatTotals [$CategoryValue] =["Category"=>$CategoryValue, "Qty"=>$CatTotals [$CategoryValue] ["Qty"]+1, "Total"=> number_format((float)($CatTotals [$CategoryValue] ["Total"]+($Dish_Qty*$CategoryPrice )), 2, '.', '')  ];
  //         //$Gross_Total = number_format((float)($CatTotals [$CategoryValue] ["Total"]+($Dish_Qty*$CategoryPrice )), 2, '.', '') ;

  //        } else {
  //        // error_log(print_r("does not exsist"  ,true));
  //         $ChartData[$CategoryValue ]=1;
  //         $CatTotals [$CategoryValue] = ["Category"=>$CategoryValue, "Qty"=>1, "Total"=>number_format((float)(($Dish_Qty*$CategoryPrice )), 2, '.', '')  ];
  //         //$Gross_Total = number_format((float)(($Dish_Qty*$CategoryPrice )), 2, '.', '');
  //        }

  //      }

  // }


  //        ///showing category
  //       //  error_log(print_r("Final data"  ,true));
  //       //  error_log(print_r( $ChartData   ,true));
  //        return   [
  //          "StaffName" =>$staffName, 
  //           "Keys"=> array_keys($ChartData),
  //           "Values" =>  array_values($ChartData),
  //           "Sum" => array_sum(array_values($ChartData)),
  //           "total_Orders"=>  $totalOrders, 
  //           "RawData"=> $ChartData,
  //           "CatTotals" =>  array_values($CatTotals),
  //           "CatTotals_Key" =>  array_keys($CatTotals),
  //           "Gross_Total"=> $Gross_Total,
  //           "Staff_Sales_Graph"=> self::CashBreakDown_Staff ($datePassed, $StaffID), 
  //           "Discount_Given"=> array_values($Discount_Given),
  //           "Net_Total_Item_Sold"=>number_format((float)($Gross_Total-$Discount_Given['Total'] ), 2, '.', '') 
  //        ];

     
  //  }

  

   public static function StaffCatSells ($datePassed="", $StaffID="") {
    global $database;
    $totalOrders=0;
    $ChartData =[];
    $paymentMethod =[];
    $paymentMethod_Chart =[];
    $CatTotals =[];
    $Gross_Total=0;
    $Discount_Given=["Qty"=>0, "Total"=>0];
    $CC_Cheque_Tips = 0;
    $CASH_SALES_INCL_SERV_CHAR=0;
    $CASH_SERVICE_CHARGE=0;
 

    $staffName =Staff::getFullName ($StaffID);
    $sql = "SELECT `id`,`Discount`,`Tip`,`Service_Charge`,`Payment_Method`,`Total` FROM `Orders`  WHERE `Date` LIKE '{$datePassed}%' AND `APEX_Staff_ID`='{$StaffID}' AND `Cash`='PAID' ";


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

    while ($row = mysqli_fetch_array( $dataBaseResult , MYSQLI_ASSOC)) {
     // error_log(print_r(  $row['id'] ,true));
     $totalOrders++;
      $Order_id=$row['id'] ;
     // $Discount= ;

      if ($row['Discount'] >0) {
        //$Discount_Given=["Qty"=>+1, "Total"=>""];
        $Discount_Given["Qty"]=$Discount_Given["Qty"]+1;
        $Discount_Given["Total"]= number_format((float)($Discount_Given["Total"]+$row['Discount']), 2, '.', '') ;
      }

  
      

      //gettiny payment Mehthod
      $PaymentMehodType = $row["Payment_Method"] ;
      if ($row['Tip'] >0 && $PaymentMehodType!="Cash" ) {
        $CC_Cheque_Tips= number_format((float)($CC_Cheque_Tips+$row['Tip']), 2, '.', '')  ;
      }

         //$CategoryPrice = $Categoryrow["Price"] ;

         if (array_key_exists($PaymentMehodType , $PaymentMethod)) {
         // error_log(print_r("does exsist"  ,true));

          $paymentMethod_Chart[$PaymentMehodType ]= $paymentMethod_Chart[$PaymentMehodType ]+ $row['Total']  ;

          //$PaymentMethod[$PaymentMehodType ] =["Method"=>$PaymentMehodType,"Total"=> number_format((float)($paymentMethod_Chart [$PaymentMehodType] ["Total"]+($row['Total'])), 2, '.', '')  ];

          $PaymentMethod [$PaymentMehodType] =["Method"=>$PaymentMehodType, "Qty"=>$PaymentMethod [$PaymentMehodType]["Qty"]+1, "Total"=> number_format((float)($PaymentMethod [$PaymentMehodType] ["Total"]+($row['Total'])), 2, '.', '')  ];
          //$Gross_Total = number_format((float)($CatTotals [$CategoryValue] ["Total"]+($Dish_Qty*$CategoryPrice )), 2, '.', '') ;

          if ($PaymentMehodType=="Cash") {
            $CASH_SALES_INCL_SERV_CHAR =  number_format((float)($CASH_SALES_INCL_SERV_CHAR + $row["Service_Charge"] +$row['Total']), 2, '.', '');
            $CASH_SERVICE_CHARGE =number_format((float)($row["Service_Charge"]+$CASH_SERVICE_CHARGE), 2, '.', '');
          }else{
            // $CC_DB_CHEQUE_TIPS=number_format((float)( $CC_DB_CHEQUE_TIPS+$row["Tip"]), 2, '.', '');
          }



         } else {
         // error_log(print_r("does not exsist"  ,true));
          //$PaymentMethod [$PaymentMehodType ]=1;
          $paymentMethod_Chart[$PaymentMehodType ] = $row['Total'] ;
            if ($PaymentMehodType=="Cash") {
              $CASH_SALES_INCL_SERV_CHAR =number_format((float)($row["Service_Charge"] +$row['Total']), 2, '.', '');
              $CASH_SERVICE_CHARGE =number_format((float)($row["Service_Charge"]), 2, '.', '');
            }else{
              // $CC_DB_CHEQUE_TIPS=number_format((float)($row["Tip"]), 2, '.', '');
            }

          $PaymentMethod [$PaymentMehodType] =["Method"=>$PaymentMehodType, "Qty"=>1, "Total"=> $row['Total']];
         // $CatTotals [$CategoryValue] = ["Category"=>$CategoryValue, "Qty"=>1, "Total"=>number_format((float)(($Dish_Qty*$CategoryPrice )), 2, '.', '')  ];
          //$Gross_Total = number_format((float)(($Dish_Qty*$CategoryPrice )), 2, '.', '');
         }


      $OrderDishInfo = "SELECT `ItemType`,`ItemType_id`,`Qty`,`Price` FROM `OrderDishInfo` WHERE `Orders_ID`='{$Order_id}' ";

      //now we loop based on OrderId
      $OrderDishInfoResult = $database->query($OrderDishInfo);

       while ($row = mysqli_fetch_array( $OrderDishInfoResult , MYSQLI_ASSOC)) {
       
        //$OrderDishInfo = "SELECT `ItemType`,`ItemType_id` FROM `OrderDishInfo` WHERE `Orders_ID`='{$Order_id}' AND `Dish_Status` !='IN QUEUE' OR `Dish_Status` !='DECLINED' ";

         $type =  $row['ItemType'] == "Menu_Dish" || $row['ItemType'] == "Menu_Dishes" ? 'MenuDishes':'SideDishes' ;
         $typeId =  $row['ItemType_id'] ;
         $Dish_Qty = $row['Qty'];
         $CategoryPrice = $row["Price"] ;

         $dynamicSQL = "SELECT `Category` FROM `{$type}` WHERE `id`='{$typeId}' ";

        


         //now finding
         $Category = $database->query($dynamicSQL);

         $Categoryrow = $Category->fetch_array(MYSQLI_ASSOC);

         ///showing category
        // error_log(print_r( $Categoryrow["Category"]  ,true));
         $CategoryValue = $Categoryrow["Category"] ;
         //$CategoryPrice = $Categoryrow["Price"] ;

         $Gross_Total = number_format((float)($Gross_Total +($Dish_Qty*$CategoryPrice )), 2, '.', '') ;


         if (array_key_exists(  $CategoryValue , $ChartData)) {
         // error_log(print_r("does exsist"  ,true));
          $ChartData[$CategoryValue ]= $ChartData[$CategoryValue ]+1 ;

          $CatTotals [$CategoryValue] =["Category"=>$CategoryValue, "Qty"=>$CatTotals [$CategoryValue] ["Qty"]+1, "Total"=> number_format((float)($CatTotals [$CategoryValue] ["Total"]+($Dish_Qty*$CategoryPrice )), 2, '.', '')  ];
          //$Gross_Total = number_format((float)($CatTotals [$CategoryValue] ["Total"]+($Dish_Qty*$CategoryPrice )), 2, '.', '') ;

         } else {
         // error_log(print_r("does not exsist"  ,true));
          $ChartData[$CategoryValue ]=1;
          $CatTotals [$CategoryValue] = ["Category"=>$CategoryValue, "Qty"=>1, "Total"=>number_format((float)(($Dish_Qty*$CategoryPrice )), 2, '.', '')  ];
          //$Gross_Total = number_format((float)(($Dish_Qty*$CategoryPrice )), 2, '.', '');
         }

       }

  }

  $DailyFloat =Staff::Get_DAILY_FLOAT($StaffID);


         ///showing category
        //  error_log(print_r("Final data"  ,true));
        //  error_log(print_r( $ChartData   ,true));
         return   [
           "StaffName" =>$staffName, 
            "Keys"=> array_keys($ChartData),
            "Values" =>  array_values($ChartData),
            "Sum" => array_sum(array_values($ChartData)),
            "total_Orders"=>  $totalOrders, 
            "RawData"=> $ChartData,
            "CatTotals" =>  array_values($CatTotals),
            "CatTotals_Key" =>  array_keys($CatTotals),
            "Gross_Total"=> $Gross_Total,
            "Discount_Given"=> array_values($Discount_Given),
            "Net_Total_Item_Sold"=>number_format((float)($Gross_Total-$Discount_Given['Total'] ), 2, '.', '') ,
            "TOTAL_SALES_GRAPH_DATA"=> self::CashBreakDown_Staff ($datePassed, $StaffID), 
            "CC_Cheque_Tips"=> $CC_Cheque_Tips,
            "PAYMENT_METHOD_SALES"=> $PaymentMethod,
            "PAYMENT_METHOD_SALES_KEYS_Only"=> array_keys($PaymentMethod),
            "PAYMENT_METHOD_SALES_KEYS"=> array_keys($paymentMethod_Chart),
            "PAYMENT_METHOD_SALES_VALUES"=> array_values($paymentMethod_Chart),
            "GROSS_TOTAL_SALES" => array_sum(array_values($paymentMethod_Chart)),
            "DAILY_FLOAT"=> $DailyFloat,
            "CASH_SALES_INCL_SERV_CHAR"=> $CASH_SALES_INCL_SERV_CHAR,
            "CASH_SERVICE_CHARGE"=> $CASH_SERVICE_CHARGE,
            "CASH_TO_HAND_IN_EXC_FLOAT"=> $CASH_SALES_INCL_SERV_CHAR,
            "CASH_TO_HAND_IN_INC_FLOAT"=> ($DailyFloat+$CASH_SALES_INCL_SERV_CHAR) 
            
         ];

   }

   public static function SubtractCash_TO_HAND ( $num_A="", $num_B=""){
    if ( $num_A > $num_B) {
       return number_format((float)(($num_A-$num_B) ), 2, '.', '') ;
    } else {
      return number_format((float)(($num_B-$num_A ) ), 2, '.', '') ;
    }
   }



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

    $ChartData =[];

   // error_log(print_r( "inside doughnutChartData" ,true));

    $sql = "SELECT `id` FROM `Orders`  WHERE `Date` LIKE '{$datePassed}%' ";


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

    while ($row = mysqli_fetch_array( $dataBaseResult , MYSQLI_ASSOC)) {
     // error_log(print_r(  $row['id'] ,true));

      $Order_id=$row['id'] ;

      $OrderDishInfo = "SELECT `ItemType`,`ItemType_id` FROM `OrderDishInfo` WHERE `Orders_ID`='{$Order_id}' ";

      //now we loop based on OrderId
      $OrderDishInfoResult = $database->query($OrderDishInfo);

       while ($row = mysqli_fetch_array( $OrderDishInfoResult , MYSQLI_ASSOC)) {

        $OrderDishInfo = "SELECT `ItemType`,`ItemType_id` FROM `OrderDishInfo` WHERE `Orders_ID`='{$Order_id}' AND `Dish_Status` !='IN QUEUE' OR `Dish_Status` !='DECLINED' ";

         $type =  $row['ItemType'] == "Menu_Dish" || $row['ItemType'] == "Menu_Dishes" ? 'MenuDishes':'SideDishes' ;
         $typeId =  $row['ItemType_id'] ;

         $dynamicSQL = "SELECT `Category` FROM `{$type}` WHERE `id`='{$typeId}' ";


         //now finding
         $Category = $database->query($dynamicSQL);

         $Categoryrow = $Category->fetch_array(MYSQLI_ASSOC);

         ///showing category
        // error_log(print_r( $Categoryrow["Category"]  ,true));
         $CategoryValue = $Categoryrow["Category"] ;

         if (array_key_exists(  $CategoryValue , $ChartData)) {
         // error_log(print_r("does exsist"  ,true));
          $ChartData[$CategoryValue ]= $ChartData[$CategoryValue ]+1 ;

         } else {
         // error_log(print_r("does not exsist"  ,true));
          $ChartData[$CategoryValue ]=1;
         }

       }

  }


         ///showing category
        //  error_log(print_r("Final data"  ,true));
        //  error_log(print_r( $ChartData   ,true));
         return   [
            "Keys"=> array_keys($ChartData),
            "Values" =>  array_values($ChartData),
            "Sum" => array_sum(array_values($ChartData))

         ];

   }


   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 "";
    }
  }





}

?>