<?php

class Model{

	static $host = DATABASEHOST;
	static $user = HOST_USERNAME;
	static $password = HOST_PASSWORD;
	static $database = HOST_DATABASE;
	
	function __construct(){
		Session::init();
		require_once 'include_dao.php';
		require_once("libs/cpanel_api.php");
	}

	static function setHost($h){
		self::$host = $h;
	}
	
	static function getConnection(){
		// echo self::$password = (self::$password) ? self::$password : '';
		// echo 'asd';
		// exit;
		return mysqli_connect(self::$host, self::$user, self::$password, self::$database);
	}
	
	static function executeSqlQuery($sql){
		$conn = self::getConnection();
		
		if(!$conn){
			return false;
		}
		
		$result = $conn->query($sql);
		/* if(empty($result)){
			echo $sql;
		} */
		
		if(isset($result)){
			if ($result->num_rows > 0) {
				$details = array();
				while($row = $result->fetch_assoc()) {
					$details[] = $row;
				}
				// $details = $result->fetch_assoc();
				mysqli_close($conn);
				return $details;
			}
		}
		return false;
	}
	
	static function executeSqlInsert($sql){
		
		$conn = self::getConnection();
		
		$result = $conn->query($sql);
		$id = $conn->insert_id;
		mysqli_close($conn);
		return $id;
	}
	
	static function executeSqlUpdate($sql){
		
		$conn = self::getConnection();
		
		$result = $conn->query($sql);
		mysqli_close($conn);
		return true;
	}
	
	static function setLogs($type = 'api', $msg){
		$user = Session::getSession('userDbUser');
		date_default_timezone_set('Asia/Taipei');
		require_once 'include_dao.php';
		
		$logs = new TblLog();
		
		$logs->log = $user['username'].' '.$msg;
		if($user['status'] == 'admin')
		{
			$logs->type = 'admin Transaction';
		}
		else
		{
			$logs->type = 'developer Transaction';
		}
		$logs->dateTime = date('Y-m-d H:i:s');
		
		DAOFactory::getTblLogsDAO()->insert($logs);
	}
	
	static function getDatabasepre($type){
		$ubs_data = Session::getSession('UBS_DATA');
		$array = array();
		foreach($ubs_data as $each){
			if($each[0] == $type) return $each['pre_value'];
		}
	}
	
	public function url_get_contents($url) 
	{
		if (!function_exists('curl_init')){ 
			die('Error 500!');
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
}