<?php
include_once "../../../../tools/inc.php";
$page = include("../../../common.php");
include "../tools/class.XMLCreator2.php";
$table="newsletters".$config["table_prefix"];
$table_stat='stat'.$config["table_prefix"];
$n_id=intval($n_id);
$trendHeader='confirmed';

$trend_list=array(
	'confirmed'		=> '{rs:TREND_UNSUBSCRIBES_CONFIRMED}',
	'pending'		=> '{rs:TREND_UNSUBSCRIBES_PENDING}',
);


$trend_by_list=array(
	'day'			=> '{rs:STATISTICS_GRAPH_BY_DAY}',
	'week'			=> '{rs:STATISTICS_GRAPH_BY_WEEK}',
	'month'			=> '{rs:STATISTICS_GRAPH_BY_MONTH}',
);

$trend_by=(isset($trend_by_list[$trend_by]) ? $trend_by : 'day');
$t1=time();
if ($trend_by=='day') {
	$t0=mktime(0, 0, 0, date('m', $t1), date('d', $t1), date('Y', $t1));
	$pt1=mktime(23, 59, 59, date('m', $t1), date('d', $t1)-1, date('Y', $t1));
	$pt0=mktime(0, 0, 0, date('m', $pt1), date('d', $pt1), date('Y', $pt1));
} elseif ($trend_by=='week') {
	$wd=date('w', $t1);
	$wd=($wd ? $wd-1 : 6);
	$t0=mktime(0, 0, 0, date('m', $t1), date('d', $t1)-$wd, date('Y', $t1));
	$pt1=mktime(23, 59, 59, date('m', $t0), date('d', $t0)-1, date('Y', $t0));
	$pt0=mktime(0, 0, 0, date('m', $t0), date('d', $t0)-7, date('Y', $t0));
} else {
	$t0=mktime(0, 0, 0, date('m', $t1), 1, date('Y', $t1));
	$pt1=mktime(23, 59, 59, date('m', $t0), date('d', $t0)-1, date('Y', $t0));
	$pt0=mktime(0, 0, 0, date('m', $pt1), 1, date('Y', $pt1));
}

$sql=array();
$sql['confirmed']=	"select sum(count) from $table_stat
				where
					code='NEWSLETTER[{$n_id}].UNSUBSCRIBES.CONFIRMED' and
					date_created>='%t0%' and
					date_created<='%t1%'
				group by code";
$sql['pending']=	"select sum(count) from $table_stat
				where
					code='NEWSLETTER[{$n_id}].UNSUBSCRIBES.PENDING' and
					date_created>='%t0%' and
					date_created<='%t1%'
				group by code";
$xml=new XMLCreator();
$xml->openTag('items');
foreach ($trend_list as $key => $val) {
	$prev=$db->count(str_replace(array('%t0%', '%t1%'), array($pt0, $pt1), $sql[$key]), true);
	$current=$db->count(str_replace(array('%t0%', '%t1%'), array($t0, $t1), $sql[$key]), true)-$prev;
	$current_percent=($current ? ($current/($prev ? $prev : $current))*100 : 0);
	if ($trendHeader==$key) {
		$trend_count=$current;
		$trend_percent=$current_percent;
	}
	$xml->addTag('item', '', array(
		'id'		=> $key,
		'count'		=> ($current>0 ? '+' : '').number_format($current, 0, ',', ' '),
		'percent'	=> ($current>0 ? '+' : '').number_format($current_percent, (($current_percent<1 and $current_percent>0) ? 2 : 0), ',', ' ').'%',
		'arrow'		=> ($current>0 ? 'up' : ($current<0 ? 'down' : '')),
	));
}
$xml->addTag('item', '', array(
	'id'		=> 'header',
	'count'		=> ($trend_count>0 ? '+' : '').number_format($trend_count, 0, ',', ' '),
	'percent'	=> ($trend_count>0 ? '+' : '').number_format($trend_percent, (($trend_percent<1 and $trend_percent>0) ? 2 : 0), ',', ' ').'%',
	'arrow'		=> '',
));
$xml->output();
exit;
?>