<?php

	class Order {
		protected $db;
		
		public function __construct($connection) {
			$this->db = $connection;
		}
		
		public function updateOrders() {

			global $db;
			
			if(API_STATUS) {
				$datas = $this->db->query("SELECT A.api_url, A.api_key, O.api_id, GROUP_CONCAT(O.api_order_id) AS orders FROM `orders` AS O INNER JOIN `apis` AS A ON A.api_id = O.api_id WHERE O.order_status != 'Partial' AND O.order_status != 'Canceled' AND O.order_status != 'Completed' GROUP BY O.api_id")->fetchAll(PDO::FETCH_ASSOC);
				
				
				foreach($datas as $data) {
					
					if($data["orders"] != null) {
						$orders = update_orders($data["api_url"], $data["api_key"], $data["orders"]);
						
						if($orders) {
							
							foreach($orders as $order => $details) {
								
								if(!isset($details["error"])) {

									if($details['status'] == "Canceled"){

										$orderQuery = $this->db->from('orders')->where('api_order_id', $order)->first();

										$query = $this->db->update('orders')
										->where('api_id', $data['api_id'])
										->where('api_order_id', $order)
										->set(array(
											'api_order_amount' => $details["charge"],
											'api_order_currency' => $details["currency"],
											'order_status' => $details["status"],
											'order_start_count' => $details["start_count"],
											'order_remains' => $details["remains"],
											'update_date' => time(),
											'order_detail' => json_encode($orders),
											'order_amount' => 0
										));

										$user = $this->db->from('users')->where('user_id', $orderQuery['user_id'])->first();
										$newBalance = $user['user_balance']+$orderQuery['order_amount'];

										$updateBalance = $this->db->update('users')
										->where('user_id', $orderQuery['user_id'])
										->set(array(
											'user_balance' => $newBalance
										));

										if($updateBalance && $query){
											user_spent("cikar", $user['user_username'], $orderQuery['order_amount']);
											echo "OK1";
										}else{
											echo "ERROR3";
										}

									}elseif($details['status'] == "Partial"){

										$orderQuery = $this->db->from('orders')->where('api_order_id', $order)->first();
										$user = $this->db->from('users')->where('user_id', $orderQuery['user_id'])->first();

										$price  		= $orderQuery["order_amount"]/$orderQuery["order_quantity"]; 	## 1 adet kaç TL
			            				$return 		= $price*$details["remains"]; 			
							            $balance 		= $user["user_balance"]+$return; 								## Üye yeni bakiye
							           // $remainsOrder 	= $orderQuery["order_quantity"]-$remains; 				## Yeni sipariş miktarı
							            $charge 		= $orderQuery["order_amount"]-$return; 					## Sipariş yeni tutar


										$query = $this->db->update('orders')
										->where('api_id', $orderQuery['api_id'])
										->where('api_order_id', $order)
										->set(array(
											'api_order_amount' => $details["charge"],
											'api_order_currency' => $details["currency"],
											'order_status' => $details["status"],
											'order_start_count' => $details["start_count"],
											'order_remains' => $details["remains"],
											'update_date' => time(),
											'order_detail' => json_encode($orders),
											'order_amount' => $charge
										));

										$updateBalance = $this->db->update('users')
										->where('user_id', $orderQuery['user_id'])
										->set(array(
											'user_balance' => $balance
										));

										if($updateBalance && $query){
											user_spent("cikar", $user['user_username'], $return);
											echo "OK2";
										}else{
											echo "ERROR2";
										}
										
									}else{
										$api_order_status = $details['status'];
										$api_order_status = str_replace("Inprogress", "In progress", $api_order_status);
										
										$query = $this->db->update('orders')
										->where('api_id', $data['api_id'])
										->where('api_order_id', $order)
										->set(array(
											'api_order_amount' => $details['charge'],
											'api_order_currency' => $details['currency'],
											'order_status' => $api_order_status,
											'update_date' => time(),
											'order_start_count' => $details['start_count'],
											'order_remains' => $details['remains'],
											'order_detail' => json_encode($orders)
										));
										
                                        echo "OK3";
									}
									
								} else {
									echo $details["error"];
								}
							}
						}else{
						    echo "ERROR1 ";
						}
					}
				}
			}
		}
		
		public function returnOrders() {

			$orders = $this->db->from('orders')->where('order_status', 'Partial')->where('order_status', 'Canceled')->where('order_return', 0)->all();

			foreach($orders as $order) {

				$user = $this->db->from('users')->where('user_id', $order['user_id'])->first();

				if($user) {

					if($order["order_status"] == "Canceled") {

						$new_balance = $user['user_balance'] + $order['order_amount'];

						$update_user = $this->db->update('users')->where('user_id', $order['user_id'])
						->set(array(
							'user_balance' => $new_balance
						));

						$update_order = $this->db->update('orders')->where('order_id', $order['order_id'])
						->set(array(
							'order_return' => 1,
							'is_failed' => 0
						));
						
						

						if($update_user && $update_order) {
						user_spent("cikar", $user['user_username'], $order['order_amount']);
							echo "success no:5";
						} else {
							echo "error no:5";
						}


					}
				}
			}
		}
	}