<?php 

// Файл с функциями
// Все функции которые используються для работы
// Мне лень было работать с ООП и MVC, поэтому тут такая система :)


// Класс для работы с шаблонами
class Templates {
	public function viewLoad($name, $vars = array()){
		$file = CP_ENGINE_DIR . $name . '.php';
		if(is_readable($file)){
			extract($vars);
	  		$content = include($file);
			
	  		return $content;
		}
		exit('Ошибка: Не удалось загрузить шаблон ' . $name . '!');
	}
	
	public function view($view = array(), $vars = array()) {
		foreach($view as $item) {
			$this->viewLoad($item, $vars);
		}
	}
}

// Класс для работы с пользователями
class User extends Templates {

	public function addUser($login, $email, $password, $firstname, $lastname) {
		global $db;

		$sql = "INSERT INTO `gd_users` 
		(	user_login, 
			user_email, 
			user_password,
			user_reg_time,
			user_reg_ip,
			user_firstname,
			user_lastname
		) VALUES (
			'{$login}', 
			'{$email}', 
			'{$password}',  
			NOW(), 
			'{$_SERVER['REMOTE_ADDR']}',
			'{$firstname}',
			'{$lastname}')";
		$db->query($sql);
		
		if(!$db->error) {
			return $db->insert_id;
		}
		return false;
	}

	// Функция авторизации
	public function auth($login, $password) {
		global $db;

		if($user = $this->userInfo($login, "user_login")){
			if($user['user_password'] == md5($password."maksa988key")){
				if($user['user_group'] >= 2){
					$this->editUser("`user_login_time` = NOW(), `user_login_ip` = '".$_SERVER['REMOTE_ADDR']."'", $user['user_id']);
					$_SESSION['user_id'] = $user['user_id'];
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	// Функция для получения информации и пользователе
	public function userInfo($value, $row = "user_id"){
		global $db;
		$sql = "SELECT * FROM `gd_users` WHERE `{$row}` = '{$value}' LIMIT 1";
		$result = $db->query($sql);

		if($result->num_rows == 1){
			return $result->fetch_assoc();
		}
		return false;
	}

	// Функция для редактирования данных пользователя
	// $param = параметры для изменения (`название столбца в таблице` = 'новое значение')
	// $id = ID пользователя
	public function editUser($param, $id) {
		global $db;
		$sql = "UPDATE `gd_users` SET ".$param." WHERE `user_id` = ".$id;
		$db->query($sql);
		
		if(!$db->error) {
			return true;
		}
		return false;
	}	

	public function getMoneys($param = "") {
		global $db;
		$sql .= "SELECT * FROM `gd_money_back` ";
		$sql .= " LEFT JOIN gd_users";
		$sql .= " ON `gd_money_back`.user_id=`gd_users`.user_id ";
		$sql .= $param;
		$sql .= " WHERE `money_status` = '0' ORDER BY `money_id` ASC";
		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}
	
	public function moneyInfo($value, $row = "money_id"){
		global $db;
		$sql = "SELECT * FROM `gd_money_back` WHERE `{$row}` = '{$value}' LIMIT 1";
		$result = $db->query($sql);

		if($result->num_rows == 1){
			return $result->fetch_assoc();
		}
		return false;
	}

	public function editRequest($param, $id) {
		global $db;
		$sql = "UPDATE `gd_money_back` SET ".$param." WHERE `money_id` = ".$id;
		$db->query($sql);
		
		if(!$db->error) {
			return true;
		}
		return false;
	}

	public function addMoneyRequest($sum, $uid, $key, $system) {
		global $db;
		$sql = "INSERT INTO `gd_money_back` 
		(	money_sum, 
			money_key, 
			user_id, 
			money_time,
			money_system
		) VALUES (
			'{$sum}', 
			'{$key}', 
			'{$uid}', 
			NOW(),
			'{$system}')";
		$db->query($sql);
		
		if(!$db->error) {
			return $db->insert_id;
		}
		return false;
	}

	public function sendUserProject($shopid, $userid, $status){
		return true;
	}
}

// Класс для работы с магазинами
class Shop extends User {

	// Функция для получения списка магазинов с параметрами:
	// $data = данные в ввиде массива ("название поля" => "значение")
	// $joins = данные в ввиде массива ("название таблицы (прим. users)")
	public function getShops($data = array(), $joins = array()){
		global $db;
		$sql = "SELECT * FROM `gd_shops`";
		foreach($joins as $join) {
			$sql .= " LEFT JOIN `gd_{$join}`";
			switch($join) {
				case "users":
					$sql .= " ON `gd_shops`.user_id=`gd_users`.user_id";
					break;
				case "servers":
					$sql .= " ON `gd_shops`.server_id=`gd_servers`.server_id";
					break;
			}
		}
		
		if(!empty($data)) {
			$count = count($data);
			$sql .= " WHERE";
			foreach($data as $key => $value) {
				$sql .= " $key = '" . $db->real_escape_string($value) . "'";
				
				$sql .= " AND";
			}
		} else {
			$sql .= " WHERE";
		}
		$sql .= ' `shop_status` != 3 ORDER BY `shop_id` DESC';
		$result = $db->query($sql);
		
		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}

	// Функция для получения списка последних покупок:
	// $data = данные в ввиде массива ("название поля" => "значение")
	// $joins = данные в ввиде массива ("название таблицы (прим. users)")
	public function getItems($data = array(), $joins = array()){
		global $db;
		$sql = "SELECT * FROM `gd_log_payments`";
		foreach($joins as $join) {
			$sql .= " LEFT JOIN `gd_{$join}`";
			switch($join) {
				case "shops":
					$sql .= " ON `gd_log_payments`.shop_id=`gd_shops`.shop_id";
					break;
			}
		}
		
		if(!empty($data)) {
			$count = count($data);
			$sql .= " WHERE";
			foreach($data as $key => $value) {
				$sql .= " $key = '" . $db->real_escape_string($value) . "'";
				
				$count--;
				if($count > 0) $sql .= " AND";
			}
		}
		$sql .= ' ORDER BY `log_payments_id` DESC';
		$result = $db->query($sql);
		
		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}
	
	// Функция для получения списка последних 50 операции для отображение в лог:
	// $data = данные в ввиде массива ("название поля" => "значение")
	// $joins = данные в ввиде массива ("название таблицы (прим. users)")	
	public function getStatsAll($data = array(), $joins = array()){
		global $db;
		$sql = "SELECT * FROM `gd_log_payments`";
		foreach($joins as $join) {
			$sql .= " LEFT JOIN `gd_{$join}`";
			switch($join) {
				case "shops":
					$sql .= " ON `gd_log_payments`.shop_id=`gd_shops`.shop_id";
					break;
			}
		}
		
		if(!empty($data)) {
			$count = count($data);
			$sql .= " WHERE";
			foreach($data as $key => $value) {
				$sql .= " $key = '" . $db->real_escape_string($value) . "'";
				
				$count--;
				if($count > 0) $sql .= " AND";
			}
		}
		$sql .= ' ORDER BY `log_payments_id` DESC LIMIT 0, 1000';
		$result = $db->query($sql);
		
		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}	

	// Функция для получения информации о магазине с параметрами:
	// $shopid = int
	// $joins = данные в ввиде массива ("название таблицы (прим. users)")
	public function getShopByID($shopid, $joins = array()) {
		global $db;
		$sql = "SELECT * FROM `gd_shops`";
		foreach($joins as $join) {
			$sql .= " LEFT JOIN `gd_{$join}`";
			switch($join) {
				case "users":
					$sql .= " ON `gd_shops`.user_id=`gd_users`.user_id";
					break;
				case "servers":
					$sql .= " ON `gd_shops`.server_id=`gd_servers`.server_id";
					break;
			}
		}
		$sql .=  " WHERE `shop_id` = '" . (int)$shopid . "' LIMIT 1";
		$result = $db->query($sql);
		if($result->num_rows == 1){
			return $result->fetch_assoc();
		}
		return false;
	}

	// Функция для проверки занятости домена
	// $domain = домен
	public function checkShop($domain) {
		global $db;
		$sql = "SELECT * FROM `gd_shops` WHERE `shop_domain` = '{$domain}' LIMIT 1";
		$result = $db->query($sql);

		if($result->num_rows == 1){
			return true;
		}
		return false;
	}

	// Функция для создания магазина
	// $name = название
	// $url = домен
	// $game = игра
	public function createShop($name, $url, $game) {
		global $db;
		$sql = "INSERT INTO `gd_shops` 
		(	shop_name, 
			shop_domain, 
			shop_game, 
			user_id, 
			shop_add_time, 
			shop_status
		) VALUES (
			'{$name}', 
			'{$url}', 
			'{$game}', 
			'{$_SESSION['user_id']}', 
			NOW(), 
			'0')";
		$db->query($sql);
		
		if(!$db->error) {
			return $db->insert_id;
		}
		return false;
	}

	// Функция для редактирования данных
	// $param = параметры для изменения (`название столбца в таблице` = 'новое значение')
	// $id = ID магазина
	public function editShop($param, $id) {
		global $db;
		$sql = "UPDATE `gd_shops` SET ".$param." WHERE `shop_id` = ".$id;
		$db->query($sql);
		
		if(!$db->error) {
			return true;
		}
		return false;
	}

	public function getShopStatsWeek($status = "1", $shopid) {
		global $db;
		
		if($status == "1"){
			$sql = "SELECT DATE( `log_payments_time` ) AS DATE, COUNT( * ) AS stat 
			FROM `gd_log_payments` 
			WHERE `shop_id` = '{$shopid}' AND `log_payments_time` BETWEEN NOW( ) - INTERVAL 7 DAY AND NOW( ) 
			GROUP BY DATE( `log_payments_time` ) 
			ORDER BY `log_payments_time` LIMIT 0, 7";
		} else {
			$sql = "SELECT DATE( `log_payments_time_complete` ) AS DATE, SUM( `log_payments_sum_client` ) AS sum 
			FROM `gd_log_payments` 
			WHERE `shop_id` = '{$shopid}' AND `log_payments_time` BETWEEN NOW( ) - INTERVAL 7 DAY AND NOW( ) 
			GROUP BY DATE( `log_payments_time_complete` ) 
			ORDER BY `log_payments_time_complete` LIMIT 0, 7";
		}

		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}

	public function getStatsWeek() {
		global $db;
		
		$sql = "SELECT DATE( `log_payments_time` ) AS DATE, COUNT( * ) AS stat, SUM( `log_payments_sum_client` ) AS sum 
		FROM `gd_log_payments` 
		WHERE `log_payments_time` BETWEEN NOW( ) - INTERVAL 7 DAY AND NOW( ) 
		GROUP BY DATE( `log_payments_time` ) 
		ORDER BY `log_payments_time` LIMIT 0, 7";
		// dd($sql);
		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}

	public function getBalanceAll($status = "today", $shops = array()) {
		global $db;
		
		if(!empty($shops)) {
			$count = count($shops);
			foreach($shops as $item) {
				$sqlShop .= " `shop_id` = '" . $db->real_escape_string($item) . "'";
				
				$count--;
				if($count > 0) { $sqlShop .= " OR"; }
				else { $sqlShop .= " AND"; }
			}
		}

		if($status == "today"){
			$sql = "SELECT SUM( `log_payments_sum_client` ) as sum FROM `gd_log_payments` WHERE log_payments_time_complete LIKE '%".date("m-d")."%'";
			
			$result = $db->query($sql);
			$data = $result->fetch_assoc();

			return (int) $data['sum'];
		} if($status == "s"){
			$sql = "SELECT SUM( `log_payments_sum_client` ) as sum FROM `gd_log_payments` WHERE log_payments_time_complete >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)";

			$result = $db->query($sql);
			$data = $result->fetch_assoc();

			return (int) $data['sum'];
		}
		if($status == "today2"){
			$sql = "SELECT SUM( `log_payments_sum_client` ) as sum FROM `gd_log_payments` WHERE log_payments_time_complete LIKE '%".date("m-d")."%'";

			$result = $db->query($sql);
			$dataOne = $result->fetch_assoc();
			
			$sql = "SELECT SUM(`money_sum`) FROM `gd_money_back` WHERE `money_time` LIKE '%".date("m-d")."%' AND `money_status` != 2";
			$result = $db->query($sql);
			$dataTwo = $result->fetch_assoc();
			return (int) $dataOne['sum'] - (int) $dataTwo['SUM(`money_sum`)'];
		} else {
			$sql = "SELECT SUM( `log_payments_sum_client` ) as sum FROM `gd_log_payments` WHERE log_payments_time_complete >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)";

			$result = $db->query($sql);
			$dataOne = $result->fetch_assoc();
			
			$sql = "SELECT SUM(`money_sum`) FROM `gd_money_back` WHERE `money_time` >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) AND `money_status` != 2";
			$result = $db->query($sql);
			$dataTwo = $result->fetch_assoc();

			return (int) $dataOne['sum'] - (int) $dataTwo['SUM(`money_sum`)'];
		}

		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}

	public function getBalance($status = "today", $shopid) {
		global $db;
		
		if($status == "today"){
			$sql = "SELECT SUM( `log_payments_sum_client` ) as sum FROM `gd_log_payments` WHERE `shop_id` = '{$shopid}' AND log_payments_time_complete >= DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY)";
		} else {
			$sql = "SELECT SUM( `log_payments_sum_client` ) as sum FROM `gd_log_payments` WHERE `shop_id` = '{$shopid}' AND log_payments_time_complete >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)";
		}

		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}
}

class Tickets extends Shop {
	public function getTickets($param = '') {
		global $db;
		$sql .= "SELECT * FROM `gd_tickets` ";
		$sql .= " LEFT JOIN gd_users";
		$sql .= " ON `gd_tickets`.user_id = `gd_users`.user_id ";
		$sql .= $param;
		$sql .= "ORDER BY `ticket_status` DESC,  `ticket_time_add` DESC ";
		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}
	public function getTicket($id) {
		global $db;
		$sql = "SELECT * FROM `gd_tickets` WHERE `ticket_id` = '{$id}' LIMIT 1";
		$result = $db->query($sql);
		
		if($result->num_rows == 1){
			return $result->fetch_assoc();
		}
		return false;
	}
	public function editTicket($param, $id) {
		global $db;
		$sql = "UPDATE `gd_tickets` SET ".$param." WHERE `ticket_id` = ".$id;
		$db->query($sql);
		
		if(!$db->error) {
			return true;
		}
		return false;
	}
	public function createTicket($userid, $name, $dep, $shopid = '') {
		global $db;

		$sql = "INSERT INTO `gd_tickets` 
		(	user_id, 
			ticket_name, 
			ticket_status, 
			shop_id, 
			ticket_dep, 
			ticket_time_add
		) VALUES (
			'{$userid}', 
			'{$name}', 
			'1', 
			'{$shopid}', 
			'{$dep}',
			NOW()
		)";
		$db->query($sql);
		
		if(!$db->error) {
			return $db->insert_id;
		}
		return false;
	}
}

class Tickets_messages extends Tickets {
	public function getMessages($ticketid) {
		global $db;
		$sql = "SELECT * FROM `gd_tickets_messages` LEFT JOIN `gd_users` ON `gd_tickets_messages`.user_id=`gd_users`.user_id WHERE `ticket_id` = '{$ticketid}'";
		$result = $db->query($sql);

		$items = array();
		
		if($result->num_rows >= 1){
			while($data = $result->fetch_assoc())
			$items[] = $data;
			
			return $items;
		}
		return false;
	}
	public function addMessage($userid, $ticketid, $text) {
		global $db;

		$sql = "INSERT INTO `gd_tickets_messages` 
		(	ticket_id, 
			user_id, 
			ticket_message_time, 
			ticket_message_asses, 
			ticket_message_text
		) VALUES (
			'{$ticketid}', 
			'{$userid}', 
			NOW(), 
			'0', 
			'{$text}'
		)";
		$db->query($sql);
		
		if(!$db->error) {
			return $db->insert_id;
		}
		return false;
	}
	public function editMessage($param, $id) {
		global $db;
		$sql = "UPDATE `gd_tickets_messages` SET ".$param." WHERE `ticket_message_id` = ".$id;
		$db->query($sql);
		
		if(!$db->error) {
			return true;
		}
		return false;
	}
}

// Главный класс для запуска всего и всея
class Main extends Tickets_messages {
	protected $user = array();
	protected $shops = array();
	protected $param = array();
	protected $mons = array();

	public function Main(){
		if(!empty($_SESSION['user_id'])){
			$this->user = $this->userInfo($_SESSION['user_id']);

			$this->shops = $this->getShops(array("user_id" => $_SESSION['user_id']));
		}
		$this->month = array("1"=>"Января",
			"2"=>"Февраля",
			"3"=>"Марта",
			"4"=>"Апреля",
			"5"=>"Мая", 
			"6"=>"Июня", 
			"7"=>"Июля",
			"8"=>"Августа",
			"9"=>"Сентября",
			"10"=>"Октября",
			"11"=>"Ноября",
			"12"=>"Декабря");
	}

	public function getVKNews(){
		$response = file_get_contents("http://api.vk.com/method/wall.get?owner_id=-99696684&extended=1&count=10");
		$wall = json_decode($response, true);
		return $wall;
	}

	public function loadModule($name, $param = array()){
		$file = CP_ENGINE_DIR . "app/" . $name . '.php';
		if(is_readable($file)){
			$this->param = $param;
	  		if(require_once($file)){
	  			return true;
	  		} else {
	  			return false;
	  		}
		}
		exit('Ошибка: Не удалось загрузить модуль ' . $name . '!');
	}

	public function requestAPITelegram($method, $msg, $code, $tid) {
		// if(@file_get_contents("")){
		// 	return true;
		// }

		return true;
	}

	public function checkURL($url){
		$status = @file_get_contents($url);
		$status = json_decode($status, true);
		// dd($status);
		if($status['error']['message'] == "Invalid request"){
			return true;
		} else {
			return false;
		}
	}

	public function escape($value = array()){
		global $db;

		return $db->real_escape_string($value);
	}

	function smtpmail($mail_to, $subject, $message) { 
		require './mailer/PHPMailerAutoload.php'; 

		$mail = new PHPMailer; // Enable verbose debug output 
		$mail->CharSet = 'utf-8'; 
		$mail->isSMTP(); 
		$mail->Host = "server99.hosting.reg.ru"; 
		$mail->SMTPAuth = true; 
		$mail->Username = "support@localpay.ru"; 
		$mail->Password = "x6xXIb0c"; 
		$mail->SMTPSecure = 'ssl'; 
		$mail->Port = "465"; 

		$mail->setFrom("support@localpay.ru"); 
		$mail->addAddress($mail_to); // Name is optional 
		$mail->isHTML(true); // Set email format to HTML 

		$mail->Subject = $subject; 
		$mail->Body = $message; 

		if(!$mail->send()) { 
			return 'Mailer Error: ' . $mail->ErrorInfo; 
		} 
		return true; 
	}
}


// Функция для дебага
function dd($value, $type = 1, $pre = true){
	if($pre){
		echo "<pre>";
	}

	switch($type){
		case 1: 
			var_dump($value);
		break;

		case 2:
			echo $value;
		break;

		case 3:
			print_r($value);
		break;
	}

	exit("</pre>");
}