<?php
class MyAPICore {




  public function checkUserIsLogdedIn() {

    return true;

  }
  public function sendPushNotification($user_id,$data=array(),$dn=array()){
       $db = new Db();
      //sleep(5);
       
    $datarows = $db -> select("SELECT * FROM `users` where id=$user_id limit 1");  
   
    if((int)$datarows[0]['activateNotify']==1){
        
    $id1=$datarows[0]['id'];
  $rows = $db -> select("SELECT * FROM `user_firebaseToken` where user_id=$id1 ORDER BY `id` DESC limit 1 ");

  if(!empty($rows)){
  foreach ($rows as $val) {
  $to= $val['firebaseToken']; 
  $apiKey='AAAA9DP7I44:APA91bGBtk1DJn0IQPv_yDlf17wWvgnbxy9dYFLB5OM8Z4bTUUWwx7-vw07pe9nOcj10XSd7PyaIZNyHLrbyyX7RNRfIbN-ju_1FRkEO87t9NdqIm20HXWR9WwVabqkv44as-NZA-oFS';
  
  $fields=array('to'=>$to,'notification'=>$data,'data'=>$dn);
  
  $headers=array('Authorization:key='.$apiKey,'Content-Type: application/json');
  
  $url='https://fcm.googleapis.com/fcm/send';
  
   $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
	            curl_setopt($ch, CURLOPT_POST, true);
	            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		            // Disabling SSL Certificate support temporarly
	            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($fields));
	            $result = curl_exec($ch);
	            curl_close($ch);
	          
	
	           
  }
    }
   return 1;
    } 
}
public function addNotify($user_id,$title,$body) {

    $db = new Db();
    $date=date("Y-m-d");
    $result = $db -> query("INSERT INTO `notifications` (`user_id`,`title`,`body`,`status`,`date`) VALUES ($user_id, '$title', '$body',0,'$date')");
     return $result;

  }

public function genOrderNum(){
        $num = rand(10000,99999);
        $db = new Db();
        $row =$db -> select("SELECT * FROM `orders` where `order_num`  = '$num'  "); 
        if($row){
        genOrderNum();
        }
        return $num;
 }
  public function changeOrderStatus($order_num,$status,$v) {

    $db = new Db();
    $date= date("Y-m-d");
    $order =$db -> select("SELECT * FROM `orders` where `order_num`  = '$order_num' limit 1  ");
    $user_id=$order[0]['user_id'];
    
    if(!empty($order)){
        
     ////////////update status/////////
      $update_status = $db ->query("UPDATE `orders` SET status=$status  WHERE order_num='$order_num'  order by id DESC limit 1 "); 
      
     //////////////////insert active order///////////////  
     $order_st=$db -> select("SELECT * FROM `order_status` where id=$status limit 1 ");
          $name_ar=$order_st[0]['name_ar'];
     $note_ar='تم تحديث حالة الطلب الى '.$name_ar;
    if($status==0){
     $this ->addOrderActivity($order_num,$user_id,$note_ar,'',$date);   
    }else{
     $this ->addOrderActivity($order_num,$v,$note_ar,'',$date);
    }
    //////////push notifications/////////////
    $cart=json_decode($order[0]['cart']);
    $product_id=$cart[0]->product_id;
    $productdata=$db -> select("SELECT * FROM `products` where id=$product_id limit 1");
    $vendor_id=$productdata[0]['user_id'];
    if($status==0){
        $sub="اضافة طلب";
        $msg="تم اضافة طلب #" .$order_num." حالته مستلم";
    $this -> sendPushNotification($user_id,array("title"=> urldecode($sub),"body"=>urldecode($msg)),array("order_num"=>urldecode($order_num)));  
    $this -> sendPushNotification($vendor_id,array("title"=> urldecode($sub),"body"=>urldecode($msg)),array("order_num"=>urldecode($order_num)));  
    $this -> addNotify($user_id,$sub,$msg) ;
    $this -> addNotify($vendor_id,$sub,$msg) ;    
    }else{
       $sub=" تحديث حالة الطلب # ".$order_num;
      $msg='تم تحديث حالة الطلب الى '.$name_ar;
     $this -> sendPushNotification($user_id,array("title"=> urldecode($sub),"body"=>urldecode($msg)),array("order_num"=>urldecode($order_num)));  
    $this -> sendPushNotification($vendor_id,array("title"=> urldecode($sub),"body"=>urldecode($msg)),array("order_num"=>urldecode($order_num)));  
    $this -> addNotify($user_id,$sub,$msg) ;
    $this -> addNotify($vendor_id,$sub,$msg) ;  
   }
    
    }
    
    
  }
 public function addOrderActivity($order_num,$id,$note_ar,$note_en,$date) {

    $db = new Db();
    $d = date("Y-m-d H:i:s");
    $result = $db ->query("INSERT INTO `order_activity`(`order_num`,`user_id`,`note_ar`,`note_en`,`date`) VALUES ('$order_num',$id,'$note_ar','$note_en','$date')");

   // $result = $db -> query("INSERT INTO `users_account_activity` (`user_id`, `from_id`, `note`,`user_account_id`,`activity_currency_id`,`activity_amount`,`activity_type`,`activity_date`,`status`) VALUES ($user_id, $from_id, '$note',$user_account_id,$activity_currency_id,'$activity_amount','$activity_type','$d',1)");
//  mysqli_insert_id($db->getCon());
    return mysqli_insert_id($db->getCon());

  }
  public function encodeKey($key) {

   if($this -> checkUserIsLogdedIn()== true){
$newKey= $key*2 ;
     return $newKey;
 }
   else {
     return false;
   }

  } // end function

  public function decodeKey($key) {

   if($this -> checkUserIsLogdedIn()== true){
$newKey= $key/2 ;
     return $newKey;
 }
   else {
     return false;
   }

  } // end function
  public function insertNewUserAccount($account_name,$account_c,$user_id,$email) {

    $this->user_logs($email,"insertNewUserAccount-mobail",date("Y-m-d H:i:s"));

    $d = date("Y-m-d H:i:s");


    $account_c = (int) $account_c;
    $account_name = strip_tags($account_name);
    $db = new Db();
    $result = $db -> query("INSERT INTO `users_accounts` (`user_id`, `currency_id`, `account_name`, `balance`, `date`) VALUES ($user_id, $account_c,'$account_name', '0', '$d')");

    return $result;

  }

 public function getEmailByMobile($mobile) {

    $db = new Db();
    $date=date("Y-m-d H:i:s");
    $rows = $db -> select("SELECT * FROM `user_mobile` WHERE `mobile` = '$mobile' AND `status` = 1");

    $user_id = $rows[0]['user_id'];

    $rows = $db -> select("SELECT * FROM `users` WHERE `id` = $user_id ");

    return $rows[0]['email'];

  }
public function getNotyfyByType($user_id,$type,$status) {

     $db = new Db();
     if($status==-1)
     $rows = $db -> select("SELECT * FROM `notify` where `user_id` = $user_id AND `type` = '$type'  ORDER BY `id` DESC LIMIT 50");
     else {
       $rows = $db -> select("SELECT * FROM `notify` where `user_id` = $user_id AND `type` = '$type'  AND `status` = $status ORDER BY `id` DESC LIMIT 50");
     }
     return $rows;


  } 

  
public function checkifvirfyUser($user_id) {

   $db = new Db();
   $rows = $db -> select("SELECT * FROM `account_verify` where `user_id` = $user_id and `status` = 1 ");

   return $rows;


}
public function updateAccountByID($acc_id,$s,$user_id) {

  $db = new Db();
  $result = $db -> query("UPDATE `users_accounts` SET `status`= $s WHERE `user_id` = $user_id and `id` = $acc_id");

  return $result;
}
//
 public function getBillByID($id) {

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `invoices` where `id` = $id ");

     return $rows;


  }
  
 public function getAccountInfo($user_id,$account_id) {

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `users_accounts` where `id` = $account_id  and `user_id`  = $user_id ORDER BY `id` DESC limit 20");

     return $rows;


  }  
  
public function selectAccountByID($acc_id,$s,$user_id) {

  $db = new Db();
  $result = $db -> select("select * from `users_accounts` WHERE `user_id` = $user_id and `id` = $acc_id");

  return $result;
}
  public function insertInvoice($from_user_id,$to_email,$invoice,$amount,$carrancy_id) {

    $db = new Db();
    $date=date("Y-m-d H:i:s");
    $result = $db -> query("INSERT INTO `invoices` (`from_user_id`,`to_user_email`, `invoice`, `total`,`carrancy_id`,`is_paid`,`date`,`status`) VALUES ($from_user_id,'$to_email','$invoice', '$amount',$carrancy_id, 0,'$date',0)");
    $last_id = mysqli_insert_id($db->getCon());

    $rows = $db -> select("SELECT * FROM `users` WHERE `email` = '$to_email' LIMIT 1");

    $note = 'استقبلت مطالبة مالية جديدة برجاء دفعها ';

    $this -> addNotify($rows[0]['id'],'SITE','INV',$last_id,'مطالبة مالية غير مدفوعه',$note,0);

    return $result;

  }
public function getCompanybyId($id) {

     $db = new Db();
     $rows = $db -> select("SELECT  *,(select name from category_servic where category_servic.id=compan_service.category_id ) as category ,
     (select name from users_profile  where users_profile.user_id=compan_service.user_id ) as user ,
     (select 	account_name from users_accounts  where users_accounts.id=compan_service.user_account_id ) as account_name
     FROM `compan_service` where compan_service.id=$id ORDER BY `id` DESC Limit 1");

     return $rows; 
}

  public function getAdminByID($admin_id) {

   if($this -> checkUserIsLogdedIn()== true){

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `admin` WHERE `id` = $admin_id");

     return $rows;


   }
   else {
     return false;
   }

 } // end function
 
public function login($user,$pass) {
//print $pass;
  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `users` WHERE `email` = '$user' AND `password` = '$pass' ORDER BY `id` DESC LIMIT 1");

    return $rows;


  }
  else {
    return false;
  }

 } // end function
public function user_logs($email,$action,$date) {

    $db = new Db();
    $result = $db -> query("INSERT INTO `user_logs` (`email`, `action`, `date`) VALUES ('$email', '$action', '$date')");

    return $result;

  }
 public function getUserProfile($id) {


    $db = new Db();
    $rows = $db -> select("SELECT * from `users_profile` where `user_id`= $id");

    return $rows;


 } // end function
 public function getSystemCarrncyById($id) {

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `system_currencies` WHERE `id` = $id");

     return $rows;


  }
   public function getUserProfileUsingEmail($email) {

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `users_profile` WHERE `re_email` = '$email' ORDER BY `id` DESC");

     return $rows;


  }
  public function getUserInvoicesOut($user_id) {
     $db = new Db();
     $rows = $db -> select("SELECT * FROM `invoices` where  `from_user_id` = $user_id  ORDER BY `id` DESC limit 20");
     return $rows;

  }
  public function getUserInvtsOUTSerche($user_id,$text) {

     $db = new Db();
    
      $rows = $db -> select("SELECT * from (SELECT *,(SELECT name from users_profile where users_profile.user_id=invoices.from_user_id) as name1 FROM `invoices` where  `from_user_id` = $user_id ORDER BY `id` DESC limit 20)
		 as m where 
         m.id LIKE '%$text%' or
         m.name1 LIKE '%$text%' or
         m.invoice LIKE '%$text%' or
         m.total LIKE '%$text%' or
         m.date LIKE '%$text%' 
		 ");
     return $rows;


  }
    public function getNotyfyByTypeSerche($user_id,$type,$status,$text) {

     $db = new Db();
     if($status==-1)
     $rows = $db -> select("SELECT * from (SELECT * FROM `notify` where `user_id` = $user_id AND `type` = '$type'  ORDER BY `id` DESC LIMIT 50)
     as m where 
         m.title LIKE '%$text%' or
         m.body LIKE '%$text%' or
         m.date LIKE '%$text%' 
     ");
     else {
       $rows = $db -> select("SELECT * from (SSELECT * FROM `notify` where `user_id` = $user_id AND `type` = '$type'  AND `status` = $status ORDER BY `id` DESC LIMIT 50)
       
        as m where 
         m.title LIKE '%$text%' or
         m.body LIKE '%$text%' or
         m.date LIKE '%$text%' 
       
       ");
     }
     return $rows;


  } 
   public function getUserInvtsINSerche($email,$text) {

     $db = new Db();
    
      $rows = $db -> select("SELECT * from (SELECT *,(SELECT name from users_profile where users_profile.user_id=invoices.from_user_id) as name1 FROM `invoices` where `to_user_email` = '$email' ORDER BY `id` DESC limit 20)
		 as m where 
         m.id LIKE '%$text%' or
         m.name1 LIKE '%$text%' or
         m.invoice LIKE '%$text%' or
         m.total LIKE '%$text%' or
         m.date LIKE '%$text%' 
		 ");
     return $rows;


  }
   public function getUserInvoicesByEmail($email) {

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `invoices` where `to_user_email` = '$email' ORDER BY `id` DESC limit 20");

     return $rows;


  }
  
  public function sendPushNotification1($user_id,$data=array()){
      //sleep(5);
      
     $db = new Db();
  $rows = $db -> select(" SELECT * FROM `user_firebaseToken` where user_id=$user_id");
  foreach ($rows as $val) {
  $to= $val['firebaseToken']; 
  $apiKey='AIzaSyCBY7DfjkXXcAZ2lcHQ5Usu1JquY_jQ4gA';
  
  $fields=array('to'=>$to,'notification'=>$data);
  
  $headers=array('Authorization:key='.$apiKey,'Content-Type: application/json');
  
  $url='https://fcm.googleapis.com/fcm/send';
  
   $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
	            curl_setopt($ch, CURLOPT_POST, true);
	            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		            // Disabling SSL Certificate support temporarly
	            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($fields));
	            $result = curl_exec($ch);
	            curl_close($ch);
	
	           
  }
   return json_decode($rows,JSON_UNESCAPED_UNICODE);
  
}

public function getUser($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * from `users` where `id`= $id");

    return $rows;


  }
  else {
    return false;
  }

 } // end function

public function forget($email){
    $db = new Db();
$rows = $db -> select("SELECT * FROM `users` where `email` = '$email'  ORDER BY `id` DESC LIMIT 1 ");
return $rows;
}

public function servicesCats(){
    $db = new Db();
$rows = $db -> select("SELECT * FROM `category_servic` WHERE `status` =1 ");
return $rows;
}

public function getTotalBonusByUserID($user_id) {

   $bal = 0.00;
   $db = new Db();
   $rows = $db -> select("SELECT * FROM `bonus` where `c_id` = 0 AND `user_id` = $user_id ");


   foreach ($rows as $b) {


     $bal = $bal + (float) $b['bal'];

   }


   return $bal;

}
public function getUserBonusByUserID($user_id) {
 $db = new Db();
   $rows = $db -> select("SELECT * FROM `bonus` where `c_id` = 0 AND `user_id` = $user_id ORDER BY `bonus`.`id` DESC");

   return $rows;

}




public function servicesList($cat_id){
    $db = new Db();
$rows = $db -> select("SELECT * FROM `compan_service` WHERE `category_id` =$cat_id AND `status` = 1 ");
return $rows;
}
public function updateMainEmailAdderss($new_mail,$user_id,$email){

  $this->user_logs($email,"updatenewemailaddress-mobail",date("Y-m-d H:i:s"));

 //$user_id = $_SESSION["usid"];

  $db = new Db();
  $result = $db -> query("UPDATE `users` SET `email`='$new_mail', `status` = 0 WHERE `id` = $user_id");

  return $result;


}

public function addNewMobileNumber($new_mobile,$user_id,$email) {

if(true){
  $this->user_logs($email,"addNewMobileNumber-mobail",date("Y-m-d H:i:s"));
  $db = new Db();
  $result = $db -> query("INSERT INTO `user_mobile` (`user_id`, `mobile`, `hit`, `status`, `date`) VALUES ($user_id, '$new_mobile',0,0,'$date' )");
  $result = $db -> query("UPDATE `users` SET  `status` = 0 WHERE `id` = $user_id");
  return $result;

}
else {

  return false;
}


}

public function update_user_photo($user_id,$photo) {
 $this->user_logs($old,"Update Profile photo",date("Y-m-d H:i:s"));

  $db = new Db();
  $result = $db -> query("UPDATE `users_profile` SET `photo`='$photo' WHERE `user_id` = $user_id");

  return $result;

}
public function update_user_profile($user_id,$name,$email,$mobile,$date,$id_no,$tel,$old) {

if(true){
  $this->user_logs($old,"UpdateProfile",date("Y-m-d H:i:s"));

  $db = new Db();
  $result = $db -> query("UPDATE `users_profile` SET `name`='$name',`id_no` = '$id_no', `mobile`='$mobile',`tel` = '$tel', `re_email`='$email' WHERE `user_id` = $user_id");

  return $result;

}
else {

  return false;
}


}

public function addCommToSystemCommAccount($c_id,$amount,$user_activity_id,$note,$user_id) {
  $d = date("Y-m-d H:i:s");
  $db = new Db();

   $system_comm_rows = $db -> select("SELECT * FROM `system_accounts` WHERE `c_id` = $c_id ");

   $system_comm_id = $system_comm_rows[0]['id'];
   $c_bal = $system_comm_rows[0]['bal'];

   $new_bal = $amount + $c_bal;
   $result = $db -> query("UPDATE `system_accounts` SET  `bal` = '$new_bal' WHERE `id` = $system_comm_id");
  $result = $db -> query("INSERT INTO `system_accounts_activity` (`user_id`, `user_activity_id`, `note`, `bal`, `c_id`,`type`,`date`)
                                                          VALUES ($user_id, $user_activity_id,'$note','$amount',$c_id,'IN','$d')");



  return $result;





}



/*public function addNotify($user_id,$type,$ref_type,$ref_id,$title,$body,$status) {

    $db = new Db();
    $date=date("Y-m-d H:i:s");
    $result = $db -> query("INSERT INTO `notify` (`user_id`,`type`, `ref_type`, `ref_id`,`title`,`body`,`status`,`date`) VALUES ($user_id,'$type','$ref_type', $ref_id,'$title', '$body',$status,'$date')");

    return $result;

  }*/
  
  
    public function monyEX1($from_c,$to_c,$amount) {

      $amount = (float) $amount;

      if($this -> checkUserIsLogdedIn()== true and $amount>0){
        $db = new Db();
        $rows = $db -> select("SELECT * FROM `currencies_ex` WHERE `from_c` = $from_c AND `to_c` = $to_c ORDER BY `id` DESC LIMIT 1");


          if(sizeof($rows)>0){

              $rate = $rows[0]['rate'];

              if($from_c == $to_c)
              $rate = 1;

              return $amount*$rate;

          }
          else {
            return $amount;
          }


        }
        else {

          return false;
        }






    }
    public function getProfileByEmail($email) {

   $db = new Db();
   $rows = $db -> select("SELECT * FROM `users_profile` WHERE `re_email`= '$email' ORDER BY `id`");
   return $rows;

}
public function  add_order($user_id,$value,$user_account_id,$order_id_crm) {

     $date=date("Y-m-d H:i:s");
     $db = new Db();
	 $user_id=intval($user_id); $value=floatval($value); $user_account_id=intval($user_account_id); $order_id_crm=intval($order_id_crm);
	 $result = $db ->query("INSERT INTO `shippingOrders` (`order_id_crm`, `user_id`, `valueILS`, `user_account_id`, `date_order`) VALUES ($order_id_crm, $user_id,$value,$user_account_id,'$date')");
     return $result;
  }
 public function logSend($type,$sendTo,$sub,$msg) {
      //$uid=intval($_SESSION['usid']);
     $date=date("Y-m-d H:i:s");
     $db = new Db();
      $result1 = $db ->query("INSERT INTO `admin_send` ( `type`, `sendTo`,`sub`,`msg`,`date`,`admin_id`)
     VALUES ($type,'$sendTo','$sub','$msg','$date',0)");
     $last_id = mysqli_insert_id($db->getCon());
     return $last_id;
  }
public function addBonus($user_id,$tag,$type,$user_activit_id,$system_activity_id,$bal,$c_id,$note,$email) {


  $this->user_logs($email,"addBonus-mobail",date("Y-m-d H:i:s"));

  $user_id = (int) $user_id;

  $date = date("Y-m-d H:i:s");
  $user_activit_id = (int) $user_activit_id;
  $system_activity_id = (int) $system_activity_id;
  $c_id = (int) $c_id;


  $db = new Db();
  $result = $db -> query("INSERT INTO `bonus` (`user_id`, `tag`, `type`, `user_activit_id`, `system_activity_id`,`bal`,`c_id`,`note`,`date`)
  VALUES ($user_id, '$tag','$type',$user_activit_id,$system_activity_id,'$bal',$c_id,'$note','$date' )");




  // add activity to MLM $account



  $mlm_account = $db -> select("SELECT * FROM `users_accounts` WHERE `user_id` = $user_id AND `currency_id` = 10000 ");



  if(sizeof($mlm_account)>0){


    $mlm_acc_id = $mlm_account[0]['id'];
    $old_bal = $mlm_account[0]['balance'];
    $new_bal = $old_bal+$bal;

    $result = $db -> query("UPDATE `users_accounts` SET  `balance` = '$new_bal' WHERE `id` = $mlm_acc_id");

    $last_id = $this -> addAccountActivity($user_id,$user_id,$note,$mlm_acc_id,10000,$bal,'T_IN');


  }





  return $result;



}



public function getBounsFromCommition($comm,$c_c) {
$comm = (float) $comm;

$comm = $this ->monyEX($c_c,1,$comm);

 $boz = 0;


 if($comm>=0.0000 and $comm<= 0.5000){

   $boz = $comm*0.030;

 }

 if($comm>=0.4000 and $comm<= 0.8800){

   $boz = $comm*0.050;

 }


 if($comm>=0.6600 and $comm<= 30.0600){

   $boz = $comm*0.01;

 }

 if($comm>=10.0200 and $comm<= 20.0200){

   $boz = $comm*0.03;

 }



 if($comm>=10.0200 and $comm<= 20.0200){

   $boz = $comm*0.03;

 }


 if($comm>=12.0120 and $comm<= 60.0060){

   $boz = $comm*0.07;

 }


 if($comm>=30.0060 and $comm<= 60.0060){

   $boz = $comm*0.10;

 }


 if($comm>=30.0020 and $comm<= 60.0030){

   $boz = $comm*0.15;

 }

 if($comm>=40.0020 and $comm<= 100.0020){

   $boz = $comm*0.20;

 }


 if($comm>=45.0009 and $comm<= 225.0009){

   $boz = $comm*0.22;

 }


 if($comm>=75.0003 and $comm<= 1500000.0000){

   $boz = $comm*0.30;

 }

   return $boz;


}
 public function getComm($price) {
  $db = new Db();
     $rows = $db -> select("SELECT * FROM `commission_rate`");

     $rate = 0;


     foreach ($rows as $r ) {

       $f = (int) $r['from_price'];
       $t = (int) $r['to_price'];

       if($price >= $f and $price<=$t){
       $rate = (float) $r['rate'];
     }


     }

     $final_comm = 0;

     if($rate>0){

       $final_comm = $price*$rate;

     }
     else {
      $final_comm = 0;
     }
     return $final_comm;


  }


public function exstrnal_transfare($to_email,$from_account_id,$amount,$type,$user_id) {

   $db = new Db();

   $current_user_id = $user_id;
   
   $userData= $this->getUserProfile($user_id);
   $emaill=$userData[0]['re_email'];

   $users_arr = $db -> select("SELECT * FROM `users` WHERE `email`= '$to_email'");

   $to_user_id = $users_arr[0]['id'];
   $to_user_email = $users_arr[0]['email'];

   $from_account_arr = $db -> select("SELECT * FROM `users_accounts` WHERE `id`= $from_account_id AND `user_id` = $current_user_id ");

   $from_carrancy_id = $from_account_arr[0]['currency_id'];
   $from_account_balance = $from_account_arr[0]['balance'];

   if($from_account_arr[0]['balance']<$amount or $from_account_arr[0]['balance']<=0){
    
	  $msg = 'Failed';
            if($lang=='ar'){
            $msg = 'فشلت العملية ';
             }
           $result['status']= false;
            $result['http_code']= (int) 200;
            $result['token']=$user_id;
            $result['msg']=$msg;
            $result['data']=array();
            print json_encode($result,JSON_UNESCAPED_UNICODE); 
           exit;
    

   }
   // check remote user has same currany account
   $to_account_arr = $db -> select("SELECT * FROM `users_accounts` WHERE `currency_id`= $from_carrancy_id AND `user_id` = $to_user_id AND `status` = 1 ");

   if(sizeof($to_account_arr)>0){


     // calclate transfareing

     $to_carrancy_id = $to_account_arr[0]['currency_id'];
     $to_account_balance = $to_account_arr[0]['balance'];

     $new_balance = $from_account_balance - $amount;

     $new_balance = (float) $new_balance;

     if($new_balance<0){
         $msg = 'Failed';
            if($lang=='ar'){
            $msg = 'فشلت العملية ';
             }
           $result['status']= false;
            $result['http_code']= (int) 200;
            $result['token']=$user_id;
            $result['msg']=$msg;
            $result['data']=array();
            print json_encode($result,JSON_UNESCAPED_UNICODE); 
           exit;

     }

     $result = $db -> query("UPDATE `users_accounts` SET `balance` = '$new_balance'  WHERE `id` = $from_account_id AND `user_id` = $current_user_id");

    $carr_sss = $this->getCurrencyByID($from_account_arr[0]['currency_id']);

     $note = "خصم حوالة بمبلغ ".$amount.' '.$carr_sss[0]['symbol'].' '. " من حـ/".$from_account_arr[0]['account_name'];
     $note .= " واصبح رصيد حسابك ".$new_balance.' '.$carr_sss[0]['symbol'];
     if($type=='inv'){

       $note = "دفع مبلغ مطالبة مالية ".$amount.' '.$carr_sss[0]['symbol'].' '. " من حـ/".$from_account_arr[0]['account_name'];
       $note .= " واصبح رصيد حسابك ".$new_balance.' '.$carr_sss[0]['symbol'];
     }

      $note.="<br>"."تمت الحركة بواسطتك: ";


     $user_account_id = $from_account_arr[0]['id'];
     $activity_currency_id = $from_account_arr[0]['currency_id'];
     $last_iddddd=$this -> addAccountActivity($current_user_id,$to_user_id,$note,$user_account_id,$activity_currency_id,$amount,'T_OUT');




     //bonus
     $bal = 1;

     if($type=='inv'){

        $bal = 8;

     }


     $bal = $this->getBounsFromCommition($this -> getComm($amount),$from_account_arr[0]['currency_id']);


     $note2 = "مكافأة إثر ".$note;
     $this -> addBonus($current_user_id,'PAY_USER','IN',$last_iddddd,0,$bal,0,$note2,$emaill);

     $this -> addNotify($current_user_id,'SITE','BONUS',$last_iddddd,'مكافأة',$note2,0);



          $sub = urlencode('تهانيناً .. لقد حصلت على مكافأة من أموالي‎');
          $msg = urlencode($note2);
          $emaill = $emaill;
          file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$emaill}&sub={$sub}&msg={$msg}&ref=?action=activity");


          $this -> logSend(1,$emaill,$sub,$msg);


     $sub = urlencode('حوالة صادرة من حسابك');


     if($type=='inv'){

        $sub = urlencode('تم دفع المطالبة المالية بنجاح');

     }
     $msg = urlencode($note);
     $emaill = $emaill;
     file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$emaill}&sub={$sub}&msg={$msg}&ref=?action=activity");

       $this -> logSend(1,$emaill,$sub,$msg);
     $to_account_id = $to_account_arr[0]['id'];



     $comm_amount = $this -> getComm($amount);






     $new_balance = ($to_account_balance + $amount ) - $comm_amount;

     $result = $db -> query("UPDATE `users_accounts` SET `balance` = '$new_balance'  WHERE `id` = $to_account_id AND `user_id` = $to_user_id");

     $pp_arr = $this -> getProfileByUserID($user_id);

     //qqqqqqqqqqqqq
     $carr_sss = $this->getCurrencyByID($to_account_arr[0]['currency_id']);

     $note = "رصيد من حوالة بمبلغ ".$amount.' '.$carr_sss[0]['symbol'].' '. " الى حـ/ ".$to_account_arr[0]['account_name'];
     $note .= " واصبح رصيد حسابك ".$new_balance.' '.$carr_sss[0]['symbol'];
     $note.="<br>تمت الحركة بواسطة: ".$pp_arr[0]['name'];



     if($type=='inv'){

       $note = "تم اضافة رصيد بناء على مطالبة مالية مرسله ".$amount.' '.$carr_sss[0]['symbol'].' '. " الى حـ/ ".$to_account_arr[0]['account_name'];
       $note .= " واصبح رصيد حسابك ".$new_balance.' '.$carr_sss[0]['symbol'];
       $note.="<br>تمت الحركة بواسطة: ".$pp_arr[0]['name'];

     }


     $user_account_id = $to_account_arr[0]['id'];
     $activity_currency_id = $to_account_arr[0]['currency_id'];
     $last_id = $this -> addAccountActivity($to_user_id,$current_user_id,$note,$user_account_id,$activity_currency_id,$amount,'T_IN');

     $this -> addNotify($to_user_id,'SITE','TRANS_ACTIVITY',$last_id,'حوالة واردة ',$note,0);
     $sub = urlencode('حوالة واردة ');
     if($type=='inv'){
      $sub = urlencode('تم تلقي دفعة مالية إثر دفع مطالبة مالية');
     }
     $msg = urlencode($note);
     file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$to_user_email}&sub={$sub}&msg={$msg}&ref=?action=activity");
      $this -> logSend(1,$to_user_email,$sub,$msg);

     $note ="خصم عمولة تحويل اموال بقيمة $comm_amount". ' من حـ/ '.$to_account_arr[0]['account_name'];
     $note.="<br>"."حوالة من: ".$pp_arr[0]['name'];


     $last_id = $this -> addAccountActivity($to_user_id,0,$note,$user_account_id,$activity_currency_id,$comm_amount,'T_OUT');
     $this -> addCommToSystemCommAccount($activity_currency_id,$comm_amount,$last_id,$note,$user_id);

   }
   else {
     $new_balance = $from_account_balance - $amount;

     $new_balance = (float)  $new_balance;

     if($new_balance<0){
         $msg = 'Failed';
            if($lang=='ar'){
            $msg = 'فشلت العملية ';
             }
           $result['status']= false;
            $result['http_code']= (int) 200;
            $result['token']=$user_id;
            $result['msg']=$msg;
            $result['data']=array();
            print json_encode($result,JSON_UNESCAPED_UNICODE); 
           exit;

     }

     $result = $db -> query("UPDATE `users_accounts` SET `balance` = '$new_balance'  WHERE `id` = $from_account_id AND `user_id` = $current_user_id");


      $pp_arr = $this -> getProfileByUserID($user_id);

      $note = "خصم حوالة بمبلغ ".$amount. " من حـ/".$from_account_arr[0]['account_name'];
      $note .= " واصبح رصيد حسابك ".$new_balance;
      $note.="<br>تمت الحركة بواسطة: ".$pp_arr[0]['name'];





     $user_account_id = $from_account_arr[0]['id'];
     $activity_currency_id = $from_account_arr[0]['currency_id'];
     $last_iddddd = $this -> addAccountActivity($current_user_id,$to_user_id,$note,$user_account_id,$activity_currency_id,$amount,'T_OUT');
     $bal = 1;
     $note2 = "مكافأة إثر ".$note;
     $this -> addBonus($current_user_id,'PAY_USER','IN',$last_iddddd,0,$bal,0,$note2,$emaill);
     $this -> addNotify($current_user_id,'SITE','BONUS',$last_iddddd,'مكافأة',$note2,0);


     $sub = urlencode('تهانيناً .. لقد حصلت على مكافأة من أموالي‎');
     $msg = urlencode($note2);
     $emaill = $emaill;
     file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$emaill}&sub={$sub}&msg={$msg}&ref=?action=activity");

       $this -> logSend(1,$emaill,$sub,$msg);
    $note1 = $note;
     $sub = urlencode('حوالة صادرة من حسابك');
     $msg = urlencode($note);
     $emaill = $emaill;
     file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$emaill}&sub={$sub}&msg={$msg}&ref=?action=activity");
     $this -> logSend(1,$emaill,$sub,$msg);
 
     $date_now =  date("Y-m-d H:i:s");

    $carr_arrr = $db -> select("SELECT * FROM `system_currencies` WHERE `id`= $from_carrancy_id");

     $account_name = "حساب ".$carr_arrr[0]['name_ar'];

     $old_am = $amount;
       $comm_amount = $this -> getComm($amount);
       $amount = $amount - $comm_amount;
     $result111 = $db -> query("INSERT INTO `users_accounts` ( `user_id`, `currency_id`,`account_name`,`balance`,`date`)
     VALUES ($to_user_id,$from_carrancy_id,'$account_name','$amount','$date_now')");


    $last_iddd = mysqli_insert_id($db->getCon());
     $pp_arr = $this -> getProfileByUserID($user_id);
     $carr_sss = $this->getCurrencyByID($from_carrancy_id);

     $note = "رصيد من حوالة بمبلغ ".$old_am. ' '.$carr_sss[0]['symbol'].' '. "الى ".$account_name;
     $note .= " وأصبح رصيد حسابك ".$amount." ".$carr_sss[0]['symbol'];

     $note.="<br>تمت الحركة بواسطة: ".$pp_arr[0]['name'];
     $user_account_id = $to_dc_arr[0]['id'];
     $activity_currency_id = 0;
     $last_id = $this -> addAccountActivity($to_user_id,$current_user_id,$note,$last_iddd,$from_carrancy_id,$old_am,'T_IN');

     $this -> addNotify($to_user_id,'SITE','TRANS_ACTIVITY',$last_id,'حوالة واردة ',$note,0);
     $sub = urlencode('حوالة واردة ');
     $msg = urlencode($note);
     file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$to_user_email}&sub={$sub}&msg={$msg}&ref=?action=activity");
     $this -> logSend(1,$to_user_email,$sub,$msg);

     $note ="خصم عمولة تحويل اموال بقيمة $comm_amount". ' من حـ/ '.$account_name;
     $note.="<br>"."حوالة من: ".$pp_arr[0]['name'];

     $last_id = $this -> addAccountActivity($to_user_id,0,$note,$last_iddd,$from_carrancy_id,$comm_amount,'T_OUT');
     $this -> addCommToSystemCommAccount($from_carrancy_id,$comm_amount,$last_id,$note,$user_id);


   }


   return true;

}



 public function addAccountActivity($user_id,$from_id,$note,$user_account_id,$activity_currency_id,$activity_amount,$activity_type) {

    $db = new Db();
    $d = date("Y-m-d H:i:s");
    $result = $db -> query("INSERT INTO `users_account_activity` (`user_id`, `from_id`, `note`,`user_account_id`,`activity_currency_id`,`activity_amount`,`activity_type`,`activity_date`,`status`) VALUES ($user_id, $from_id, '$note',$user_account_id,$activity_currency_id,'$activity_amount','$activity_type','$d',1)");
//  mysqli_insert_id($db->getCon());
    return mysqli_insert_id($db->getCon());

  }
public function getCurrencyByID($c) {

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `system_currencies` where `id` = $c LIMIT 1");

     return $rows;


  }
public function checkAmountIsIn($amount,$user_account_id,$user_id) {

        $test = false;

        $amount = (float) $amount;
        $user_account_id = (int) $user_account_id;

        if(!is_numeric($amount) or $amount < 0 or $user_account_id==0 ){

          $test = false;

        }
        else {
          $test = true;
        }


        if($test==true){

        $user_id = $user_id;

        $db = new Db();
        $acc_rows = $db -> select("SELECT * FROM `users_accounts` WHERE `user_id` = $user_id AND `id` = $user_account_id ");

        $acc_bal = (float) $acc_rows[0]['balance'] ;


        if($acc_bal <= 0 or $amount>$acc_bal){

          $test = false;

        }




      }




          return $test;







    }


public function monyEX($from_c,$to_c,$amount) {

      $amount = (float) $amount;

      if($amount>0){
        $db = new Db();
        $rows = $db -> select("SELECT * FROM `currencies_ex` WHERE `from_c` = $from_c AND `to_c` = $to_c ORDER BY `id` DESC LIMIT 1");


          if(sizeof($rows)>0){

              $rate = $rows[0]['rate'];

              if($from_c == $to_c)
              $rate = 1;

              return $amount*$rate;

          }
          else {
            return $amount;
          }


        }
        else {

          return false;
        }






    }

/////////////////////////////////////////////////




////////////////////////////////////////////////


public function chackEmailExsist($email) {

     $check = 0;

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `users` where `email` = '$email'  ");

     if(sizeof($rows)>0){
     $check = 1;
     }
     return $check;

  }
 
public function chackMobileExsist($mobile) {


      $check = 0;

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `user_mobile` where `mobile` = '$mobile' AND `status` = 1 LIMIT 1 ");

     if(sizeof($rows)>0)
     $check = 1;

     return $check;

  } 
 
  public function signup($name,$email,$password,$mobile) {

     $date=date("Y-m-d H:i:s");

     $name = strip_tags($name);
     $mobile = strip_tags($mobile);


     $db = new Db();
     $result1 = $db -> query("INSERT INTO `users` ( `email`, `password`,`status`,`date`)
     VALUES ('$email','$password',0,'$date')");

     $last_id = mysqli_insert_id($db->getCon());

     $f_user_id = $last_id;
     $email_id = $last_id;
     //$_SESSION["reg_usid"]=$last_id;
    // $_SESSION["reg_mobile"]=$mobile;

     $result1 = $db -> query("INSERT INTO `user_mobile` ( `user_id`, `mobile`,`hit`,`status`,`date`)
     VALUES ($last_id,'$mobile',0,0,'$date')");

     $mobile_id = mysqli_insert_id($db->getCon());

     $result1 = $db -> query("INSERT INTO `users_profile` ( `user_id`, `name`,`id_no`,`mobile`,`tel`,`re_email`,`photo`,`country_id`)
     VALUES ($last_id,'$name','','$mobile','','$email','https://amwwaly.com/d.jpg',6)");

     $result1 = $db -> query("INSERT INTO `users_main_account` ( `user_id`, `balance`,`date`)
     VALUES ($last_id,'0','$date')");

     $account_name = "حساب دولار";

     $result1 = $db -> query("INSERT INTO `users_accounts` ( `user_id`, `currency_id`,`account_name`,`balance`,`date`)
     VALUES ($last_id,1,'$account_name','0','$date')");


     $account_name = "حساب ملاليم";

     $result1 = $db -> query("INSERT INTO `users_accounts` ( `user_id`, `currency_id`,`account_name`,`balance`,`date`)
     VALUES ($last_id,10000,'$account_name','0','$date')");

     $last_id = mysqli_insert_id($db->getCon());


     $code = $mobile_id*12345;
     $msg = "Your Code is: ".$code;
     //$result1 = $this -> sendSMS($msg,$mobile);




     ////// update InviteUser


        $rowsss = $db -> select("SELECT * FROM `emails_invite` where `email` = '$email' and `status` = 0 ");



        if(sizeof($rowsss)>0){

          $invite_user_id = $rowsss[0]['user_id'];
          //bonus for register user
          $bal = 5;
          $note2 = "مكافأة إثر "."قيام المستخدم"." $name"." بالاشتراك من خلالك";
      //    $this -> addBonus($invite_user_id,'INVITE_REG_USER','IN',0,0,$bal,0,$note2);

        $d = date("Y-m-d H:i:s");
        $resultxxxx = $db -> query("INSERT INTO `bonus` (`user_id`, `tag`, `type`, `user_activit_id`, `system_activity_id`,`bal`,`c_id`,`note`,`date`)
        VALUES ($invite_user_id, 'INVITE_REG_USER','IN',0,0,'$bal',0,'$note2','$d' )");


        }





       $result23232323 = $db -> query("UPDATE `emails_invite` SET `status` = 1 WHERE `email` = '$email' ");








       /////


            //bonus for register user
            $bal = 2;
            $note2 = "مكافأة إثر "."اشراكك في خدمة أموالي";
          //  $this -> addBonus($f_user_id,'REG_USER','IN',0,0,$bal,0,$note2);

          $d = date("Y-m-d H:i:s");
          $resultxxxx = $db -> query("INSERT INTO `bonus` (`user_id`, `tag`, `type`, `user_activit_id`, `system_activity_id`,`bal`,`c_id`,`note`,`date`)
          VALUES ($f_user_id, 'REG_USER','IN',0,0,'$bal',0,'$note2','$d' )");





     $email_code = $email_id*54321;

     $sub = urlencode('شكرا لإشتراكك');
     $msg = urlencode("شكرا لاختيارك خدمة أموالي, لتفعيل حسابك برجاء الضغط على الزر التالي لتمام عملية اشتراكك لدينا");
     file_get_contents("http://m.qedama.com/leenMail/pay4.php?to={$email}&sub={$sub}&msg={$msg}&btype=reg&code={$email_code}");


     return $result1;
  }

public function getUserAccountsByUserID($user_id) {

     $db = new Db();
     $rows = $db -> select("SELECT *,(select name_ar from system_currencies where system_currencies.id=users_accounts.currency_id) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_accounts.currency_id) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_accounts.currency_id) as currency_symbol
     FROM `users_accounts` where `user_id` = $user_id  ORDER BY `id` DESC Limit 50");

     return $rows;


  }
 
 public function getUserAccountMovements($user_id,$user_account_id) {

     $db = new Db();
     
     $rows = $db -> select("SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
     (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id and `user_account_id` = $user_account_id ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
  public function getUserMovements($user_id) {

     $db = new Db();
     
     $rows = $db -> select("SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
      (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
  public function getUserBonusByUserIDSerche($user_id,$text) {
 $db = new Db();
   $rows = $db -> select("SELECT * from (SELECT * FROM `bonus` where `c_id` = 0 AND `user_id` = $user_id  ORDER BY `bonus`.`id` DESC)as m where 
         m.date LIKE '%$text%' or
         m.bal LIKE '%$text%' or
         m. note LIKE '%$text%'
         
         ORDER BY `id` DESC Limit 50");

   return $rows;

}
  public function getUserMovementsSerche($user_id,$text) {

     $db = new Db();
     
     $rows = $db -> select("SELECT * from (SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
     (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id ORDER BY `id` DESC Limit 50) as m where 
         m.note LIKE '%$text%' or
         m.currency_name_ar LIKE '%$text%' or
         m.currency_name_en LIKE '%$text%' or
         m.currency_symbol LIKE '%$text%' or
         m.activity_date LIKE '%$text%' or
         m. from_name LIKE '%$text%'
         
         ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
  public function getUserLastMovements($user_id) {

     $db = new Db();
     
     $rows = $db -> select("SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
      (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id ORDER BY `id` DESC Limit 10");
 //var_dump($rows);
    return $rows;
  }
  
  
  public function getUserMovementsINSerche($user_id,$text) {

     $db = new Db();
     
     $rows = $db -> select("SELECT * from (SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
     (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id and activity_type='T_IN' ORDER BY `id` DESC Limit 50) as m where 
         m.note LIKE '%$text%' or
         m.currency_name_ar LIKE '%$text%' or
         m.currency_name_en LIKE '%$text%' or
         m.currency_symbol LIKE '%$text%' or
         m.activity_date LIKE '%$text%' or
         m. from_name LIKE '%$text%'
         
         ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
  public function getUserMovementsIN($user_id) {

     $db = new Db();
     
     $rows = $db -> select("SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
     (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id and activity_type='T_IN' ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
   public function getUserMovementsOUT($user_id) {

     $db = new Db();
     
     $rows = $db -> select("SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
     (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id and activity_type='T_OUT' ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
  public function getUserMovementsOUTSerche($user_id,$text) {

     $db = new Db();
     
     $rows = $db -> select("SELECT * from ( SELECT *,(select name_ar from system_currencies where system_currencies.id=users_account_activity.activity_currency_id	Limit 1) as currency_name_ar,
     (select name_en from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_name_en,
     (select symbol from system_currencies where system_currencies.id=users_account_activity.activity_currency_id Limit 1) as currency_symbol,
     (select photo from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as photo,
     (select name from users_profile where users_profile.user_id=users_account_activity.from_id	Limit 1) as from_name
     FROM `users_account_activity` where `user_id` = $user_id and activity_type='T_OUT' ORDER BY `id` DESC Limit 50 ) as m where 
         m.note LIKE '%$text%' or
         m.currency_name_ar LIKE '%$text%' or
         m.currency_name_en LIKE '%$text%' or
         m.currency_symbol LIKE '%$text%' or
         m.activity_date LIKE '%$text%' or
         m. from_name LIKE '%$text%'
         
         ORDER BY `id` DESC Limit 50");
 //var_dump($rows);
    return $rows;
  }
  
 
 
 
 
 public function getPhotoByItemID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `menu_items` WHERE `id` = $id");

    return $rows;


  }
  else {
    return false;
  }

} // end function




public function get_type_violation_by_id($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `type_violation` WHERE `id` = $id");

    return $rows;


  }
  else {
    return false;
  }

} // end function




public function getDeviceData($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_form` WHERE `device_id` = '$id'");

    return $rows;


  }
  else {
    return false;
  }

} // end function


 public function getMenuCategories() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `menu_cats` WHERE `status` = 1 ORDER BY `order`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function

 public function getMainGridItem() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `home_grid_items` ORDER BY `sort` ASC");

    return $rows;


  }
  else {
    return false;
  }

 } // end function




 public function isCOAllowdForUser($user_id) {

  if($this -> checkUserIsLogdedIn()== true){

    $canCO = false;

    $db = new Db();


    // time check

    $start_arr = $db -> select("SELECT * FROM `orders_setting` WHERE `id` = 4 ");
    $end_arr = $db -> select("SELECT * FROM `orders_setting` WHERE `id` = 5 ");

    $curentHour = date("H");

    $s = $start_arr[0][value];
    $e = $end_arr[0][value];

    if($curentHour >= $s and $curentHour <= $e)
    $canCO = true;



    if($canCO == true){

      $user_pforile_arr = $db -> select("SELECT * FROM `users_profile` WHERE `user_id` = $user_id ");

      if($user_pforile_arr[0][abroval] != 3){
      $canCO = false;
    }

    }

    return $canCO;


  }
  else {
    return false;
  }

 } // end function



 public function msgCOAllowdForUser($user_id) {

  if($this -> checkUserIsLogdedIn()== true){

    $canCO = "خطأ غير معروف راجع الإدارة";

    $db = new Db();


    // time check

    $start_arr = $db -> select("SELECT * FROM `orders_setting` WHERE `id` = 4 ");
    $end_arr = $db -> select("SELECT * FROM `orders_setting` WHERE `id` = 5 ");

    $curentHour = date("H");

    $s = $start_arr[0][value];
    $e = $end_arr[0][value];

    if($curentHour >= $s and $curentHour <= $e){

    }
    else {
    $canCO = "عذرا الطلبات متاحة فقط في اوقات العمل " . "من الساعة: ". $s ." صباحا وحتى الساعة: ".$e. " مساءا";
    }





      $user_pforile_arr = $db -> select("SELECT * FROM `users_profile` WHERE `user_id` = $user_id ");

      if($user_pforile_arr[0][abroval] != 3){
      $canCO = "حسابك غير معتمد ,, تاكد من ادخال البيانات والحصول على عضوية ";
    }



    return $canCO;


  }
  else {
    return false;
  }

 } // end function





 public function insertToMarnaDB($OrderIDNumber,$userName,$marna_id,$date_time_order,$payName,$mobileNO,$item_number,$item_name,$cartItemQuntity,$optionToIntert,$address_to_instaert) {

  if(true){
 $date=date("Y-m-d H:i:s");
    $db = new Db();

    $result1 = $db -> query("INSERT INTO `marna_order` ( `order_id`, `full_name`,`marna_id`,`date_time`,`payment_method_txt`,`mobile`,`item_number`,`item_name`,`quntaty`,`item_option_txt`,`delevery_address_txt`,`date`,`status`)
    VALUES ( $OrderIDNumber, '$userName',$marna_id,'$date_time_order','$payName','$mobileNO','$item_number','$item_name','$cartItemQuntity','$optionToIntert','$address_to_instaert','$date',0)");

    return $result1;

  }
  else {
    return false;
  }
 } // end function





public function getHomeItemsSorted() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `home_menu_v2` ORDER BY `sort` ASC");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getHomeItemsSortedv2() {

   if($this -> checkUserIsLogdedIn()== true){

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `home_menu_v3` where `status`=1 ORDER BY `sort` ASC");

     return $rows;


   }
   else {
     return false;
   }

  } // end function


public function getHomeItemsSortedv4() {

   if($this -> checkUserIsLogdedIn()== true){

     $db = new Db();
     $rows = $db -> select("SELECT * FROM `home_menu_v4` where `status`=1 ORDER BY `sort` ASC");

     return $rows;


   }
   else {
     return false;
   }

  } // end function

  public function getHomeItemsSortedv5() {

     if($this -> checkUserIsLogdedIn()== true){

       $db = new Db();
       $rows = $db -> select("SELECT * FROM `home_menu_v5` where `status`=1 ORDER BY `sort` ASC");

       return $rows;


     }
     else {
       return false;
     }

    } // end function



    public function getOOrderSettingByNamE($name) {

     if($this -> checkUserIsLogdedIn()== true){

       $db = new Db();
       $rows = $db -> select("SELECT * FROM `orders_setting` WHERE `name` = '$name' ");

       return $rows;


     }
     else {
       return false;
     }

    }




public function getAllMenuItems() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `menu_items` WHERE `online` = 1 ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function





 public function checkTK($tk,$user_id) {

   if($this -> checkUserIsLogdedIn()== true){


     $db = new Db();
     $rows = $db -> select("SELECT * FROM `user_login` WHERE `id`= $user_id");
     $pass = $rows[0][password];

     $key = "2017".$pass.$user_id;
     $eync = md5($key);

     if($tk==$eync)
     return true;
     else {
       return false;
     }




   }
   else {
     return false;
   }

  } // end function




 public function calcolateCrantDeleveryPrice($price) {

   $delvery_cost = 0 ;

   if($this -> checkUserIsLogdedIn()== true){



     $db = new Db();
     $rows = $db -> select("SELECT * FROM `orders_setting` WHERE `name` = 'delevary_cost_id'");


     $current_delevery_id = $rows[0]['value'];

     $rows = $db -> select("SELECT * FROM `delivery_type` WHERE `id` = $current_delevery_id");

     if($current_delevery_id==199285){

       // free

       $delvery_cost = 0 ;

     }

     if($current_delevery_id==199286){

       $delvery_cost = $rows[0]['val1'] ;

     }


     if($current_delevery_id==199287){

       if($price >= $rows[0]['val2'])
          $delvery_cost = 0 ;
          else {
            $delvery_cost = $rows[0]['val1'] ;
          }

     }


     if($current_delevery_id==199288){

       $delvery_cost = ($rows[0]['val1']*$price)/100 ;

     }





     if($current_delevery_id==199289){

      $val1 = explode("-", $rows[0][val1]);
      $val2 = explode("-", $rows[0][val2]);
      $val3 = explode("-", $rows[0][val3]);
      $val4 = explode("-", $rows[0][val4]);
      $val5 = explode("-", $rows[0][val5]);

      $delvery_cost = $val1[2];

      if($price<=$val1[1] and $val1[1] != 0 and $price>=$val1[0])
      $delvery_cost = $val1[2];


      if($price<=$val2[1] and $val2[1] != 0  and $price>=$val2[0])
      $delvery_cost = $val2[2];

      if($price<=$val3[1] and $val3[1] != 0  and $price>=$val3[0])
      $delvery_cost = $val3[2];

      if($price<=$val4[1] and $val4[1] != 0  and $price>=$val4[0])
      $delvery_cost = $val4[2];

      if($price<=$val5[1] and $val5[1] != 0  and $price>=$val5[0])
      $delvery_cost = $val5[2];




     }




     return $delvery_cost;


   }
   else {
     return false;
   }

  } // end function




 public function getUserLogin($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT `id`,`name`,`email`,`verified`,`status`,`date` FROM `user_login` WHERE `id`= '$user_id' ORDER BY `id`");
    return $rows;
  }
  else {
    return false;
  }

 } // end function


 public function getUserByEmail($email) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_login` WHERE `email`= '$email' ORDER BY `id`");
    return $rows;
  }
  else {
    return false;
  }

 } // end function


 public function getProfileByUserID($user_id) {
    $db = new Db();
   
    $rows = $db -> select("SELECT * FROM `users_profile` WHERE `user_id`= $user_id ORDER BY `id`");
    return $rows;
 

 } // end function


 public function getRatesByITemID($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `rates` WHERE `item_id`= $user_id AND `status` = 1 ORDER BY `id` ASC");
    return $rows;
  }
  else {
    return false;
  }

 } // end function


 public function getUnPrintetOrder() {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `marna_order` WHERE `status`= 0  ORDER BY `id` ASC");

    foreach ($rows as $key ) {


      $m_id = $key[id];

      $result2 = $db -> query("UPDATE `marna_order` SET  `status`= 1 WHERE `id` = $m_id");

    }


    return $rows;
  }
  else {
    return false;
  }

 } // end function


 public function getAllUnProOrder() {


      date_default_timezone_set('Asia/Jerusalem');

     if($this -> checkUserIsLogdedIn()== true){

       $db = new Db();
       $rows = $db -> select("SELECT * FROM `ordars` WHERE `order_status` = 0  ORDER BY `id` DESC");


       $UTC = new DateTimeZone("UTC");
   $newTZ = new DateTimeZone("Asia/Jerusalem");

   $date= date("Y-m-d H:i:s");
   $date = new DateTime( $date, $UTC );
   $date->setTimezone( $newTZ );

       if(sizeof($rows)>0){
         $final_arr=array();
         $temp=array();
       foreach ($rows as $key) {


         $payment_arr = $this -> getOnePaymentMethodsByID($key['payment_methods']);
         $address_arr = $this -> getOneAddressByID($key['address_id']);


         $status_name="";

         if($key['address_id']==0 or $key['address_id']==-1)
         $withDelevery = false;
         else {
           $withDelevery = true;
         }

         if($key['order_status']==0)
         $status_name="تم استلام طلبكم";

         if($key['order_status']==1)
         $status_name="قيد التنفيذ";

         if($key['order_status']==2){

           if($withDelevery)
         $status_name="قيد التوصيل";
         else {
           $status_name="طلبكم جاهز في مارنا هاوس";
         }


       }

         if($key['order_status']==5)
         $status_name="تم تسليم الطلبية بنجاح";

         if($key['order_status']==6)
         $status_name="طلبية مرفوضة";




         $final_arr['id'] = (int) $key['id'];
         $final_arr['user_id'] = $key['user_id'];
         $final_arr['payment_method_id'] = (int) $key['payment_methods'];
         $final_arr['payment_method_txt_ar'] = $payment_arr[0]['payment_name_ar'];
         $final_arr['payment_method_txt_en'] = $payment_arr[0]['payment_name_en'];
         $final_arr['delevary_type_id'] = 0;
         $final_arr['address_id'] = (int) $key['address_id'];
         $final_arr['address_title'] = $address_arr[0]['address_name'];
         $final_arr['price'] = $key['price'];
         $final_arr['order_text_status_ar'] =$status_name;
         $final_arr['order_text_status_en'] = $status_name;
         $final_arr['isRated'] = false;
         $final_arr['withDelivary'] = $withDelevery;
         $final_arr['order_status'] = (int) $key['order_status'];


         $date= date("Y-m-d H:i:s");

         $date=$key['date'];

         $final_arr['order_datetime'] = $date;

         $minFromDB = $this -> getOOrderSettingByNamE('time_delevery');
         $minutes_to_add = $minFromDB[0]['value'];



         $time = new DateTime($date);
         $time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

         $stamp = $time->format('Y-m-d H:i:s');

         $final_arr['order_delivered_datetime'] = $stamp;




         $final_arr['items'] = $this -> getCartPordactForUserIDandOrderID($key['user_id'],$key['id']);
         array_push($temp,$final_arr);

       }

       $rows = $temp;


     }


       return $rows;


     }
     else {
       return false;
     }

 } // end function




 public function getRatesByITemIDWithUsername($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();

    $final_arr = array();
    $arr = array();

    $rows = $db -> select("SELECT * FROM `rates` WHERE `item_id`= $user_id AND `status` = 1 ORDER BY `id` ASC");

    if(sizeof($rows) > 0){


        foreach ($rows as $rate) {

        $id_u = $rate['user_id'];
        $rows2 = $db -> select("SELECT *  FROM `user_login` WHERE `id` =  $id_u ");

        $userName = $rows2[0]['name'];


        $final_arr['rate_id'] = (int)  $rate['id'];
        $final_arr['rate_by_user_id'] = (int)  $rate['user_id'];
        $final_arr['rate_by_user_name'] = $userName;
        $final_arr['rate_value'] = (int) $rate['rate'];
        $final_arr['rate_txt'] = $rate['comments'];
        $final_arr['rate_date'] = $rate['date'];

        array_push($arr,$final_arr);


      } // foreach





  //$rows['userName'] = $userName;

} // end size of




    return $arr;
  }
  else {
    return false;
  }

 } // end function


public function getPointsByMarnaID($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `points` WHERE `marna_id`= $user_id ORDER BY `id` DESC LIMIT 1");
    return $rows;
  }
  else {
    return false;
  }

 } // end function


 public function getUserAddressByUserId($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_address` WHERE `user_id`= '$user_id' AND `city_id` != '' ORDER BY `id` DESC ");
    return $rows;
  }
  else {
    return false;
  }

 } // end function

 public function getUserGpsByUserId($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_gps` WHERE `user_id`= '$user_id' ORDER BY `id`");
    return $rows;
  }
  else {
    return false;
  }

 } // end function

 public function getUserDevicesByUserId($user_id) {

  if($this -> checkUserIsLogdedIn()== true){
    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_devices` WHERE `user_id`= '$user_id' ORDER BY `id`");
    return $rows;
  }
  else {
    return false;
  }

 } // end function


 public function getRegSetting() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `reg_setting` ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function

 public function getUserCitys() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `citys` ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function
 
 
 
 public function getTablesList() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT `id`, CONCAT(`table_number`,' - ',`table_name_ar`) AS `table_number`,`table_name_ar`,`table_name_en`,`online`, `table_number` AS `sort` FROM `tables` WHERE `online` = 1 ORDER BY `sort` ASC");

    return $rows;


  }
  else {
    return false;
  }

 } // end function
 
 
 


 public function getCityByID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `citys` WHERE `id` = $id ");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getRegonByID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `region` WHERE `id` = $id ");

    return $rows;


  }
  else {
    return false;
  }

 } // end function

 public function getUserRegion() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `region` ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function



 public function getAllActivePaymentMethods() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `payment_methods` WHERE `status` = 1 ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function



 public function getDeviceTKforUser($user_id) {

  if($this -> checkUserIsLogdedIn()== true){


    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_login` WHERE `id`= $user_id");
    $pass = $rows[0][password];

    $key = "2017".$pass.$user_id;

    return md5($key);


  }
  else {
    return false;
  }

 } // end function



 public function getAllPyamentForUserID($user_id) {

   $arr = array();
$arr2 = array();
  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `users_payment_methods` WHERE `user_id` = $user_id");


    foreach ($rows as $key) {
      $temp = array();

      $pid = $key[payment_id];

      $rows2 = $db -> select("SELECT * FROM `payment_methods` WHERE `id` = $pid ");

      array_push($arr,$rows2[0]);


    }

    return $arr;


  }
  else {
    return false;
  }

 } // end function



 public function getAllActiveDelivaryType() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `orders_setting` WHERE `name` = 'delevary_cost_id'");
    $id = $rows[0]['value'];
    $rows = $db -> select("SELECT * FROM `delivery_type` WHERE `id` = $id ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getOnePaymentMethodsByID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `payment_methods` WHERE `id` = $id ");

    return $rows;


  }
  else {
    return false;
  }

 } // end function



 public function getOneAddressByID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `user_address` WHERE `id` = $id ");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function addMsgFromAPI($from_user_id,$to_user_id,$msg,$subject) {

  if($this -> checkUserIsLogdedIn()== true){

    $date=date("Y-m-d H:i:s");
    $db = new Db();
    $result1 = $db -> query("INSERT INTO `msgs` ( `from_user_id`, `to_user_id`,`session_id`,`subject`,`msg`,`read`,`status`,`type`,`date`)
    VALUES ( $from_user_id, $to_user_id,0,'$subject','$msg',0,0,'GM','$date')");



    $device = $this -> getUserDevicebyId($to_user_id);

    $to = urlencode($device[0]['device_cloud_id']);
    $subject2 = urlencode($subject);
    $url ="http://app.marnahouse.ps/api/sendToOneDevice.php?to=".$to."&msg=".$subject2;
    $homepage = file_get_contents($url);


    return $result1;


  }
  else {
    return false;
  }

 }
 public function sendASMS($msg,$mobile) {
     $date=date("Y-m-d H:i:s");
      $db = new Db();
   $result1 = $db ->query("INSERT INTO `admin_send` ( `type`, `sendTo`,`msg`,`date`,`admin_id`)
     VALUES (2,'$mobile','$msg','$date',0)");
    // $last_id = mysqli_insert_id($db->getCon());

         $username = "pay4";
         $password = 'pay42019';
         $sinder = "AMWWALY.COM";
         $sinder = urlencode($sinder);
         $msg = urldecode($msg);
         $msg = urlencode($msg);


  $url ="https://int.mtcsms.com/sendsms.aspx?username=$username&password=$password&from=$sinder&to=$mobile&msg=$msg&type=0";
       // $url =urlencode($url);
  $response = file_get_contents($url);

  return $response;

}

 public function updateOrderStatusFROMAPI($order_id,$to_status) {
   date_default_timezone_set('Asia/Jerusalem');

 if($this -> checkUserIsLogdedIn()== true){


   $db = new Db();
   $result = $db -> query("UPDATE `ordars` SET `order_status` = $to_status WHERE `id` = $order_id");

   $d = date("Y-m-d H:i:s");

   $result = $db -> query("INSERT INTO `order_actions_log` (`order_id`,  `to_status`, `by_user`, `date`)
    VALUES ($order_id,'$to_status', 'NABIL-SYSTEM', '$d')");

   return $result;

 }
 else {

   return false;
 }


 }


 public function getOrderByOrderID($order_id) {
   date_default_timezone_set('Asia/Jerusalem');

 if($this -> checkUserIsLogdedIn()== true){



   $db = new Db();
   $rows = $db -> select("SELECT * FROM `ordars` WHERE `id` = $order_id");

   return $rows;

 }
 else {

   return false;
 }


 }


 public function getUserDevicebyId($user_id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `devices` where `user_id` = $user_id ORDER BY `id` DESC LIMIT 15");

    return $rows;


  }
  else {
    return false;
  }

 }


 public function checkIfratedByUser($user_id,$order_id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `rate_full_order` where `user_id` = $user_id AND `order_id` = $order_id");

    $isRated = true;
    if(sizeof($rows)==0)
    $isRated = false;

    return $isRated;


  }
  else {
    return false;
  }

 }




 public function getAllOrdersToUserID($user_id) {

   date_default_timezone_set('Asia/Jerusalem');

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `ordars` WHERE `user_id` = $user_id ORDER BY `id` DESC");


    $UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("Asia/Jerusalem");

$date= date("Y-m-d H:i:s");
$date = new DateTime( $date, $UTC );
$date->setTimezone( $newTZ );

    if(sizeof($rows)>0){
      $final_arr=array();
      $temp=array();
    foreach ($rows as $key) {


      $payment_arr = $this -> getOnePaymentMethodsByID($key['payment_methods']);
      $address_arr = $this -> getOneAddressByID($key['address_id']);


      $status_name="";

      if($key['address_id']==0 or $key['address_id']==-1)
      $withDelevery = false;
      else {
        $withDelevery = true;
      }

      if($key['order_status']==0)
      $status_name="تم استلام طلبكم";

      if($key['order_status']==1)
      $status_name="قيد التنفيذ";

      if($key['order_status']==2){

        if($withDelevery)
      $status_name="قيد التوصيل";
      else {
        $status_name="طلبكم جاهز في مارنا هاوس";
      }


    }

      if($key['order_status']==5)
      $status_name="تم تسليم الطلبية بنجاح";

      if($key['order_status']==6)
      $status_name="طلبية مرفوضة";




      $final_arr['id'] = (int) $key['id'];
      $final_arr['user_id'] = $key['user_id'];
      $final_arr['payment_method_id'] = (int) $key['payment_methods'];
      $final_arr['payment_method_txt_ar'] = $payment_arr[0]['payment_name_ar'];
      $final_arr['payment_method_txt_en'] = $payment_arr[0]['payment_name_en'];
      $final_arr['delevary_type_id'] = 0;
      $final_arr['address_id'] = (int) $key['address_id'];
      $final_arr['address_title'] = $address_arr[0]['address_name'];
      $final_arr['price'] = $key['price'];
      $final_arr['order_text_status_ar'] =$status_name;
      $final_arr['order_text_status_en'] = $status_name;
      $final_arr['isRated'] = $this -> checkIfratedByUser($key['user_id'],$key['id']);
      $final_arr['withDelivary'] = $withDelevery;
      $final_arr['order_status'] = (int) $key['order_status'];


      $date= date("Y-m-d H:i:s");

      $date=$key['date'];

      $final_arr['order_datetime'] = $date;

      $minFromDB = $this -> getOOrderSettingByNamE('time_delevery');
      $minutes_to_add = $minFromDB[0]['value'];



      $time = new DateTime($date);
      $time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

      $stamp = $time->format('Y-m-d H:i:s');

      $final_arr['order_delivered_datetime'] = $stamp;




      $final_arr['items'] = $this -> getCartPordactForUserIDandOrderID($key['user_id'],$key['id']);
      array_push($temp,$final_arr);

    }

    $rows = $temp;


  }


    return $rows;


  }
  else {
    return false;
  }

 } // end function





 public function getAllMesgFroUserID($user_id) {

   date_default_timezone_set('Asia/Jerusalem');

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `msgs` WHERE `from_user_id` = $user_id OR `to_user_id` = $user_id ORDER BY `id` DESC");


    $UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("Asia/Jerusalem");

$date= date("Y-m-d H:i:s");
$date = new DateTime( $date, $UTC );
$date->setTimezone( $newTZ );

    if(sizeof($rows)>0){
      $final_arr=array();
      $temp=array();
    foreach ($rows as $key) {
      $final_arr['id'] = (int) $key['id'];
      $final_arr['from_user_id'] = (int) $key['from_user_id'];
      $final_arr['to_user_id'] = (int) $key['to_user_id'];
      $user_arr = $this->getUserLogin($final_arr['from_user_id']);

      if(sizeof($user_arr)>0){
        $name = $user_arr[0][name];
      }
      else {
        $name = "Marna House";
      }


      $final_arr['from_user_name'] = $name;
      $user_arr = $this->getUserLogin($final_arr['to_user_id']);


      if(sizeof($user_arr)>0){
        $name = $user_arr[0][name];
      }
      else {
        $name = "Marna House";
      }


      $final_arr['to_user_name'] = $name;
      $final_arr['session_id'] = 0;
      $final_arr['subject'] = $key['subject'];
      $final_arr['msg'] = $key['msg'];
      $final_arr['read'] = (int) $key['read'];
      $final_arr['status'] = (int) $key['status'];
      $final_arr['type'] = $key['type'];
      $final_arr['date'] = $key['date'];

      array_push($temp,$final_arr);

    }

    $rows = $temp;


  }


    return $rows;


  }
  else {
    return false;
  }

 } // end function





 public function getUserJob() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `job` ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function

 public function getSetting() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `setting` ");

    return $rows;


  }
  else {
    return false;
  }

 } // end function
 public function getAllOffers() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `offers` WHERE `offer_status` = 1 ORDER BY `sort` ASC");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getAllOffersv2() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `offersv2` WHERE `offer_status` = 1 ORDER BY `sort` ASC");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getAllHalls() {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `rooms` WHERE `room_status` = 1 ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function



 public function getAllMenuItemsByCatID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `menu_items` WHERE `online` = 1 AND `item_cat` = $id ORDER BY `item_number`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function





 public function getCartPordactForUserIDandOrderID($useridd,$ordidd) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `cart` WHERE `user_id` = $useridd AND `order_id` = $ordidd  ORDER BY `id` DESC");

    if(sizeof($rows)>0){

      $arr =  array();
      $final =  array();

      foreach ($rows as $key) {

        $item_id_fromDB = $key['item_id'];

        $rows2 = $db -> select("SELECT * FROM `menu_items` WHERE `id` = $item_id_fromDB LIMIT 1");



        $arr['id'] = (int) $rows2[0]['id'];
        $arr['item_cart_id'] = (int) $rows2[0]['id'];
        $arr['item_number'] = (int)  $rows2[0]['item_number'];
        $arr['item_name_ar'] = $rows2[0]['item_name_ar'];
        $arr['item_name_en'] = $rows2[0]['item_name_en'];
        $arr['item_body_ar'] = $rows2[0]['item_body_ar'];
        $arr['item_body_en'] = $rows2[0]['item_body_en'];
        $arr['item_price'] = $rows2[0]['item_price'];
        $arr['item_cat'] = $rows2[0]['item_cat'];
        $arr['date'] = $rows2[0]['date'];


        $sid = md5($rows2[0]['photo']);

        $arr['photo'] = "http://app.marnahouse.ps/api/?sid=".$sid."&api_data=ac45375cc4744b9a8bc89ae0bad6f15d&action=getIitemPhoto&id=".$rows2[0]['id'];
        $arr['online'] = $rows2[0]['online'];
        $arr['OptionsList'] = json_decode($key['item_options_obj']);

        array_push($final,$arr);

      }

      $rows = $final;

    }



    return $rows;


  }
  else {
    return false;
  }

 } // end function



 public function getItemsReadyForOrdersByUserID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `menu_items` WHERE `online` = 1 AND `item_cat` = $id ORDER BY `item_number`");

    if(sizeof($rows)>0){

      $arr =  array();
      $final =  array();

      foreach ($rows as $key) {

        $arr['id'] = (int) $key['id'];
        $arr['item_cart_id'] = (int) $key['id'];
        $arr['item_number'] = (int)  $key['item_number'];
        $arr['item_name_ar'] = $key['item_name_ar'];
        $arr['item_name_en'] = $key['item_name_en'];
        $arr['item_body_ar'] = $key['item_body_ar'];
        $arr['item_body_en'] = $key['item_body_en'];
        $arr['item_price'] = $key['item_price'];
        $arr['item_cat'] = $key['item_cat'];
        $arr['date'] = $key['date'];


        $sid = md5($key['photo']);

        $arr['photo'] = "http://app.marnahouse.ps/api/?sid=".$sid."&api_data=ac45375cc4744b9a8bc89ae0bad6f15d&action=getIitemPhoto&id=".$key['id'];
        $arr['online'] = $key['online'];
        $arr['OptionsList'] = array();

        array_push($final,$arr);

      }

      $rows = $final;

    }



    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getAllOptionForOneItemByItemID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `item_options` WHERE `item_id` = $id ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getAllImagesForPageByPageID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `photos` WHERE  `cat_id` = $id ORDER BY `id`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function


 public function getPageInfoByID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `pages` WHERE  `id` = $id ");

    return $rows;


  }
  else {
    return false;
  }

 } // end function




 public function CheckAPIDATA($password) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
   // $rows = $db -> select("SELECT * FROM `api_data` WHERE `password` = '$password' AND `status` = 1");




    return true;


  }
  else {
    return false;
  }

} // end function


public function userFormData($name,$email,$password) {

if($this -> checkUserIsLogdedIn()== true){
  $date= date("Y-m-d H:i:s");
  $db = new Db();

  $result = $db -> query("INSERT INTO `user_login` ( `name`, `email`,`password`, `date`) VALUES
  ( '$name', '$email', '$password', '$date')");
    $id= mysqli_insert_id($db->getCon());


      $result3 = $db -> query("INSERT INTO `users_profile` ( `user_id`,`marna_id`,`job`, `gender`,`birthday`, `mobile_no`,`photo`,`haweya`, `status`, `date`) VALUES
      ( $id, '','', '','','','', '','', '$date')");


  return $id;
}
else {
  return false;
}

} // end of class


public function userVerifyData($user_id,$email,$code,$status) {

if($this -> checkUserIsLogdedIn()== true){
  $date= date("Y-m-d H:i:s");
  $db = new Db();

  $result = $db -> query("INSERT INTO `user_verify` (`user_id`, `email`, `code`,`status`, `date`) VALUES
  ( '$user_id', '$email', '$code', '$status', '$date')");
  return $result;
}
else {
  return false;
}

} // end of class

public function getVerifyByCode($passkey) {

 if($this -> checkUserIsLogdedIn()== true){

   $db = new Db();
   $rows = $db -> select("SELECT * FROM `user_verify` WHERE `code` = '$passkey'");

   return $rows;


 }
 else {
   return false;
 }

} // end function



public function updateUserVerified($email,$user_id) {

 if($this -> checkUserIsLogdedIn()== true){

   $db = new Db();

   $result = $db -> query("UPDATE `user_login` SET `verified`= '1', `status` = '1' WHERE `email` = '$email' and `id`= $user_id");
   return $result;

 }
 else {
   return false;
 }
} // end function

public function deleteVerifyRow($passkey) {

 if($this -> checkUserIsLogdedIn()== true){

   $db = new Db();

   $result = $db -> query("DELETE FROM `user_verify` WHERE `code` = '$passkey'");
   return $result;

 }
 else {
   return false;
 }
} // end function


public function postMobileData($form_data) {

 if(true){
$date=date("Y-m-d H:i:s");
   $db = new Db();

   $result = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");
   return $result;

 }
 else {
   return false;
 }
} // end function



public function addNewRate($user_id,$item_id,$rate,$comments) {

 if(true){
$date=date("Y-m-d H:i:s");
   $db = new Db();


   $rows = $db -> select("SELECT * FROM `rates` where `item_id` =  $item_id AND `user_id` = $user_id ");
   if(sizeof($rows)> 0){
     $result = false;
   }
else {
  $result = $db -> query("INSERT INTO `rates` ( `user_id`, `item_id`, `rate`, `type`, `comments`, `date`, `status`) VALUES ( $user_id, $item_id, $rate, 'menu','$comments','$date',0)");
}
   return $result;

 }
 else {
   return false;
 }
} // end function



public function setPoints($user_id,$points,$cashback,$disc) {

 if(true){
  $date=date("Y-m-d H:i:s");
   $db = new Db();

   $result = $db -> query("INSERT INTO `points` (`marna_id`, `marna_points`,`marna_disc`,`marna_cash_back`,`marna_other_disc`,`date`) VALUES ($user_id,$points,'$disc','$cashback','0','$date')");
   return $result;

 }
 else {
   return true;
 }
} // end function




public function mobileFormData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $rows = $db -> select("SELECT * FROM `user_form` where `device_id` =  '$arr->device_id' ");
  if(sizeof($rows)> 0){
    $result2 = $db -> query("UPDATE `user_form` SET `fname`='$arr->fname', `mname`='$arr->mname', `lname`='$arr->lname', `marna_id`='$arr->marna_id', `job`='$arr->job', `gender`='$arr->gender',
       `birthday`='$arr->birthday', `email`='$arr->email', `mobile_no`='$arr->mobile_no', `city`='$arr->city',  `region`='$arr->region', `address`='$arr->address',`device_type`='$arr->type', `status`='1',`date`='$date'
        WHERE `device_id` = '$arr->device_id'");
  return $result2;

  }else{

  $result3 = $db -> query("INSERT INTO `user_form` ( `fname`, `mname`,`lname`, `marna_id`,`job`, `gender`,`birthday`,`email`, `mobile_no`,`city`, `region`,`address`,`device_id`, `device_type`,`status`, `date`) VALUES
  ( '$arr->fname', '$arr->mname','$arr->lname', '$arr->marna_id','$arr->job', '$arr->gender','$arr->birthday','$arr->email', '$arr->mobile_no','$arr->city',
     '$arr->region','$arr->address','$arr->device_id', '$arr->type','1', '$date')");
  return $result3;
}
}
else {

  return false;
}


}





public function updateDeviceCloudID($user_id,$device_cloud_id,$device_name,$device_type) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();

  $result1 = $db -> query("INSERT INTO `devices` (`user_id`, `device_cloud_id`, `device_name`, `device_type`, `date`) VALUES ($user_id,'$device_cloud_id','$device_name','$device_type','$date')");
  return true;
}
else {

  return false;
}


}






public function getAllUserData($user_id){
  $user_result = array();

  $u_result =    $this->getUserLogin($user_id);
 $profile_result =    $this->getProfileByUserID($user_id);
  $address_result =    $this->getUserAddressByUserId($user_id);
  $gps_result =    $this->getUserGpsByUserId($user_id);
  $devices_result =    $this->getUserDevicesByUserId($user_id);

  $points_results = $this->getPointsByMarnaID($profile_result[0][marna_id]);

  $user_result["user_login"]= $u_result;
  $user_result["userProfile"]= $profile_result;
  $user_result["marnaData"]= $points_results;
  $user_result["userAddress"]=   $address_result;
  $user_result["userGps"]=   $gps_result;
  $user_result["userDevices"]= $devices_result;

   return  $user_result;

}

public function mobileFormDatav2($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);
  $birthday1=$arr->birthday;

$birthday = date("Y-m-d",strtotime(str_replace('/','-',$birthday1)));

$city_name = $this -> getCityByID($arr->city);
$regon_name = $this -> getRegonByID($arr->region);

//if(sizeof($city_name) > 0 and sizeof($regon_name) >0 ){
$final_address_with_txt = $city_name[0][city_name_ar].' - '.$regon_name[0][name_ar].' - '.$arr->address;

//$result5 = $db -> query("INSERT INTO `user_address` ( `user_id`,`address_name`, `city_id`,`region_id`,`address_txt`,`status`,`date`) VALUES ( $arr->user_id, 'Profile Address','$arr->city','$arr->region','$arr->address','1','$date')");
//}


  $rows = $db -> select("SELECT * FROM `users_profile` where `user_id` =  $arr->user_id ");
  if(sizeof($rows)> 0){
    $result2 = $db -> query("UPDATE `users_profile` SET `marna_id`='$arr->marna_id', `job`='$arr->job', `gender`='$arr->gender',
       `birthday`='$birthday',  `mobile_no`='$arr->mobile_no',  `photo`='$arr->photo',`haweya`='$arr->haweya', `status`='$arr->status',`date`='$date'
        WHERE `user_id` = $arr->user_id");
  $result3=  $db -> query("UPDATE `user_login` SET `name`='$arr->name' WHERE `id` = $arr->user_id");

  return $id;

  }else{

  $result3 = $db -> query("INSERT INTO `users_profile` ( `user_id`,`marna_id`,`job`, `gender`,`birthday`, `mobile_no`,`photo`,`haweya`, `status`, `date`) VALUES
  ( '$arr->user_id', '$arr->marna_id','$arr->job', '$arr->gender','$birthday','$arr->mobile_no','$arr->photo', '$arr->haweya','$arr->status', '$date')");
  return $result3;
}
}
else {

  return false;
}


}

public function mobileFormDataByIdv2($user_id,$up) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();


  $rows = $db -> select("SELECT * FROM `users_profile` where `user_id` =  '$user_id' ");
  if(sizeof($rows)> 0){
    $result2 = $db -> query("UPDATE `users_profile` SET  `photo`='$up'  WHERE `user_id` = $user_id");

  return $id;

  }else{

  $result3 = $db -> query("INSERT INTO `users_profile` ( `user_id`,`photo`, `date`) VALUES
  ( '$user_id', '$Up', '$date')");
  return $result3;
}
}
else {

  return false;
}


}

public function addAddressData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result3 = $db -> query("INSERT INTO `user_address` ( `user_id`,`address_name`,`city_id`, `region_id`,`address_txt`,`status`, `date`) VALUES
  ( '$arr->user_id', '$arr->address_name','$arr->city_id', '$arr->region_id','$arr->address_txt','$arr->status', '$date')");
  return $result3;

}
else {

  return false;
}
}



public function deleteUserAdressData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);
  $id = $arr->address_id;

  $result3 = $db -> query("DELETE FROM `user_address` WHERE `id` = $id");

  return $result3;

}
else {

  return false;
}
}


public function deleteMsgByMSGID($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);
  $id = $arr->msg_id;

  $result3 = $db -> query("DELETE FROM `msgs` WHERE `id` = $id");

  return $result3;

}
else {

  return false;
}
}






public function addFullDataByAction($form_data,$type) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `action_logs` ( `type`, `data`,`device_hedar`,`device_ip`,`date`) VALUES ( '$type', '$form_data','headr','USER_IP','$date')");


if($type=="addNewOrder"){


  $arr = json_decode($form_data);

  $user_id = $arr->userId;
  $paymentMethodId = $arr->paymentMethodId;
  $addressId = $arr->addressId;
  $price = $arr->price;
  $cartProducts = $arr->cartProducts;
  
  $tableNumber = $arr->tableNumber;

  $ar_status = "تم استلام الطلب";
  $en_status = "Order Accepted";

  $date=date("Y-m-d H:i:s");


  $result1 = $db -> query("INSERT INTO `ordars` ( `user_id`, `payment_methods`,`delevary_type_id`,`address_id`,`price`,`order_text_status_ar`,`order_text_status_en`,`order_status`,`date`)
  VALUES ( $user_id, $paymentMethodId,0,$addressId,'$price','$ar_status','$en_status',0,'$date')");


  $paymentMName= $this -> getOnePaymentMethodsByID($paymentMethodId);

  $payName = $paymentMName[0][payment_name_ar];

  $user_name_arr = $this -> getUserLogin($user_id);
  $userName= $user_name_arr[0][name];

  $pofile_arr = $this -> getProfileByUserID($user_id);
  $marna_id = $pofile_arr[0][marna_id];
  $mobileNO = $pofile_arr[0][mobile_no];

  $OrderID = $db -> select("SELECT * FROM `ordars` WHERE `user_id` = $user_id ORDER BY `id` DESC LIMIT 1");
  $OrderIDNumber = $OrderID[0]['id'];
  
  $realTablearr= $db -> select("SELECT * FROM `tables` WHERE `id` = $tableNumber");
  $realTableNumber = $realTablearr[0]['table_number'];
  $realTableNameAr = $realTablearr[0]['table_name_ar'];


  $marna_ord_arr = array();

  foreach ($cartProducts as $cart ) {

    $temp_arr = array();

    $cart     = get_object_vars($cart);

    $date=date("Y-m-d H:i:s");
    //$obtion_json = $cart[cartItemOptions];
    $item_id = $cart['itemId'];

    $itemData_arr2 = $this -> getPhotoByItemID($item_id);
    $item_number = $itemData_arr2[0][item_number];
    $item_name = $itemData_arr2[0][item_name_ar];

    $cartItemPrice = $cart['cartItemPrice'];
    $cartItemQuntity = $cart['cartItemQuntity'];
    $cartItemOptions = json_encode($cart['cartItemOptions'],JSON_UNESCAPED_UNICODE);

    $result1 = $db -> query("INSERT INTO `cart` ( `user_id`, `order_id`,`item_id`,`item_price`,`item_quntity`,`item_options_obj`,`status`,`date`)
    VALUES ( $user_id, $OrderIDNumber,$item_id,'$cartItemPrice','$cartItemQuntity','$cartItemOptions',0,'$date')");




    $optionToIntert = "";

    $arr = json_decode($cartItemOptions);
    foreach ($arr as $key) {
      $optionToIntert = $optionToIntert.$key->option_name_ar.', ';
    }
    if(sizeof($arr)==0) $optionToIntert = "بدون اضافات";


    $address_to_instaert = "الاستلام في المارنا هاوس";

    if($addressId==0 or $addressId==-1 or $addressId==-2){
      $address_to_instaert = "الاستلام في المارنا هاوس";
      
      if($addressId==-2)
      $address_to_instaert =  "طلب على الطاولة رقم: ". $realTableNumber.' - '.$realTableNameAr;
    }
      else {

          $address_arr = $this -> getOneAddressByID($addressId);


          $city = $this -> getCityByID($address_arr[0]['city_id']);

          $reg = $this -> getRegionByID2($address_arr[0]['region_id']);




          $address_to_instaert = $city[0][city_name_ar].' ~ '.$reg[0][name_ar].' ~ '.$address_arr[0][address_name].' ~ '.$address_arr[0][address_txt].'';

      }


      $result1 = $db -> query("INSERT INTO `marna_order` ( `order_id`, `full_name`,`marna_id`,`date_time`,`payment_method_txt`,`mobile`,`item_number`,`item_name`,`quntaty`,`item_option_txt`,`delevery_address_txt`,`date`,`status`)
      VALUES ( $OrderIDNumber, '$userName',$marna_id,'$date','$payName','$mobileNO','$item_number','$item_name','$cartItemQuntity','$optionToIntert','$address_to_instaert','$date',0)");


      $temp_arr[order_id] = $OrderIDNumber;
      $temp_arr[user_name] = $userName;
      $temp_arr[marna_id] = $marna_id;
      $temp_arr[date_time_order] = $date;
      $temp_arr[pay_name] = $payName;
      $temp_arr[mobile_no] = $mobileNO;
      $temp_arr[item_number] = $item_number;
      $temp_arr[item_name] = $item_name;
      $temp_arr[quntity] = $cartItemQuntity;
      $temp_arr[options] = $optionToIntert;
      $temp_arr[address] = $address_to_instaert;

      array_push($marna_ord_arr,$temp_arr);



  }

  $from_data_json = json_encode($marna_ord_arr,JSON_UNESCAPED_UNICODE);
  $from_data_json = urlencode($from_data_json);


  $url = "http://213.6.134.34/?api_data=ac45375cc4744b9a8bc89ae0bad6f15d&action=setOrderOnMarna&form_data=".$from_data_json;

  try {

  $InertDATAtoMarnaServer =  @file_get_contents($url);
} catch (Exception $e) {
    $InertDATAtoMarnaServer =  "false";
}


  if($InertDATAtoMarnaServer!="true"){

      $x = $db -> query("DELETE FROM `ordars` WHERE `id` = $OrderIDNumber");
      $x = $db -> query("DELETE FROM `cart` WHERE `order_id` = $OrderIDNumber");
  }


  $result1 = $InertDATAtoMarnaServer ;











}// end of addNewOrder



if($type=="addNewMessage"){

  $date=date("Y-m-d H:i:s");


  $arr = json_decode($form_data);

  $f_user_id = $arr->user_id;
  $subject = $arr->msg_subject;
  $msg = $arr->msg_txt;

  $result1 = $db -> query("INSERT INTO `msgs` ( `from_user_id`, `to_user_id`,`session_id`,`subject`,`msg`,`read`,`status`,`type`,`date`)
  VALUES ( $f_user_id, 0,0,'$subject','$msg',0,0,'GM','$date')");



} //end read msg


if($type=="ReadMessage"){


  $arr = json_decode($form_data);

  $msg_id = $arr->id;

  $result1 = $db -> query("UPDATE `msgs` SET `read` = 1 WHERE `id` = $msg_id");




} //end read msg


if($type=="rateOrder"){


  $arr = json_decode($form_data);
  $date=date("Y-m-d H:i:s");

  $user_id = $arr->userId;
  $order_id = $arr->orderId;
  $orderComment = $arr->orderComment;
  $orderRate = $arr->orderRate;
  $delivaryComment = $arr->orderDeliveryComment;
  $delivaryRate = $arr->orderDeliveryRate;
  $rateItemsObj = $arr->toRateItems;
  $rateItemsObj = json_encode($rateItemsObj,JSON_UNESCAPED_UNICODE);

  $result1 = $db -> query("INSERT INTO
    `rate_full_order`(`user_id`, `order_id`, `orderComment`, `orderRate`, `delivaryComment`, `delivaryRate`, `rateItemsObj`, `status`, `date`)
            VALUES ($user_id,$order_id,'$orderComment','$orderRate','$delivaryComment','$delivaryRate','$rateItemsObj','0','$date')");

$msgto_admin = "رقم الطلبية: "."<a target=_blank href=?action=show_order&order_id=".$order_id." >".$order_id."</a><br>";
$msgto_admin = $msgto_admin . "تقييم الطلب اجمالا من ٥: ".$orderRate."<br>";
$msgto_admin = $msgto_admin . "تعليقات على الطب: ".$orderComment."<br>";
$msgto_admin = $msgto_admin . "<hr><br>";
$msgto_admin = $msgto_admin . "تقييم التوصيل ان وجد من ٥ : ".$delivaryRate."<br>";
$msgto_admin = $msgto_admin . "تعليق على التوصل ان وجد: ".$delivaryComment."<br>";

$msg_arr = $this -> addMsgFromAPI($user_id,0,$msgto_admin,"تقييم طلبية رقم: ".$order_id);


} //end read msg



  return $result1;

}
else {

  return false;
}
}



public function getRegionByID2($region_id) {

 if($this -> checkUserIsLogdedIn()== true){

   $db = new Db();
   $rows = $db -> select("SELECT * FROM `region` where `id` = '$region_id' ");

   return $rows;


 }
 else {
   return false;
 }

}


public function editUserAddress($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result2 = $db -> query("UPDATE `user_address` SET `user_id` = '$arr->user_id', `address_name`='$arr->address_name', `city_id`='$arr->city_id', `region_id`='$arr->region_id',
     `address_txt`='$arr->address_txt', `status`='$arr->status',`date`='$date' WHERE `id` = $arr->address_id");
  return $result2;

}
else {

  return false;
}
}


public function addGpsData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result3 = $db -> query("INSERT INTO `user_gps` ( `user_id`,`latitude`,`longitude`, `address_id`,`status`, `date`) VALUES
  ( '$arr->user_id', '$arr->latitude','$arr->longitude', '$arr->address_id','$arr->status', '$date')");
  return $result3;

}
else {

  return false;
}
}

public function editGpsData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result2 = $db -> query("UPDATE `user_gps` SET  `user_id` = '$arr->user_id', `latitude`='$arr->latitude', `longitude`='$arr->longitude', `address_id`='$arr->address_id',
     `status`='$arr->status',`date`='$date' WHERE `id` = $arr->id");
  return $result2;

}
else {

  return false;
}
}

public function addDeviceData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result3 = $db -> query("INSERT INTO `user_devices` ( `user_id`,`device_name`,`device_type`, `device_os`,`device_uniqe_id`, `device_cloud_id`,`status`, `date`) VALUES
  ( '$arr->user_id', '$arr->device_name','$arr->device_type', '$arr->device_os','$arr->device_uniqe_id', '$arr->device_cloud_id','$arr->status', '$date')");
  return $result3;

}
else {

  return false;
}
}

public function editDeviceData($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result2 = $db -> query("UPDATE `user_devices` SET `user_id` = '$arr->user_id',`device_name`='$arr->device_name', `device_type`='$arr->device_type', `device_os`='$arr->device_os',
     `device_uniqe_id`='$arr->device_uniqe_id', `device_cloud_id`='$arr->device_cloud_id',`status`='$arr->status',`date`='$date' WHERE `id` = $arr->id");
  return $result2;

}
else {

  return false;
}
}

public function updateUserPassword($form_data) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();
  $result1 = $db -> query("INSERT INTO `mobile_form_data` ( `form_data`, `date`) VALUES ( '$form_data', '$date')");

  $arr = json_decode($form_data);

  $result2 = $db -> query("UPDATE `user_login` SET `password` = '$arr->new_password' WHERE `id` = $arr->user_id");
  return $result2;

}
else {

  return false;
}
}


public function updateUserVerifiedStatus($user_id, $status) {

if($this -> checkUserIsLogdedIn()== true){
  $date=date("Y-m-d H:i:s");
  $db = new Db();

  $result2 = $db -> query("UPDATE `users_profile` SET `abroval` = $status WHERE `user_id` = $user_id");
  return $result2;

}
else {

  return false;
}
}




 function uploadImage($files) {

  $target_dir = "../uploads/";

  $finalFilename = md5(date("Y-m-d H:i:s")) .basename($files["fileToUpload"]["name"]);

  $target_file = $target_dir . $finalFilename;


  $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "PNG" ) {
    //  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
  }
  // Check if $uploadOk is set to 0 by an error
  if ($uploadOk == 0) {

  return false;

  } else {
  $images= $files["fileToUpload"]["tmp_name"];
  $width=150;
  $size=GetimageSize($images);
  $height=round($width*$size[1]/$size[0]);
  if($imageFileType == "jpg" or $imageFileType == "jpeg" && $imageFileType == "JPG" ){
  $images_orig = ImageCreateFromJPEG($images);
}elseif( $imageFileType == "png" or $imageFileType == "PNG"){
  $images_orig = ImageCreateFrompng($images);
}
  $photoX = ImagesX($images_orig);
  $photoY = ImagesY($images_orig);
  $images_fin = ImageCreateTrueColor($width, $height);
  ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
  ImageJPEG($images_fin,$target_file);
  ImageDestroy($images_orig);
  ImageDestroy($images_fin);

        return $finalFilename;

  }


}







///////// PCHR//////



 
 
 public function getUserByID($id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `users` WHERE `id` = '$id'");

    return $rows;


  }
  else {
    return false;
  }

 } // end function
 
 
 
 public function getTableData($table) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `$table`");

    return $rows;


  }
  else {
    return false;
  }

 } // end function
 
 
 public function getSuns($cont_id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `city` WHERE `districtid` = $cont_id");

    
    
    

    return $rows;


  }
  else {
    return false;
  }

 } // end function
 
 
 
 public function getD($cont_id) {

  if($this -> checkUserIsLogdedIn()== true){

    $db = new Db();
    $rows = $db -> select("SELECT * FROM `district` WHERE `country` = $cont_id");
    
    
    
    
    $darr = array();
    
    foreach ($rows as $r){
        
        $temp = array(
            
            "id" => $r['id'],
            "name" => $r['name'],
            "sun" => $this -> getSuns($r['id']),
            
            );
            
             array_push($darr,$temp);  
        
    }
    
    

    return $darr;


  }
  else {
    return false;
  }

 } // end function
 
 
 
 public function mobile_log($u,$k,$form_data) {

 if(true){
$date=date("Y-m-d H:i:s");
   $db = new Db();

   $result = $db -> query("INSERT INTO `mobile_log` ( `user_id`, `form_key`,`form_data`,`indate`) VALUES ( $u, '$k','$form_data','$date')");
   return $result;

 }
 else {
   return false;
 }
} // end function



public function update_form($form_id,$form_data) {

 if(true){
$date=date("Y-m-d H:i:s");
   $db = new Db();

   //$result = $db -> query("INSERT INTO `mobile_log` ( `user_id`, `form_key`,`form_data`,`indate`) VALUES ( $u, '$k','$form_data','$date')");
   
   $result2 = $db -> query("UPDATE `mobile_log` SET  `form_data`= '$form_data', `status` = 0 WHERE `id` = $form_id");
   return $result2;

 }
 else {
   return false;
 }
} // end function



public function formsList($u) {

 if(true){


    $db = new Db();
    $rows = $db -> select("SELECT * FROM `mobile_log` WHERE `user_id` = $u ORDER BY `id` DESC");
    
    
   return $rows;

 }
 else {
   return false;
 }
} // end function


public function formsListWithSatatus($u,$status) {

 if(true){


    $db = new Db();
    $rows = $db -> select("SELECT * FROM `mobile_log` WHERE `user_id` = $u and `status` = $status ORDER BY `id` DESC");
    
    
   return $rows;

 }
 else {
   return false;
 }
} // end function




public function search($u,$q) {

 if(true){


    $db = new Db();
    $rows = $db -> select("SELECT * FROM `mobile_log` WHERE `form_data` LIKE '%$q%'");
    
    
   return $rows;

 }
 else {
   return false;
 }
} // end function


public function searchfull($u,$q) {

 if(true){


    $db = new Db();
    $rows = $db -> select("SELECT * FROM `person` WHERE `name` LIKE '%$q%' OR `identity` LIKE '%$q%' limit 50");
    
    
   return $rows;

 }
 else {
   return false;
 }
} // end function




} // end of class


 ?>
