<?php
// If it's going to need the database, then it's 
// probably smart to require it before we start.
require_once('initializer.php');

class Expenses extends DatabaseObject {
	
  protected static $table_name="Expenses";
  
  //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 ("Password");

	// 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 testGetField () {
    return self::$db_fields;
  }



  public static function MonthtlyProgress_Inventory ($DateToReport="") {
    global $database;

   $ProgressData = [];
   $Operating_Data =[];
   $Labor_Data=[];
   $FOOD_SALES_DATA = [];
   $FOOD_SALES_TOTAL =0;
   $Food_Cost_Percentage	=0;
   $Gross_Profit=0;

   $DAILY_ProgressData = [];
   $DAILY_Operating_Data =[];
   $DAILY_Labor_Data=[];
   $DAILY_FOOD_SALES_DATA = [];
   $DAILY_FOOD_SALES_TOTAL =0;
   $DAILY_Food_Cost_Percentage	=0;
   $DAILY_Gross_Profit=0;


   $YearPassed=  date("Y", strtotime($DateToReport))  ;
   $YearCurrrent=  date("Y")  ;



   if ($YearPassed == $YearCurrrent) {
    $sql = "SELECT `Date_paid`,`Amount_paid`,`Type` FROM `Expenses` WHERE `Date_paid` > DATE_SUB(NOW(),Interval 12 month) ORDER BY `Date_paid` ASC";
   } else {
    $sql = "SELECT `Date_paid`,`Amount_paid`,`Type` FROM `Expenses` WHERE YEAR(`Date_paid`) = {$YearPassed} ORDER BY `Date_paid` ASC";

  }

  // $sql = "SELECT `Date_paid`,`Amount_paid`,`Type` FROM `Expenses` WHERE `Date_paid` > DATE_SUB(NOW(),Interval 12 month) ORDER BY `Date_paid` ASC";

  $dailyReport="SELECT `Date_paid`,`Amount_paid`,`Type` FROM `Expenses` WHERE `Date_paid` LIKE '{$DateToReport}%' ORDER BY `Date_paid` ASC";
  $DailyResult = $database->query($dailyReport);

  ///**  entering DAILY_*/
    while ($row = mysqli_fetch_array( $DailyResult , MYSQLI_ASSOC)) {


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


     //Storing Labor Data
   
      if (isset($DAILY_Labor_Data [$Month]) ) {
        if ($row['Type'] == "Labor") {
          $DAILY_Labor_Data [$Month] =  number_format((float)$DAILY_Labor_Data[$Month]+ $row['Amount_paid'] , 2, '.', '');
        }else{
          $DAILY_Labor_Data [$Month] =   number_format((float)$DAILY_Labor_Data[$Month]+ 0.00, 2, '.', '');
        }
       
  
       }else{
          if ($row['Type'] == "Labor") {
            $DAILY_Labor_Data [$Month] =  number_format((float)$row['Amount_paid'] , 2, '.', '');
          }else{
            $DAILY_Labor_Data [$Month] = 0.00;
          }
  
       }


     //Query the DB FOR Operating Data
       if (isset($DAILY_Operating_Data [$Month]) ) {
       
        if ($row['Type'] == "Operating") {
          $DAILY_Operating_Data [$Month] =  number_format((float)$DAILY_Operating_Data[$Month]+ $row['Amount_paid'] , 2, '.', '');
        }else{
          $DAILY_Operating_Data [$Month] =  number_format((float)$DAILY_Operating_Data[$Month]+ 0.00 , 2, '.', '');
        }
       
       }else{
        if ($row['Type'] == "Operating") {
          $DAILY_Operating_Data [$Month] =  number_format((float)$row['Amount_paid'] , 2, '.', '');
        }else{
          $DAILY_Operating_Data [$Month] = 0.00;
        }

       }

     


    
   //Setting Inventory Data
   if ($row['Type'] == "Inventory") {
    if (isset($DAILY_ProgressData [$Month]) ) {
      $DAILY_ProgressData [$Month] =  number_format((float)$DAILY_ProgressData[$Month]+ $row['Amount_paid'] , 2, '.', '');

     }else{
      $DAILY_ProgressData [$Month] =  number_format((float)$row['Amount_paid'] , 2, '.', '');
       //we loop in the return array or just grap sum and add
       $DAILY_PAID_ORDERS = Orders::CashBreakDown (date("Y-m", strtotime($row['Date_paid']))) ;

       $DAILY_FOOD_SALES_DATA [$Month] =$DAILY_PAID_ORDERS ["Sum"];
       $DAILY_FOOD_SALES_TOTAL= number_format((float)($DAILY_FOOD_SALES_TOTAL+$DAILY_PAID_ORDERS ["Sum"]) , 2, '.', '');
     }

   }


    }
    


    
       $DAILY_TOTAL_COGS =array_sum(array_values($DAILY_ProgressData));

      //getting Food Cost Percentage	
      $Percentage= number_format((float)($DAILY_TOTAL_COGS/$DAILY_FOOD_SALES_TOTAL) );
      $DAILY_Food_Cost_Percentage = $Percentage=="nan" ?   0:$Percentage;

      //getting Gross Profit	
      $DAILY_Gross_Profit =  number_format((float)($DAILY_FOOD_SALES_TOTAL - $DAILY_TOTAL_COGS ) , 2, '.', ''); 

      $DAILY_Operating_Cost = array_sum(array_values($DAILY_Operating_Data));
      $DAILY_Labor_Cost = array_sum(array_values($DAILY_Labor_Data));

      $DAILY_Net_Profit_Loss = $DAILY_Gross_Profit -($DAILY_Labor_Cost+ $DAILY_Operating_Cost);

  



  ///**END OD DAILY REPORT **/////


    //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_paid`,`Amount_paid` FROM `Expenses` WHERE `Date_paid` > DATE_SUB(NOW(),Interval 12 month) AND `Type`='Inventory'  ORDER BY `Date_paid` ASC";
   // $sql = "SELECT `Date_paid`,`Amount_paid` FROM `Expenses` WHERE YEAR(`Date_paid`) = 2019 AND `Type`='Inventory'  ORDER BY `Date_paid` ASC";

    $dataBaseResult = $database->query($sql);
    while ($row = mysqli_fetch_array( $dataBaseResult , MYSQLI_ASSOC)) {


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


     //Storing Labor Data
   
      if (isset($Labor_Data [$Month]) ) {
        if ($row['Type'] == "Labor") {
          $Labor_Data [$Month] =  number_format((float)$Labor_Data[$Month]+ $row['Amount_paid'] , 2, '.', '');
        }else{
          $Labor_Data [$Month] =   number_format((float)$Labor_Data[$Month]+ 0.00, 2, '.', '');
        }
       
  
       }else{
          if ($row['Type'] == "Labor") {
            $Labor_Data [$Month] =  number_format((float)$row['Amount_paid'] , 2, '.', '');
          }else{
            $Labor_Data [$Month] = 0.00;
          }
          
         //we loop in the return array or just grap sum and add
         //$PAID_ORDERS = Orders::CashBreakDown (date("Y-m", strtotime($row['Date_paid']))) ;
       }

 

    

     //Query the DB FOR Operating Data
       if (isset($Operating_Data [$Month]) ) {
       
        if ($row['Type'] == "Operating") {
          $Operating_Data [$Month] =  number_format((float)$Operating_Data[$Month]+ $row['Amount_paid'] , 2, '.', '');
        }else{
          $Operating_Data [$Month] =  number_format((float)$Operating_Data[$Month]+ 0.00 , 2, '.', '');
        }
       
       }else{
        if ($row['Type'] == "Operating") {
          $Operating_Data [$Month] =  number_format((float)$row['Amount_paid'] , 2, '.', '');
        }else{
          $Operating_Data [$Month] = 0.00;
        }
       
       
         //we loop in the return array or just grap sum and add
         //$PAID_ORDERS = Orders::CashBreakDown (date("Y-m", strtotime($row['Date_paid']))) ;
       }

     


    
   //Setting Inventory Data
   if ($row['Type'] == "Inventory") {
    if (isset($ProgressData [$Month]) ) {
      $ProgressData [$Month] =  number_format((float)$ProgressData[$Month]+ $row['Amount_paid'] , 2, '.', '');

     }else{
      $ProgressData [$Month] =  number_format((float)$row['Amount_paid'] , 2, '.', '');
       //we loop in the return array or just grap sum and add
       $PAID_ORDERS = Orders::CashBreakDown (date("Y-m", strtotime($row['Date_paid']))) ;

       $FOOD_SALES_DATA [$Month] =$PAID_ORDERS ["Sum"];
       $FOOD_SALES_TOTAL= number_format((float)($FOOD_SALES_TOTAL+$PAID_ORDERS ["Sum"]) , 2, '.', '');
     }

   }

     
    
    // $dataPasseed = $row['Date_paid'];

  
    

    //  $MonthOrder = "SELECT `Amount_paid` FROM `Expenses` WHERE YEAR(`Date_paid`) = YEAR('{$dataPasseed}') AND MONTH (`Date_paid`)= MONTH('{$dataPasseed}' ) AND `Type`='Inventory' ";
    //  error_log(print_r(  $MonthOrder ,true));

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

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

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


    }
    


    
       $TOTAL_COGS =array_sum(array_values($ProgressData));

      //getting Food Cost Percentage	
      $PercentageMon = number_format((float)($TOTAL_COGS/$FOOD_SALES_TOTAL) , 2, '.', ''); 
       $Food_Cost_Percentage = $PercentageMon=="nan" ?   0:$PercentageMon;

      //getting Gross Profit	
      $Gross_Profit =  number_format((float)($FOOD_SALES_TOTAL - $TOTAL_COGS ) , 2, '.', ''); 

      $Operating_Cost = array_sum(array_values($Operating_Data));
      $Labor_Cost = array_sum(array_values($Labor_Data));

      $Net_Profit_Loss = $Gross_Profit -($Labor_Cost+ $Operating_Cost);



    return [
      "INVENTORY_DATA"=> [ "Keys"=> array_keys($ProgressData),"Values" => array_values($ProgressData),"Sum" =>array_sum(array_values($ProgressData))],
      "FOOD_SALES_DATA"=> [ "Keys"=> array_keys($FOOD_SALES_DATA),"Values" => array_values($FOOD_SALES_DATA),"Sum" =>array_sum(array_values($FOOD_SALES_DATA))],
      "OPERATING_DATA"=> [ "Keys"=> array_keys($Operating_Data),"Values" => array_values($Operating_Data),"Sum" =>array_sum(array_values($Operating_Data))],
      "LABOR_DATA"=> [ "Keys"=> array_keys($Labor_Data),"Values" => array_values($Labor_Data),"Sum" =>array_sum(array_values($Labor_Data))],
      "TOTAL_COGS"=>  array_sum(array_values($ProgressData)),
      "Food_Cost_Percentage"=> $Food_Cost_Percentage,
      "Gross_Profit"=>  $Gross_Profit,
      "Net_Profit_Loss"=>$Net_Profit_Loss,
      "FOOD_SALES_TOTAL"=>$FOOD_SALES_TOTAL,
      //daily Values
      "DAILY_INVENTORY_DATA"=> [ "Keys"=> array_keys($DAILY_ProgressData),"Values" => array_values($DAILY_ProgressData),"Sum" =>array_sum(array_values($DAILY_ProgressData))],
      "DAILY_FOOD_SALES_DATA"=> [ "Keys"=> array_keys($DAILY_FOOD_SALES_DATA),"Values" => array_values($DAILY_FOOD_SALES_DATA),"Sum" =>array_sum(array_values($DAILY_FOOD_SALES_DATA))],
      "DAILY_OPERATING_DATA"=> [ "Keys"=> array_keys($DAILY_Operating_Data),"Values" => array_values($DAILY_Operating_Data),"Sum" =>array_sum(array_values($DAILY_Operating_Data))],
      "DAILY_LABOR_DATA"=> [ "Keys"=> array_keys($DAILY_Labor_Data),"Values" => array_values($DAILY_Labor_Data),"Sum" =>array_sum(array_values($DAILY_Labor_Data))],
      "DAILY_TOTAL_COGS"=>  array_sum(array_values($DAILY_ProgressData)),
      "DAILY_Food_Cost_Percentage"=> $DAILY_Food_Cost_Percentage,
      "DAILY_Gross_Profit"=>  $DAILY_Gross_Profit,
      "DAILY_Net_Profit_Loss"=>$DAILY_Net_Profit_Loss,
      "DAILY_FOOD_SALES_TOTAL"=>$DAILY_FOOD_SALES_TOTAL,
      //daily Values

   ];

   }




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



}

?>