<?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 Customer extends DatabaseObject {
	
  protected static $table_name="BVIS_User";
  
  //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 ( "OneSignal_id", "Serial","DeviceID","OneSignal");

	// 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 OpenQueue ($Provider_ID="" ){

    //finding cutomer/provider
    $provider = self::find_by_id($Provider_ID);

    $Starting_Time = new DateTime($provider->Starting_Time);

    $Ending_Time = new DateTime($provider->Ending_Time);

    $now = new DateTime();
    if (strtotime($now->date)  >= strtotime($Starting_Time->date) && strtotime($now->date)  <=  strtotime($Ending_Time->date)) {
      return true; 

    }else {
      return false;
    }


  }

  public static function GetOneSignal ($customer_ID="") {
    global $database;
    $sql = "SELECT `OneSignal_id` FROM `BVIS_User` WHERE `id`='{$customer_ID}' LIMIT 1";
    $result = $database->query($sql);
    $oneSignal_id = mysqli_fetch_assoc($result);
    return  $oneSignal_id ['OneSignal_id'];
  }


  public static function GetAvatar ($customer_ID) {
    $user =self::find_by_id($customer_ID );
    return $user->Avatar;

  }

  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 GetCustomerPrivilage ($staffid) {
    $user =self::find_by_id($staffid );
    return $user->Privilege ;
  }

  public static function GetCustomerEmail  ($staffid="", $source="") {

    if ( strtoupper ($source) == "LOCAL") {
      return LocalQueuer::GetEmail ($staffid);
      
      # code...
    } else {
     // $sql = 'SELECT * FROM `BVIS_User` WHERE `id` ="4"';
     $user =self::find_by_id($staffid );
  
      //Full_Name
      if (  $user && $user->Email  !="undefined" ) {
        return $user->Email ;
      } else {
      return "N/A";
      }

    }
    
    
  


  }



  public static function UnitRateReport( $busID="") {

    $sql = "SELECT * FROM `BVIS_User` WHERE `Business_ID`='{$busID}'";

    $units = self::find_by_sql ($sql, "ReportRate");


    return   $units ;
    
  }


  



  public static function GetCustomerPhone ($staffid="", $source="") {

    if ( strtoupper ($source) == "LOCAL") {
      return LocalQueuer::GetPhone($staffid);
      
      # code...
    } else {
     // $sql = 'SELECT * FROM `BVIS_User` WHERE `id` ="4"';
     $user =self::find_by_id($staffid );
  
      //Full_Name
      if (  $user && $user->Phone !="undefined" ) {
        return $user->Phone;
      } else {
      return "N/A";
      }

    }
    
    
  


  }




  public static function GetCustomerName ($staffid="", $source="") {

    if ( strtoupper ($source)== "LOCAL" ) {
      return LocalQueuer::GetName($staffid);
      
      # code...
    } else {
     // $sql = 'SELECT * FROM `BVIS_User` WHERE `id` ="4"';
     $user =self::find_by_id($staffid );
  
      //Full_Name
      if (  $user) {
        return $user->Full_Name;
      } else {
      return "N/A";
      }

    }
    
    
  


  }


  public static function showCustomerName ($staffid="", $source="") {

    if ( strtoupper ($source)== "LOCAL" ) {
      return LocalQueuer::GetName($staffid);
      
      # code...
    } else {
     // $sql = 'SELECT * FROM `BVIS_User` WHERE `id` ="4"';
     $user =self::find_by_id($staffid );
  
      //Full_Name
      if (  $user) {
        echo($user->Full_Name) ;
      } else {
        echo( "N/A");
      }

    }
    
    
  


  }


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

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

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

    return  $dataBaseResult->num_rows;
  }

  public static function UpdateOneSignal_ID ($OneSignal_Data="") {
   error_log( print_R("UpdateOneSignal_ID showing",true) );
   error_log( print_R($OneSignal_Data ,true) );
    global $database;
    $oneSignalID_Passed = $OneSignal_Data["OneSignal_id"];
    $pushToken = $OneSignal_Data["pushToken"];
    $CustomerId = $OneSignal_Data["id"];

    $sql = "UPDATE `BVIS_User` SET `OneSignal_id`='".$oneSignalID_Passed."',`OneSignal`='".$pushToken."' WHERE `id`='".$CustomerId."'";
   
    error_log( print_R($sql ,true) );

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

  }


public static function GetID_with_SignalID($signal="", $signalID=""){
  global $database;

 // $sql= "SELECT `id` FROM `BVIS_User` WHERE (`OneSignal`!='' AND `OneSignal_id`!='') AND  ( `OneSignal_id`='".$signalID."' OR `OneSignal`='".$signal."' ) LIMIT 1";

 $sql= "SELECT `id` FROM `BVIS_User` WHERE (`OneSignal`!='' AND `OneSignal_id`!='' AND `OneSignal`!='undefined' AND `OneSignal_id`!='undefined') AND  ( `OneSignal_id`='".$signalID."' OR `OneSignal`='".$signal."' ) ORDER BY `id` DESC LIMIT 1";

  error_log( print_R(  "sqleeeeeeee ",true) );
  error_log( print_R( $sql,true) );
  $idFound = mysqli_fetch_array($database->query($sql),MYSQLI_ASSOC);
  error_log( print_R(  "GetID_with_SignalID Will return this ",true) );
  error_log( print_R( $idFound ,true) );
  if ($idFound) {
    return $idFound["id"];
  } else {
   return "";
  }
  
 

}

  public static function addPoints($id="", $amount="" ) {
    global $database;
     $points = floor ($amount/2);
     $sql = "UPDATE `BVIS_User` SET `Points`=`Points`+$points WHERE `id`='".$id."'";
     return $database->query($sql);

  }


  public static function AddCredit ($id="", $amount="") {
    global $database;
    $sql = "UPDATE `BVIS_User` SET `Credits`=`Credits`+'{$amount}' WHERE `id`='{$id}' AND `Accredited`='Yes' AND `Blocked`='No'";
   // return $database->query($sql);

    //we need to alert user and
    //update server

    if ($database->query($sql)) {

      //inform user
      //this one can be done locally
      if (SERVER_MODE=="LOCAL") {
       $updatedCustomer = self::find_by_id($id);
      
        //updatting SERVER DB
        $post = [
          'action' => 'updateCustomer_Credit',
          'CustomerUdating'=>true,
          'updatedCustomer'=>  $updatedCustomer
         ];
    
           ONLINE_SERVER_MARKER ($post);

           $msg ="Your account at ".BUSINESS_NAME." has been charged $".number_format($amount);

           $CustomerData =array(
             "token"=>$updatedCustomer->OneSignal_id,
             "Msg"=>$msg,
             'header'=>'ACCOUNT CHARGED',
             "data" => array(
              "route" => "Order"
          ),
             'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
         );
     
         OneSignalsendMessage($CustomerData);
           
      }
    }  
  }



  private function  Find_OneSignalID($OneSignalID="") {
     global $database;
    $sql = "SELECT `OneSignal_id` FROM `BVIS_User` WHERE `OneSignal_id`='".$OneSignalID."'";
     $idFound =   $database->query($sql);
     //$result = $database->query($sql);
     //error_log( print_R($idFound->num_rows . " Find_OneSignalID function",true) );
     //error_log(print_r($OrderReadyCount->num_rows,true));
     return $idFound->num_rows;
   }

   public static function  Find_By_OneSignalID($OneSignalID="") {
    $result_array = self::find_by_sql("SELECT * FROM `BVIS_User` WHERE `OneSignal_id`='{$OneSignalID}'","");
    return !empty($result_array) ? array_shift($result_array) : false;
    //$result = $database->query($sql);
  
  }


 

  public function verifyCustomer() {
    // A new record won't have an id yet.
     return  self::Find_OneSignalID ($this->OneSignal_id)   >= 1 ? $this->update() : $this->create();
  }

  public static function FindRegistered () {

    $customer = "SELECT * FROM `BVIS_User` WHERE `Sent_to_POS`='No' " ;

   // $customer = "SELECT * FROM `Customer` WHERE `Sent_to_POS`='No' OR DATE( `Interactive_date` )>= DATE_SUB('{$POS_OLDEST}', INTERVAL 20 SECOND)" ;

    return self::find_by_sql($customer,"");
    
  }

  public static function Find_User_ID ($OneSignal_id="") {
    global $database;
    $sql = "SELECT `id` FROM `BVIS_User` WHERE `OneSignal_id`='".$OneSignal_id."' LIMIT 1";
    
   $idFound = mysqli_fetch_array($database->query($sql),MYSQLI_ASSOC);
    return $idFound["id"];
  }


  public function update() {
    global $database;
      // Don't forget your SQL syntax and good habits:
      // - UPDATE table SET key='value', key='value' WHERE condition
      // - single-quotes around all values
      // - escape all values to prevent SQL injection

      //we unset id to avoid updating with empty value
      //need to fix this to challange with id blank

      error_log( print_R( "UPDATING BY CUTOMER CLASS",true) );

      //unset($this->id);
      $attributes = $this->sanitized_attributes();
      $attribute_pairs = array();
      
      foreach($attributes as $key => $value) {
        $attribute_pairs[] = "{$key}='{$value}'";
      }
     error_log( print_R( $attribute_pairs,true) );
     //echo "see the ide here >>>". join(", ", $attribute_pairs);
    // error_log( print_R($attribute_pairs,FALSE) );\

    //we should stop update if we dont  OneSignal or OneSignal_id

    //App should always give us and OneSignal on registration
    

      $sql = "UPDATE " .static::$table_name. " SET ";
      $sql .= join(", ", $attribute_pairs);
      $sql .= " WHERE `id` ='{$this->id}' AND  (`OneSignal` ='{$this->OneSignal}' AND `OneSignal_id`='{$this->OneSignal_id}') LIMIT 1";
      
      //echo $sql;

      error_log( print_R($sql,true) );
    $database->query($sql);
    //we need to set id.
     $this->id = self::Find_User_ID ($this->OneSignal_id);

    return ($database->affected_rows() == 1) ? true : false;
  }

  public static function Accredit ($CustomerId="", $value="") {
    global $database;

    $sql = "UPDATE `BVIS_User` SET `Accredited`='{$value}' WHERE `id`= '{$CustomerId}'";

    if ( $database->query($sql)) {
      return self::find_all_Admin("Customer");

    } else {
        return false;
    }
    


  }


  public static function  RegisterPayment ($CustomerId="", $Amount="") {
    global $database;

    $sql = "UPDATE `BVIS_User` SET `Credits`=`Credits`-'{$Amount}' WHERE `id`= '{$CustomerId}'";

    if ( $database->query($sql)) {
         //we need to inform user that payment was accepted
         if(SERVER_MODE=="ONLINE"){
          setlocale(LC_MONETARY,"en_US");
          //money_format("We earnestly acknowledge your payment of %i", $Amount)
        $msg =  money_format("We earnestly acknowledge your payment of %i", $Amount)." Thank You!";

        $CustomerData =array(
           "token"=>Customer::GetCustomerToken($CustomerId),
           "Msg"=>$msg,
           'header'=>'PAYMENT RECEIVED',
           'template'=>'f5e2d1d3-27d3-432d-8990-2443eb06240b', //reservation template
        );
    
        OneSignalsendMessage($CustomerData);
          } else {
            //since aer are local, wee
            //need to tell server to update client
            $updatedCustomer = Customer::find_by_id($CustomerId);
               $post = [
                   'action' => 'updateCustomer_Credit',
                   'ConfirmPayment'=>true,
                   'Amount'=>$Amount,
                   'updatedCustomer'=>  $updatedCustomer
                  ];
               ONLINE_SERVER_MARKER ($post);
          }

           

      return self::find_all_Admin("Customer");

    } else {
        return false;
    }

  }


  public static function SetBlock ($CustomerId="", $value="") {

    global $database;

    $sql = "UPDATE `BVIS_User` SET `Blocked`='{$value}' WHERE `id`= '{$CustomerId}'";

    if ( $database->query($sql)) {
      return self::find_all_Admin("Customer");

    } else {
        return false;
    }
    



  }


  public static function GetCustomerToken ($CustomerId) {
    global $database;

    $sql = "SELECT `OneSignal_id` FROM `BVIS_User` WHERE `id` ='{$CustomerId}' " ;

    $OneSignal_id =  mysqli_fetch_assoc( $database->query($sql));

      
    //$customer =self::find_by_id($CustomerId );
    error_log( print_R("getting customer" ,true) );
    error_log( print_R( trim($OneSignal_id["OneSignal_id"]),true) );
   
    
      return trim($OneSignal_id["OneSignal_id"]) ;
  
     
 

  


  }

	

	public static function authenticate($Username="", $Password="") {
    global $database;
    $usernameP = $database->escape_value($Username);
    $passwordP = SHA1($database->escape_value($Password));


    //    $sql  = "SELECT `id`,`First_Name`,`Last_Name`,`Username`,`Privilege`,`Salary` FROM `Staff`";

    $sql  = "SELECT ".self::Columns_Select()." FROM `APEX_Staff` ";
    $sql .= "WHERE `Username` = '{$usernameP}' ";
    $sql .= "AND `Password` = '{$passwordP}' ";
    $sql .= "LIMIT 1";
    //$sql = 'SELECT * FROM `Staff` WHERE `Password`="'.$password.'" AND `Username`="'.$username.'"';
   // error_log(print_r($sql, true));

    $result_array = self::find_by_sql($sql);
   // unset($result_array["Password"]);
    // error_log(print_r($result_array, true));
		return !empty($result_array) ? array_shift($result_array) : false;
	}

}

?>