<?php

function add_order($service, $user_id, $link, $quantity, $amount, $comments = null, $runs = null, $interval = null)
{

	global $db, $NotifySettings, $settings;
	$order = null;
	if (API_STATUS && $service["api_id"] != null && $service["api_service"] != null) {
		$api = $db->query("SELECT * FROM `apis` WHERE api_id = $service[api_id]")->fetch(PDO::FETCH_ASSOC);
		if ($api) {

			if ($comments == null) {
				if ($runs != null && $interval != null) {
					$order = send_order_default($api["api_url"], $api["api_key"], $service["api_service"], $link, $quantity);
					$orderdetail = json_encode($order);
					if ($order->order) {

						$insert_order = $db->insert('orders')
							->set(array(
								'api_id' => $api["api_id"],
								'api_order_id' => $order->order,
								'user_id' => $user_id,
								'service_id' => $service["service_id"],
								'order_type' => 1,
								'order_date' => time(),
								'order_link' => $link,
								'order_quantity' => $quantity,
								'order_amount' => ($amount / $runs),
								'order_remains' => $quantity,
								'order_detail' => $orderdetail
							));

						if ($insert_order) {
							$order = $db->lastInsertId();
							$query = $db->prepare("INSERT INTO `drip_orders` SET user_id = ?, service_id = ?, drip_link = ?, drip_amount = ?, drip_quantity = ?, drip_last_action = ?, drip_runs = ?, drip_interval = ?");
							$insert_drip = $query->execute([
								$user_id, $service["service_id"], $link, $amount, $quantity, time(), $runs, $interval
							]);

							$user = $db->from('users')->where('user_id', $user_id)->first();
							user_spent("ekle", $user['user_username'], $amount);
						}
					} else {
						$query = $db->prepare("INSERT INTO `orders` SET api_id = ?, api_order_id = ?, user_id = ?, service_id = ?, order_type = ?, order_date = ?, order_link = ?, order_quantity = ?, order_amount = ?, is_failed = ?, order_remains = ?");
						$insert_order = $query->execute([
							null, null, $user_id, $service["service_id"], 1, time(), $link, $quantity, ($amount / $runs), 1, $quantity
						]);
						if ($insert_order) {
							$order = $db->lastInsertId();
							$query = $db->prepare("INSERT INTO `drip_orders` SET user_id = ?, service_id = ?, drip_link = ?, drip_amount = ?, drip_quantity = ?, drip_last_action = ?, drip_runs = ?, drip_interval = ?");
							$insert_drip = $query->execute([
								$user_id, $service["service_id"], $link, $amount, ($quantity * $runs), time(), $runs, $interval
							]);
							$user = $db->from('users')->where('user_id', $user_id)->first();
							user_spent("ekle", $user['user_username'], $amount);
						}
					}
				} else {

					$order = send_order_default($api["api_url"], $api["api_key"], $service["api_service"], $link, $quantity);
					$order = json_decode(json_encode($order), true);
					$apiorderdetail = json_encode($order);

					if (@$order['order']) {

						$query = $db->insert('orders')
							->set(array(
								'api_id' => $api['api_id'],
								'api_order_id' => $order['order'],
								'user_id' => $user_id,
								'service_id' => $service['service_id'],
								'order_type' => 0,
								'order_date' => time(),
								'update_date' => time(),
								'order_link' => $link,
								'order_quantity' => $quantity,
								'order_amount' => $amount,
								'order_remains' => $quantity,
								'order_detail' => $apiorderdetail
							));

						$user = $db->from('users')->where('user_id', $user_id)->first();
						user_spent("ekle", $user['user_username'], $amount);
					} else {

						$query = $db->insert('orders')
							->set(array(
								'api_id' => null,
								'api_order_id' => null,
								'user_id' => $user_id,
								'service_id' => $service['service_id'],
								'order_type' => 0,
								'order_date' => time(),
								'update_date' => time(),
								'order_link' => $link,
								'order_quantity' => $quantity,
								'order_amount' => $amount,
								'is_failed' => 1,
								'order_remains' => $quantity,
								'order_detail' => $apiorderdetail
							));

						$user = $db->from('users')->where('user_id', $user_id)->first();
						user_spent("ekle", $user['user_username'], $amount);

						$Notifyemail 		= 	$settings['admin_iletisim'];
						$Notifyphone 		= 	$settings['admin_phone'];
						$Notifyname 		= 	"Sn. Site Yetkilisi";
						$Notifysubject 	= 	"Hatalı Sipariş Bildirimi";
						$Notifymessage 	= 	"Sağlayıcınıza iletilemeyen siparişiniz bulunuyor. " . admin_url('orders/failed') . " sayfasından fail siparişlerinizi takip edebilirsiniz.";

						if ($NotifySettings['failed'] == 2) {

							send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
						} elseif ($NotifySettings['failed'] == 3) {

							send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
						} elseif ($NotifySettings['failed'] == 4) {

							send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
							send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
						}
					}
				}
			} else {

				$order = send_order_comments($api["api_url"], $api["api_key"], $service["api_service"], $link, $comments);
				$orderdetail = json_encode($order);

				if ($order->order) {
					$insert_order_array = array(
						'api_id' => $api["api_id"],
						'api_order_id' => $order->order,
						'user_id' => $user_id,
						'service_id' => $service["service_id"],
						'order_type' => 0,
						'order_date' => time(),
						'order_link' => $link,
						'order_quantity' => $quantity,
						'order_amount' => $amount,
						'order_remains' => $quantity,
						'order_detail' => $orderdetail,
						'order_comments' => $comments
					);
					$insert_order = $db->insert('orders')
						->set($insert_order_array);



					if ($insert_order) {

						$user = $db->from('users')->where('user_id', $user_id)->first();
						user_spent("ekle", $user['user_username'], $amount);
						$query = $db->from('orders')->where('api_order_id', $order->order)->first();
						return $query['order_id'];
					} else {
						return false;
					}
				} else {

					$insert_order_array = array(
						'api_id' => $api["api_id"],
						'api_order_id' => 0,
						'user_id' => $user_id,
						'service_id' => $service["service_id"],
						'order_type' => 0,
						'order_date' => time(),
						'order_link' => $link,
						'order_quantity' => $quantity,
						'order_amount' => $amount,
						'order_remains' => $quantity,
						'order_detail' => $orderdetail,
						'order_comments' => $comments,
						'is_failed' => 1
					);
					$insert_order = $db->insert('orders')
						->set($insert_order_array);


					return false;
				}
			}
		} else {
			return false;
		}
	} else {
		if ($comments == null) {
			if ($runs != null && $interval != null) {
				$query = $db->prepare("INSERT INTO `orders` SET api_id = ?, api_order_id = ?, user_id = ?, service_id = ?, order_type = ?, order_date = ?, order_link = ?, order_quantity = ?, order_amount = ?, order_remains = ?");
				$insert_order = $query->execute([
					null, null, $user_id, $service["service_id"], 1, time(), $link, $quantity, ($amount / $runs), $quantity
				]);
				if ($insert_order) {
					$order = $db->lastInsertId();
					$query = $db->prepare("INSERT INTO `drip_orders` SET user_id = ?, service_id = ?, drip_link = ?, drip_amount = ?, drip_quantity = ?, drip_last_action = ?, drip_runs = ?, drip_interval = ?");
					$insert_drip = $query->execute([
						$user_id, $service["service_id"], $link, $amount, ($quantity * $runs), time(), $runs, $interval
					]);

					$user = $db->from('users')->where('user_id', $user_id)->first();
					user_spent("ekle", $user['user_username'], $amount);

					$Notifyemail 		= 	$settings['admin_iletisim'];
					$Notifyphone 		= 	$settings['admin_phone'];
					$Notifyname 		= 	"Sn. Site Yetkilisi";
					$Notifysubject 	= 	"Manuel Sipariş Bildirimi";
					$Notifymessage 	= 	"Yeni bir manuel siparişiniz bulunmakta. " . admin_url('orders') . " sayfasından siparişlerinizi takip edebilirsiniz.";

					if ($NotifySettings['order'] == 2) {

						send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
					} elseif ($NotifySettings['order'] == 3) {

						send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
					} elseif ($NotifySettings['order'] == 4) {

						send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
						send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
					}
				}
			} else {
				$query = $db->prepare("INSERT INTO `orders` SET api_id = ?, api_order_id = ?, user_id = ?, service_id = ?, order_type = ?, order_date = ?, order_link = ?, order_quantity = ?, order_amount = ?, order_remains = ?");
				$insert_order = $query->execute([
					null, null, $user_id, $service["service_id"], 0, time(), $link, $quantity, $amount, $quantity
				]);
				if ($insert_order) {
					$order = $db->lastInsertId();

					$user = $db->from('users')->where('user_id', $user_id)->first();
					user_spent("ekle", $user['user_username'], $amount);

					$Notifyemail 		= 	$settings['admin_iletisim'];
					$Notifyphone 		= 	$settings['admin_phone'];
					$Notifyname 		= 	"Sn. Site Yetkilisi";
					$Notifysubject 	= 	"Manuel Sipariş Bildirimi";
					$Notifymessage 	= 	"Yeni bir manuel siparişiniz bulunmakta. " . admin_url('orders') . " sayfasından siparişlerinizi takip edebilirsiniz.";

					if ($NotifySettings['order'] == 2) {

						send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
					} elseif ($NotifySettings['order'] == 3) {

						send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
					} elseif ($NotifySettings['order'] == 4) {

						send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
						send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
					}
				}
			}
		} else {
			$query = $db->prepare("INSERT INTO `orders` SET api_id = ?, api_order_id = ?, user_id = ?, service_id = ?, order_type = ?, order_date = ?, order_link = ?, order_quantity = ?, order_amount = ?, order_remains = ?, order_comments = ?");
			$insert_order = $query->execute([
				null, null, $user_id, $service["service_id"], 0, time(), $link, $quantity, $amount, $quantity, $comments
			]);
			if ($insert_order) {
				$user = $db->from('users')->where('user_id', $user_id)->first();
				user_spent("ekle", $user['user_username'], $amount);

				$order = $db->lastInsertId();
				$Notifyemail 		= 	$settings['admin_iletisim'];
				$Notifyphone 		= 	$settings['admin_phone'];
				$Notifyname 		= 	"Sn. Site Yetkilisi";
				$Notifysubject 	= 	"Manuel Sipariş Bildirimi";
				$Notifymessage 	= 	"Yeni bir manuel siparişiniz bulunmakta. " . admin_url('orders') . " sayfasından siparişlerinizi takip edebilirsiniz.";

				if ($NotifySettings['order'] == 2) {

					send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
				} elseif ($NotifySettings['order'] == 3) {

					send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
				} elseif ($NotifySettings['order'] == 4) {

					send_email($Notifyemail, $Notifyname, $Notifysubject, $Notifymessage);
					send_sms(1, $settings['sms_provider'], $Notifyphone, $Notifymessage);
				}
			}
		}
	}
	$orderx = $db->query("SELECT order_id FROM `orders` ORDER BY order_id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
	return $orderx['order_id'];
}

function cancel_order($order_id)
{

	global $db;

	if ($order_id) {

		$order = $db->from('orders')->where('order_id', $order_id)->first();

		if ($order) {

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

				$updateOrder = $db->update('orders')
					->where('order_id', $order['order_id'])
					->set(array(
						'order_remains' => 0,
						'order_status' => "Canceled",
						'order_amount' => 0,
						'update_date' => time()
					));

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

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

				if ($updateOrder && $updateBalance) {

					user_spent("cikar", $user['user_username'], $order['order_amount']);
					$return = $order['order_id'] . " numaralı sipariş iptal edildi olarak güncellendi.";
				} else {

					$return = false;
				}
			} else {

				$return = false;
			}
		} else {

			$return = false;
		}
	} else {

		$return = false;
	}


	return $return;
}

function partial_order($order_id, $remains)
{

	global $db;

	if ($order_id && $remains) {

		$order = $db->from('orders')->where('order_id', $order_id)->first();

		if ($order) {

			if ($remains > $order['order_quantity']) {

				$return = false;
			} else {

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

					$return = false;
				} else {

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

					if ($user) {

						$price 			= $order['order_amount'] / $order['order_quantity'];	## 1 Adet Kaç TL
						$result 		= $price * $remains;									## İade Edilecek Ücret
						$newBalance 	= $user['user_balance'] + $result;					## Üyenin Yeni Bakiyesi
						$remainsOrder 	= $order['order_quantity'] - $remains;				## Yeni Sipariş Miktarı
						$charge 		= $order['order_amount'] - $result;					## Yeni Sipariş Tutarı

						$updateOrder = $db->update('orders')
							->where('order_id', $order_id)
							->set(array(
								'order_remains' => $remains,
								'order_status' => "Partial",
								'order_amount' => $charge,
								'update_date' => time()
							));

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

						if ($updateOrder && $updateBalance) {

							user_spent("cikar", $user['user_username'], $result);
							$return = $order['order_id'] . " numaralı sipariş kısmi tamamlandı olarak güncellendi.";
						} else {

							$return = false;
						}
					} else {

						$return = false;
					}
				}
			}
		} else {

			$return = false;
		}
	} else {

		$return = false;
	}

	return $return;
}
