<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Бланк для печати отчета о продажах.
 *
 * Файл: /admin/shop/action/fill_sales_report_blank.php
 *
 * @author Hostmake LLC
 * @version 5.x
 */

$shop = & singleton('shop');
$DateClass = & singleton('DateClass');
$site = & singleton('site');
$DataBase = & singleton('DataBase');

// Начальная дата
if (isset($_POST['sales_order_begin_date']))
{
	$original_date_begin = $_POST['sales_order_begin_date'] . ' 00:00:00';
	$date_begin = quote_smart($DateClass->datetime_format_sql($original_date_begin));
}
else
{
	$date_begin = date("Y-m-d H:i:s", time() - 60*60*24*31);
}

// Конечная дата
if (isset($_POST['sales_order_end_date']))
{
	// Дата окончания должна иметь время 23:59:59
	$original_date_end = $_POST['sales_order_end_date'] . ' 23:59:59';

	$date_end = quote_smart($DateClass->datetime_format_sql($original_date_end));
}
else
{
	$date_end = date("Y-m-d H:i:s");
}

$shop_system_of_pay_id = to_int($_POST['shop_system_of_pay_id']);
$shop_order_status_id = to_int($_POST['shop_order_status_id']);

$site_id = intval(CURRENT_SITE);

$shop_id = to_int($_POST['shop_shops_id']);

// Формируем запрос на получение списка периодов
switch(to_int($_POST['sales_order_grouping']))
{
	case 1: // группировка по неделям
		{
			$format_date_title = '%u';
			$year_title = ",DATE_FORMAT(shop_order_date_time, '%Y') as year_title";
			break;
		}
	case 2: // группировка по дням
		{
			$format_date_title = '%d.%m.%Y';
			$year_title = '';
			break;
		}
	default: // группировка по месяцам
		{
			$format_date_title = '%m %Y';
			$year_title = '';
			break;
		}
}

// Отображать товары только оплаченных заказов

$query_status_of_pay = isset($_REQUEST['sales_order_show_only_paid_items']) ? ' AND shop_order_status_of_pay = 1' : '';

$shop_sallers_id = intval($_REQUEST['shop_sallers_id']);

if ($shop_sallers_id > 0)
{
	$query_from = 'shop_sallers_table,shop_items_catalog_table,';
	$query_where = " AND shop_items_catalog_table.shop_sallers_id = $shop_sallers_id AND shop_sallers_table.shop_sallers_id = shop_items_catalog_table.shop_sallers_id
					AND shop_items_catalog_table.shop_items_catalog_item_id = shop_order_items_table.shop_items_catalog_item_id";
}
else
{
	$query_from = '';
	$query_where = '';
}

$sop = '';

if($shop_system_of_pay_id)
{
	$sop = " AND `shop_system_of_pay_id`='$shop_system_of_pay_id' ";
}

$order_status_string = '';

if($shop_order_status_id)
{
	$order_status_string = " AND `shop_order_status_id`='$shop_order_status_id' ";
}

$query = "SELECT COUNT(DISTINCT (shop_order_table.shop_order_id)) as count_orders, SUM(shop_order_items_quantity) AS count_items,
SUM(shop_order_items_price * shop_order_items_quantity) AS total_sum,
DATE_FORMAT(shop_order_date_time, '$format_date_title') AS date_title
$year_title
FROM $query_from shop_order_table LEFT JOIN shop_order_items_table
ON shop_order_table.shop_order_id = shop_order_items_table.shop_order_id
WHERE shop_order_table.shop_shops_id = $shop_id
$query_status_of_pay
AND shop_order_cancel = 0
AND	shop_order_date_time >= '$date_begin'
AND	shop_order_date_time <= '$date_end'
$sop
$order_status_string
$query_where
GROUP BY `date_title`
ORDER BY `date_title` ASC";

$result_periods = $DataBase->query($query);

$normal_date_begin = htmlspecialchars(to_str($_POST['sales_order_begin_date']));
$normal_date_end = htmlspecialchars(to_str($_POST['sales_order_end_date']));

// Получаем идентификаторы заказов по периодам
// shop_order_table.shop_order_status_of_pay = 1
$query = "SELECT DATE_FORMAT(shop_order_date_time, '$format_date_title') AS date_title,
 shop_order_table.shop_order_id
FROM $query_from shop_order_table LEFT JOIN shop_order_items_table
ON shop_order_table.shop_order_id = shop_order_items_table.shop_order_id
WHERE shop_order_table.shop_shops_id = $shop_id
$query_status_of_pay
AND shop_order_cancel = 0
AND shop_order_date_time >= '$date_begin'
AND shop_order_date_time <= '$date_end'
$sop
$order_status_string
$query_where
GROUP BY `date_title`, `shop_order_items_table`.`shop_order_id`
ORDER BY `date_title`";

$result_periods_orders = $DataBase->query($query);

// Двумерный массив содержащий идентификаторы заказов
$mas_periods_orders = array();

while($row_periods_orders = mysql_fetch_assoc($result_periods_orders))
{
	$mas_periods_orders[$row_periods_orders['date_title']][] = $row_periods_orders['shop_order_id'];
}

// Получаем информацию о магазине
$shop_info = $shop->GetShop($shop_id);

if ($shop_sallers_id > 0)
{
	$saller_row = $shop->GetSeller($shop_sallers_id);
	$saller_title = sprintf($GLOBALS['MSG_shops']['sales_report_title_saller'], $saller_row['shop_sallers_name']);
}
else
{
	$saller_title = '';
}

$report_title = sprintf($GLOBALS['MSG_shops']['sales_report_title'], $shop_info['shop_shops_name'], $normal_date_begin, $normal_date_end, $saller_title);

//Формируем html-код страницы
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title><?php echo $report_title?></title>
<meta http-equiv="Content-Language" content="ru">
<meta content="text/html; charset=UTF-8" http-equiv=Content-Type>
<link rel="stylesheet" type="text/css" href="/admin/css/style.css">
</head>
<body style="margin: 3.5em">

<p style="margin-bottom: 40px"><img src="/admin/images/logo.gif" alt="(^) <?php echo PRODUCT_NAME?>" title="<?php echo PRODUCT_NAME?>"></p>

<h1><?php echo $report_title?></h1>
<?php
if (mysql_num_rows($result_periods) > 0)
{
?>
<table cellpadding="2" cellspacing="2" width="100%" class="admin_table">
  <tr class="admin_table_title" >
    <td></td>
    <td width="100"><?php echo $GLOBALS['MSG_shops']['catalog_marking']?></td>
    <td width="50"><?php echo $GLOBALS['MSG_shops']['form_sales_order_count_orders']?></td>
    <td width="50"><?php echo $GLOBALS['MSG_shops']['form_sales_order_count_items']?></td>
    <td width="100"><?php echo $GLOBALS['MSG_shops']['form_sales_order_total_summ']?></td>
    <td width="100"><?php echo $GLOBALS['MSG_shops']['form_sales_order_status_of_pay']?></td>
    <td width="100"><?php echo $GLOBALS['MSG_shops']['form_sales_order_order_status']?></td>
  </tr>
<?php

$mas_months_name = array(
'01' => $GLOBALS['MSG_shops']['form_sales_order_month_january'],
'02' => $GLOBALS['MSG_shops']['form_sales_order_month_february'],
'03' => $GLOBALS['MSG_shops']['form_sales_order_month_march'],
'04' => $GLOBALS['MSG_shops']['form_sales_order_month_april'],
'05' => $GLOBALS['MSG_shops']['form_sales_order_month_may'],
'06' => $GLOBALS['MSG_shops']['form_sales_order_month_june'],
'07' => $GLOBALS['MSG_shops']['form_sales_order_month_july'],
'08' => $GLOBALS['MSG_shops']['form_sales_order_month_august'],
'09' => $GLOBALS['MSG_shops']['form_sales_order_month_september'],
'10' => $GLOBALS['MSG_shops']['form_sales_order_month_october'],
'11' => $GLOBALS['MSG_shops']['form_sales_order_month_november'],
'12' => $GLOBALS['MSG_shops']['form_sales_order_month_december']);

// Получаем информацию о магазине
$shop_info = $shop->GetShop($shop_id);

// Получаем информацию о валюте магазина
$shop_currency_info = $shop->GetCurrency($shop_info['shop_currency_id']);

$sum_count_orders = 0;
$sum_count_items = 0;
$sum_total_sum = 0;

// Цикл по периодам
while($row_period = mysql_fetch_assoc($result_periods))
{
	switch ($_POST['sales_order_grouping'])
	{
		case 0: // группировка по месяцам
			// Разделяем месяц и год
			$mas_date = explode(' ',$row_period['date_title']);

			$period_title = to_str($mas_months_name[$mas_date[0]]) . ' ' . $mas_date[1];
			break;
		case 1: // группировка по неделям
			$DayLen = 24 * 60 * 60;

			//define("WeekLen",7 * DayLen); // Длина недели в секундах

			$WeekLen = 7 * $DayLen;

			$year = $row_period['year_title'];//1993;
			$week = $row_period['date_title'];//1;

			$StJ = gmmktime(0,0,0,1,1,$year); // 1 января, 00:00:00

			// Определим начало недели, к которой относится 1 января
			$DayStJ = gmdate("w",$StJ);
			$DayStJ = ($DayStJ == 0 ? 7 : $DayStJ);
			$StWeekJ = $StJ - ($DayStJ-1) * $DayLen;

			// Если 1 января относится к 1й неделе, то в $week получается одна "лишняя" неделя
			if( gmdate("W",$StJ) == "01" )$week--;

			 // прибавили к началу "январской" недели номер нашей недели
			$start = $StWeekJ + $week * $WeekLen;

			 // К началу прибавляем недели (получаем след. понедельник, 00:00) и отняли одну секунду - т.е. воскресенье, 23:59
			$end = $start + $WeekLen - 5*60*60;

			$period_title = $row_period['date_title'] . ' неделя,<br />' . date('d.m.Y', $start) . '&mdash;' . date('d.m.Y', $end);
		break;
		default: // группировка по дням
			$period_title = $row_period['date_title'];
		break;
	}
	?>
	<tr class="row_table admin_table_sub_title report_height">
	<td><strong><?php echo $period_title?></strong></td>
    <td>&nbsp;</td>
    <td><?php echo $row_period['count_orders']?></td>
    <td><?php echo to_int($row_period['count_items'])?></td>
    <td><?php echo to_float($row_period['total_sum'])?> <?php echo $shop_currency_info['shop_currency_name']?></td>
    <td></td>
    <td></td>
    </tr>
	<?php

	// Детализация по проданным товарам
	if (isset($_POST['sales_order_show_list_items']))
	{
		if (count($mas_periods_orders[$row_period['date_title']]) > 0)
		{
			$in = '';
			// Формируем строку с идетификаторами заказов
			$in = implode(',', $mas_periods_orders[$row_period['date_title']]);

			// Получаем список товаров
			$query = "SELECT shop_order_items_table.*, `shop_order_table`.`shop_order_account_number`,
			`shop_order_table`.`shop_order_date_of_pay`,
			`shop_order_table`.`shop_order_status_of_pay`,
			`shop_order_table`.`shop_order_status_id`,
			`shop_order_status_table`.`shop_order_status_name`,
			DATE_FORMAT(shop_order_date_time, '%d.%m.%Y') AS `shop_order_date`
			FROM $query_from `shop_order_table`
			LEFT JOIN `shop_order_status_table` USING (`shop_order_status_id`)
			LEFT JOIN `shop_order_items_table`
				ON `shop_order_table`.`shop_order_id` = `shop_order_items_table`.`shop_order_id`
			WHERE `shop_order_table`.`shop_order_id` IN ($in)
			$query_where
			AND `shop_order_table`.`shop_order_cancel` = 0";

			$result_items_order = $DataBase->query($query);

			$order_id = 0;
			while ($row_item_order = mysql_fetch_assoc($result_items_order))
			{
				if ($order_id != $row_item_order['shop_order_account_number'])
				{
					$order_id = $row_item_order['shop_order_account_number'];
					?>
					<tr class="row_table report_height" style="font-size: 120%">
						<td colspan="2"><?php echo sprintf($GLOBALS['MSG_shops']['form_sales_order_orders_number'], $row_item_order['shop_order_account_number'], $row_item_order['shop_order_date'])?><?php
						if ($row_item_order['shop_order_date_of_pay'] != '0000-00-00 00:00:00')
						{
							echo sprintf($GLOBALS['MSG_shops']['form_sales_order_date_of_paid'], $DateClass->admin_datetime_format($row_item_order['shop_order_date_of_pay']));
						}
						?></td>
						<td>&nbsp;</td>
						<td>&nbsp;</td>
						<td><?php echo $shop->GetOrderSum($order_id)?> <?php echo $shop_currency_info['shop_currency_name']?></td>
						<td><?php echo intval($row_item_order['shop_order_status_of_pay']) == 0 ? $GLOBALS['MSG_shops']['form_sales_order_status_of_pay_no'] : $GLOBALS['MSG_shops']['form_sales_order_status_of_pay_yes']?></td>
						<td><?php echo $row_item_order['shop_order_status_name']?></td>
					</tr>
					<?php
				}
				if ($row_item_order['shop_order_items_id'] > 0)
				{
				?><tr class="row_table report_height">
					<td> &mdash; <?php echo $row_item_order['shop_order_items_name']?></td>
					<td><?php echo $row_item_order['shop_order_items_marking']?></td>
					<td>&nbsp;</td>
					<td><?php echo $row_item_order['shop_order_items_quantity']?></td>
					<td><?php echo ($row_item_order['shop_order_items_quantity']*$row_item_order['shop_order_items_price'])?> <?php echo $shop_currency_info['shop_currency_name']?></td>
					<td></td>
					<td></td>
				</tr><?php
				}
			}
		}
	}

	$sum_count_orders += $row_period['count_orders'];
	$sum_count_items += to_int($row_period['count_items']);
	$sum_total_sum += to_float($row_period['total_sum']);
}
?>
<tr class="admin_table_filter row_table admin_table_sub_title">
<td>&nbsp;</td>
<td style="text-align: right">∑</td>
<td><?php echo $sum_count_orders?></td>
<td><?php echo $sum_count_items?></td>
<td><?php echo $sum_total_sum?> <?php echo $shop_currency_info['shop_currency_name']?></td>
<td></td>
<td></td>
</tr>
</table>
<?php
}
else
{
	?><p><?php echo $GLOBALS['MSG_shops']['form_sales_order_empty_orders']?></p><?php
}
?>
</body>
</html>
<?php
exit();