<?php
/**
 * Copyright (c) 2013 Second Company B.V. <support@dutchauctionmasters.nl>
 * http://www.dutchauctionmasters.nl/
 * All rights reserved.
 */

class dam_functions {
	
	static public function money_format($number)
	{
// 		if (function_exists ( 'money_format' ))	{
			
// 			$currency = get_option("dam_currency");				
// 			$currencies = dam_currency::get_currencies();
				
// 			$code = $currencies[$currency];		
			
// 			setlocale(LC_MONETARY, $code['code']);
			
// 			echo money_format($format, $number);
						
// 		}else{
			
// 				$currency = get_option("dam_currency", "USD");
// 				$currencies = dam_currency::get_currencies();				
// 				$symbol = $currencies[$currency];				
// 				$decimal_point =  $symbol['decimal_point'];
// 				$thousands_sep =  $symbol['thousands_sep'];		
				
			 
				
				$decimal_point =  get_option('dam_currency_decimal_point',',');
				$thousands_sep =  get_option('dam_currency_thousends_step','.');
				$symbol = get_option('dam_currency_symbol','&euro;');				
				
				$money = number_format ( $number, 2, $decimal_point , $thousands_sep );
				return  $symbol.' '.$money;	
			 	
	//}	
	}
	
	static public function get_auction_message($is_running, $is_winner, $current_user, $is_upcoming = false) {
		$stausmessage = "";
		
		if($is_upcoming)
			return "";
		
		if (!$is_running) {
			if ($current_user->ID) {
				if ($is_winner) {
					$stausmessage = __("You've won the auction, an email will be sent to you shortly, please refer to it to know more details.","dam-auction-masters");
				} else {
					$stausmessage = __("Sorry, the auction is closed and you are not the winner.","dam-auction-masters");
				}
			} else {
				$stausmessage = __("The auction is closed","dam-auction-masters");
			}
		}
		return $stausmessage;
	}
	
	static public function get_auction_detail_url($auction_id)
	{
		$page_id = get_option("dam_auction_detail_page");
	
		if(empty($page_id))
		{			
			return "javascript:nonepage();";
		}else{
		
			$detail_page_url = get_permalink($page_id);
					
			$splitor = strpos($detail_page_url, "?")>0?"&":"?" ;
					
			$detail_url = $detail_page_url.$splitor."id=".$auction_id;
			return $detail_url;
		}
	}
	
	static public function get_auction_list($status, $category = null, $start = 0)
	{
		$total = dam_auction_adapter::get_auction_count($category, $status);		
 
		$per_page = 20;
	
		$offset = $start;
		
		$items = dam_auction_adapter::get_auction_list($category, $status, $per_page, $offset);
		

		$result = new stdClass ();
		
		if ($items && count ( $items ) > 0) {
			
			$auctions = array();
			foreach ($items as $auction)
			{
				$item = new stdClass();				
				$item->title =  (strlen($auction->title)>18)? substr($auction->title, 0, 16).'...':$auction->title;
				$item->alttitle = $auction->title;
			 	$item->auction_link = self::get_auction_detail_url($auction->id);
				$item->pic = $auction->picture ;
				$item->description = $auction->description ;
				$item->auction_ID = $auction->id;
				$item->end = strtotime ( $auction->end )- current_time('timestamp');
				$item->advicePrice = dam_functions::money_format($auction->start_price) ;
				$item->biddingPrice = dam_functions::money_format($auction->bid_price? $auction->bid_price:$auction->start_Price);
				$item->category =  $auction->Category;
				$item->start_time =  date('Y-m-d H:i' ,strtotime($auction->begin));				
				$auctions[] = $item;
			}
			
			if ($status == auction_str_status::RUNNING) {
				$result->running = $auctions;
			} else if ($status == auction_str_status::UPCOMING) {
				$result->upcoming = $auctions;
			} else {
				$result->all = $auctions;
			}
		}
		
		$result->total = $total;
		
			
		$result->islast = $total <= ($offset + $per_page);
		
		return $result;
	}
	
	static public function send_activate_email($email, $username, $email_template) {
		require_once ( ABSPATH . WPINC . '/class-phpmailer.php');
		
		if (! empty ( $email_template )) {
			
			$data = array (
					"Username" => $user_name,
					"Sitename" => get_option ( 'blogname' ),
					"Siteurl" => get_option ( 'siteurl' ),
					"Logo" => "",
					"Email" => $email 
			);
			
			$email_template = self::apply_template ( $data, $email_template );
			
			$subject = $email_template->subject;
			$email_body = $email_template->content;
			
			$email = array (
					"to" => $email,
					"from" => get_option ( 'dam_auction_admin' ),
					"from_name" => get_option ( 'dam_auction_admin_name' ),
					"subject" => $subject,
					"body" => $email_body 
			);
			
			return self::send_email ( $email );
		}
		
		return false;
	}
	
	static public function notify_to_admin($email, $auction, $email_template) {
		require_once ( ABSPATH . WPINC . '/class-phpmailer.php');
				
		if (! empty ( $email_template )) {
			
			$user_name = $auction->winner;
			$last_bids_array = json_decode ( stripslashes ( $auction->last_bids ) );
			$admin_name = $last_bids_array[0]->user_name;
			$auction_name = $auction->title;
			
			$auction_detail_url = get_permalink(get_option("dam_auction_detail_page"))."?id=";  //TODO
			
			$data = array (
					"UserName" => $user_name,
					"AdminName" => $admin_name,
					"AuctionName" => $auction_name,
					"SiteName" => get_option ( 'blogname' ),
					"SiteUrl" => get_option ( 'siteurl' ),
					"Logo" => "",
					"AuctionDate" => $auction->end,
					"AuctionUrl"=> $auction_detail_url.$auction->id,
					"Email" => $email 
			);
			
			$email_template = self::apply_template ( $data, $email_template );
			
			$subject = $email_template->subject;
			
			$email_body = $email_template->content;
			
			$email = array (
					"to" => $email,
					"from" => get_option ( 'dam_auction_admin' ), // TODO can admin
					                                              // send to admin?
					"from_name" => get_option ( 'dam_auction_admin_name' ),
					"subject" => $subject,
					"body" => $email_body 
			);
			
			return self::send_email ( $email );
		}
		return false;
	}
	
	static public function notify_to_user($email, $username, $auction, $email_template) {
				require_once ( ABSPATH . WPINC . '/class-phpmailer.php');
		
		if (! empty ( $email_template )) {
			
			$user_name = $username;
			
			$auction_name = $auction->title;
			
			$auction_detail_url = get_permalink(get_option("dam_auction_detail_page"))."?id=";  //TODO
			
			$data = array (
					"UserName" => $user_name,
					"AdminName" => $user_name,
					"AuctionName" => $auction_name,
					"SiteName" => get_option ( 'blogname' ),
					"SiteUrl" => get_option ( 'siteurl' ),
					"Logo" => "",
					"AuctionDate" => $auction->end,
					"AuctionUrl"=> $auction_detail_url.$auction->id,
					"Email" => $email
			);
			
			$email_template = self::apply_template ( $data, $email_template );
			
			$subject = $email_template->subject;
			
			$email_body = $email_template->content;
			
			$email = array (
					"to" => $email,
					"from" => get_option ( 'dam_auction_admin' ),
					"from_name" => get_option ( 'dam_auction_admin_name' ),
					"subject" => $subject,
					"body" => $email_body 
			);
			
			return self::send_email ( $email );
		}
		return false;
	}
	
	static public function apply_template($data, $template) {
		if (! empty ( $template )) {
			foreach ( $data as $key => $value ) {
				
				if (is_string ( $value )) {
					
					$template->subject = str_replace ( "[$key]", $value, $template->subject );
					$template->content = str_replace ( "[$key]", $value, $template->content );
				}else 
				{
					var_dump($key);
					var_dump($value);
				}
			}
		}
		return $template;
	}
	
	static public function send_email($email) {
		
		$mail = new PHPMailer ();
		$mail->AddAddress ( $email ["to"] );
		$mail->IsMail ();
		$mail->IsHTML ();
		$mail->From = $email ["from"];
		$mail->FromName = $email ["from_name"];
		$mail->Subject = $email ["subject"];
		$mail->Body = $email ["body"];
		$rst = $mail->Send ();
		return $rst;
	}
	
	static public function get_encrypted_timestamp($text) {
		$content_text = time () . "," . $text;
		$key = "dam-timestamp";
		$ivSize = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
		$iv = mcrypt_create_iv ( $ivSize, MCRYPT_RAND );
		$encryptText = mcrypt_encrypt ( MCRYPT_RIJNDAEL_256, $key, $content_text, MCRYPT_MODE_ECB, $iv );
		return trim ( base64_encode ( $encryptText ) );
	}
	
	static public function get_timestamp($encrypted_text) {
		$key = "dam-timestamp";
		$cryptText = base64_decode ( $encrypted_text );
		$ivSize = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
		$iv = mcrypt_create_iv ( $ivSize, MCRYPT_RAND );
		$decryptText = mcrypt_decrypt ( MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv );
		return trim ( $decryptText );
	}
	
	static public function check_timestamp_expire($encrypted_timestamp, $username) {
		$codes = self::get_timestamp ( $encrypted_timestamp );
		
		if (strpos ( $codes, ',' )) {
			
			$t = split ( ',', $codes );
			$time = intval ( $t [0] );
			$setting_time = intval ( get_option ( "activtecode_expire", "24" ) );
			$timespan = (time () - $time) / 3600;
			if ($timespan < $setting_time) {
				return false;
			}
		}
		return true;
	}
	
	static public function authenticated_place_bid($auction_id, $bid_price) {
		global $current_user;
		get_currentuserinfo ();
		
		$result = new stdClass ();
		
		if ($current_user && $current_user->ID && $current_user->roles) {
			$roles = $current_user->roles;
			
			$user_role = get_option ( "dam_user_role", "subscriber" );
			
			if (in_array ( $user_role, $roles ) && $current_user->display_name) {
				
				$name = $current_user->display_name;
				$userid = $current_user->ID;
				$email = $current_user->user_email;
				
				$result = dam_auction_adapter::placebid ( $auction_id, $bid_price, $userid, $name, $email );
			
			} else {
				$result->error = "unsign";
			}
		
		} else {
			$result->error = "unsign";
		}
		
		return $result;
	}
	
	static public function get_plugin_url() {
		return plugin_dir_url ( __FILE__ );
	}
	
	static public function unauthenticated_place_bid($auction_id, $bid_price) {
		global $dam_cookie;
		
		$user_name = $dam_cookie->value ( "user_name" );
		$user_email = $dam_cookie->value ( "user_email" );
		
		$result = new stdClass ();
		
		if (! empty ( $user_name ) && ! empty ( $user_email )) {
			
			$result = dam_auction_adapter::placebid ( $auction_id, $bid_price, 0, $user_name, $user_email );
		
		} else {
			
			$result->error = "unactived";
		}
		
		return $result;
	}

}
?>