<?php

	class Drip {
		protected $db;
		
		public function __construct($connection) {
			$this->db = $connection;
		}
		
		public function getInnerDrips() {
			return $this->db->query("SELECT D.*, S.service_id, S.api_id, S.api_service FROM `drip_orders` AS D INNER JOIN `services` AS S ON S.service_id = D.service_id WHERE D.drip_status = 1 AND S.service_status = 1")->fetchAll(PDO::FETCH_ASSOC);
		}
		
		public function getOuterDrips() {
			return $this->db->query("SELECT D.* FROM `drip_orders` AS D LEFT JOIN `services` AS S ON S.service_id = D.service_id WHERE D.drip_status = 1 AND (S.service_id IS NULL OR S.service_status = 0)")->fetchAll(PDO::FETCH_ASSOC);
		}
		
		public function cancelDrip() {
			$drips = $this->getOuterDrips();
			foreach($drips as $drip) {
				$unit_amount = $drip["drip_amount"] / $drip["drip_runs"];
				$return_amount = $unit_amount * ($drip["drip_runs"] - $drip["drip_completed"]);
				$user = $this->db->query("SELECT * FROM `users` WHERE user_id = $drip[user_id]")->fetch(PDO::FETCH_ASSOC);
				if($user) {
					$new_balance = $user["user_balance"] + $return_amount;
					$this->db->beginTransaction();
					$update_user = $this->db->query("UPDATE `users` SET user_balance = $new_balance WHERE user_id = $user[user_id]");
					$update_drip = $this->db->query("UPDATE `drip_orders` SET drip_status = 0 WHERE drip_id = $drip[drip_id]");
					if($update_user && $update_drip) {
						$this->db->commit();
					} else {
						$this->db->rollBack();
					}
				} else {
					$update_drip = $this->db->query("UPDATE `drip_orders` SET drip_status = 0 WHERE drip_id = $drip[drip_id]");
				}
			}
		}
		
		public function sendOrders() {
			$drips = $this->getInnerDrips();
			foreach($drips as $drip) {
				$interval = $drip["drip_interval"] * 60;
				if($drip["drip_last_action"] + $interval <= time()) {
					$order = add_order($drip, $drip["user_id"], $drip["drip_link"], $drip["drip_quantity"], ($drip["drip_amount"] / $drip["drip_runs"]));
					if($order) {
						$completed = $drip["drip_completed"] + 1;
						$extra = "";
						if($completed == $drip["drip_runs"]) {
							$extra = ", drip_status = 0";
						}
						$time = time();
						$update_drip = $this->db->query("UPDATE `drip_orders` SET drip_completed = $completed, drip_last_action = '$time'$extra WHERE drip_id = $drip[drip_id]");
					}
				}
			}
		}
	}