<?php

require '../../db.php';
$key = checkStr($_POST["key"]);
$guest = R::findOne('guest', 'link_key = ?', [$key]);

function checkStr($str){
    $str = strip_tags($str);
    $str = filter_var($str);
    return $str;
}
$tag = $guest['tag'];
switch (trim($_POST['func'])) {
	case "widgetprogressload":
		widgetprogressload($tag);
		break;
	case "widgetcountriesload":
		widgetcountriesload($tag);
		break;	
}

function widgetprogressload($tag)
{
	
	$count_all = R::count('log');
	
	$currentDate = new DateTime(date("Y-m-d"));
	$endDate = new DateTime(date("Y-m-d"));
	$_endDate = new DateTime(date("Y-m-d"));
	$endDate->modify('-3 month');
	$_endDate->modify('-3 month');
	$i = 0;
	$months = array();
	
	while($currentDate >= $endDate) {
		$_endDate -> modify('+7 day');
		$months[date_format($endDate, "Y-m-d")] = R::count('log', 'tag = ? AND add_date BETWEEN ? AND ?', [$tag ,date_format($endDate,'Y-m-d'), date_format($_endDate,'Y-m-d')]);
		$endDate -> modify('+7 day');	
		
	}

	echo json_encode($months);
		
}


function widgetcountriesload($tag)
{
    $countries = R::getAll('SELECT country, COUNT(*) as count FROM log WHERE tag = :tag GROUP BY country ORDER BY count DESC LIMIT 10', [":tag" => $tag]);

	$result = array();
	foreach ($countries as $zone)
	{

        $result[$zone["country"]] = intval($zone["count"]);

	}
	echo json_encode($result);		
}


?>