<?php
$request_uri = $_SERVER[REQUEST_URI] ;
$oTpl->assign( 'request_uri', $request_uri );
if( $a == 'list' || $a == 'finishing' ){
	if( isset( $_POST['sOption'] ) ){
		$oProduct->saveProducts( $_POST );
		$sOption = 'save';
	}
	if( isset( $_POST['sMultipleModifyOption'] ) ){
		switch( $_POST['sMultipleModify'] ){
			case 'delete':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					$oProduct->deleteProduct( $iProduct );
					$sOption = 'delete';
				}
				break;
			case 'modify_price':
				if( !empty( $_POST['sModifyPriceBy'] ) && preg_match( '/(\\-?[0-9]+(\\.[0-9]+)?)(%?)/', $_POST['sModifyPriceBy'], $aMatches ) ){
					$bPercent = ( $aMatches[3] == '%' );
					$fChange = $aMatches[1];
					foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
						if( $bPercent ){
							if( $fChange < 0 ){
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS          ) . '` SET `fPriceOld` = `fPrice`, `fPrice` = ROUND( `fPrice` * ' . ( 1 + $fChange / 100 ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPriceOld` = `fPrice`, `fPrice` = ROUND( `fPrice` * ' . ( 1 + $fChange / 100 ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
							} else{
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS          ) . '` SET `fPrice` = ROUND( `fPrice` * ' . ( 1 + $fChange / 100 ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPrice` = ROUND( `fPrice` * ' . ( 1 + $fChange / 100 ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
							}
						} else{
							if( $fChange < 0 ){
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS          ) . '` SET `fPriceOld` = `fPrice`, `fPrice` = ROUND( `fPrice` + ' . ( $fChange ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPriceOld` = `fPrice`, `fPrice` = ROUND( `fPrice` + ' . ( $fChange ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
							} else{
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS          ) . '` SET `fPrice` = ROUND( `fPrice` + ' . ( $fChange ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
								$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPrice` = ROUND( `fPrice` + ' . ( $fChange ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
							}
						}
					}
					$sOption = 'modify_price';
				}
				break;
			case 'cancel_promotion':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS          ) . '` SET `fPrice` = `fPriceOld`, `fPriceOld` = NULL WHERE `fPriceOld` > 0 AND `iProduct` = ' . intval( $iProduct ) );
					$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPrice` = `fPriceOld`, `fPriceOld` = NULL WHERE `fPriceOld` > 0 AND `iProduct` = ' . intval( $iProduct ) );
					$sOption = 'cancel_promotion';
				}
				break;
			case 'time_price_set':
				$iPriceTimeFrom = dateToTime( $_POST['sPriceTimeFrom'], 'ymd' );
				$iPriceTimeTo = dateToTime( $_POST['sPriceTimeTo'], 'ymd' );
				if( strpos( $_POST['sPriceTimeValue'], '%' ) !== false ){
					$bPercent = true;
					$_POST['sPriceTimeValue'] = 1 - ( substr( $_POST['sPriceTimeValue'], 0, -1 ) / 100 );
				} else{
					$bPercent = false;
				}
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					if( !empty( $_POST['sPriceTimeFrom'] ) ){
						$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS ) . '` SET `iPriceTimeFrom` = ' . intval( $iPriceTimeFrom ) . ' WHERE `iProduct` = ' . intval( $iProduct ) );
					}
					if( !empty( $_POST['sPriceTimeTo'] ) ){
						$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS ) . '` SET `iPriceTimeTo` = ' . intval( $iPriceTimeTo ) . ' WHERE `iProduct` = ' . intval( $iProduct ) );
					}
					if( !empty( $_POST['sPriceTimeValue'] ) ){
						$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS ) . '` SET `fPriceTimeValue` = ROUND( ' . ( $bPercent ? '`fPrice` * ' . $_POST['sPriceTimeValue'] : floatval( $_POST['sPriceTimeValue'] ) ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) );
						$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPriceTimeValue` = ROUND( ' . ( $bPercent ? '`fPrice` * ' . $_POST['sPriceTimeValue'] : floatval( $_POST['sPriceTimeValue'] ) ) . ', 2 ) WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `fPrice` IS NOT NULL' );
					}
					$sOption = 'time_price_set';
				}
				break;
			case 'description':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_EXT ) . '` SET `sDescriptionFull` = \'' . $oDB->escape( $_POST['sDescriptionFull'] ) . '\' WHERE `iProduct` = ' . intval( $iProduct ) );
					$sOption = 'description';
				}
				break;
			case 'options_set':
				if( is_numeric( $_POST['comments'] ) ) $aSet['iComments'] = intval( $_POST['comments'] );
				if( is_numeric( $_POST['compare'] ) ) $aSet['iCompare'] = intval( $_POST['compare'] );
				if( is_numeric( $_POST['active_discount'] ) ) $aSet['iActiveDiscount'] = intval( $_POST['active_discount'] );
				if( is_numeric( $_POST['iStockSendAdminMin'] ) ) $aSet['iStockSendAdminMin'] = intval( $_POST['iStockSendAdminMin'] );
				if( is_numeric( $_POST['active_status'] ) ) $aSet['iStatus'] = intval( $_POST['active_status'] );
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					foreach( $_POST['promoted'] as $iPromoted => $mVal ){
						if( is_numeric( $mVal ) ){
							if( !empty( $mVal ) ){
								$oDB->save( DB_PRODUCTS_PROMOTED, Array( 'iProduct' => $iProduct, 'iPromoted' => $iPromoted ), Array( 'iProduct', 'iPromoted' ) );
							} else{
								$oDB->delete( DB_PRODUCTS_PROMOTED, Array( 'iProduct' => $iProduct, 'iPromoted' => $iPromoted ) );
							}
						}
					}
					if( !empty( $aSet ) ){
						$oDB->update( DB_PRODUCTS, $aSet, Array( 'iProduct' => $iProduct ) );
						$oDB->update( DB_PRODUCTS_EXT, $aSet, Array( 'iProduct' => $iProduct ) );
					}
					$sOption = 'options_set';
				}
				break;
			case 'carriers_prices_set':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					$oDB->delete( DB_PRODUCTS_CARRIERS_PRICES, Array( 'iProduct' => $iProduct ) );
					foreach( $_POST['aCarrierPrice'] as $iCarrier => $fPrice ) if( $fPrice !== '' ){
						$oDB->save( DB_PRODUCTS_CARRIERS_PRICES, Array( 'iProduct' => $iProduct, 'iCarrier' => $iCarrier, 'fPrice' => $fPrice ) );
					}
					$sOption = 'carriers_prices_set';
				}
				break;
			case 'discounts':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					$oDB->update( DB_PRODUCTS, Array( 'iVisibleAll' => $_POST['iVisibleAll'], 'iVisiblePriceAll' => $_POST['iVisiblePriceAll'], 'iCanBuyAll' => $_POST['iCanBuyAll'] ), Array( 'iProduct' => $iProduct ) );
					if( !isset( $_POST['aGroupsInfo'] ) ){
						$_POST['aGroupsInfo'] = Array();
					}
					foreach( $_POST['aDiscounts'] as $iGroup => $fDiscount ){
						if( $fDiscount !== '' ){
							$_POST['aGroupsInfo'][$iGroup]['fMultiply'] = 1 - $fDiscount;
						}
					}
					$oDB->deleteInFile( DB_PRODUCTS_DISCOUNTS, $iProduct, 'iProduct' );
					foreach( $_POST['aGroupsInfo'] as $iGroup => $aGroupInfo ){
						$aGroupInfo['iProduct'] = $iProduct;
						$aGroupInfo['iGroup'] = $iGroup;
						$oDB->save( DB_PRODUCTS_DISCOUNTS, $aGroupInfo, null );
					}
					$sOption = 'discounts';
				}
				break;
			case 'related':
				if( is_numeric( $_POST['iRelated'] ) ){
					$aValues = Array();
					foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
						foreach( $_POST['aProductsSelect'] as $iProductRelated ) if( is_numeric( $iProductRelated ) && $iProductRelated != $iProduct ){
							$aValues[] = '( ' . intval( $iProduct ) . ', ' . intval( $iProductRelated ) . ', ' . intval( $_POST['iRelated'] ) . ' )';
						}
					}
					if( !empty( $aValues ) ){
						$oDB->executeSQL( 'INSERT IGNORE INTO `' . $oDB->throwTableName( DB_PRODUCTS_RELATED ) . '` ( `iProduct`, `iRelated`, `iBox` ) VALUES ' . implode( ', ', $aValues ) );
						$sOption = 'related';
					}
				}
				break;
			case 'advsearcher':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					foreach( $_POST['aAdvsearcherValues'] as $iAdvsearcherValue ) if( is_numeric( $iAdvsearcherValue ) ){
						$oDB->executeSQL( 'INSERT IGNORE INTO `' . $oDB->throwTableName( DB_ADVSEARCHER_PRODUCTS ) . '` ( `iValue`, `iProduct` ) VALUES ( ' . intval( $iAdvsearcherValue ) . ', ' . intval( $iProduct ) . ' )' );
					}
				}
				break;
			case 'advsearcher_clear':
				foreach( $_POST['aProductsSelect'] as $iProduct ) if( is_numeric( $iProduct ) ){
					$oDB->deleteInFile( DB_ADVSEARCHER_PRODUCTS, $iProduct, 'iProduct' );
				}
				break;
		}
		header( 'Location: admin.php?p=' . $_GET['p'] . '&sOption=' . $sOption );
		exit;
	}
	if( isset( $sOption ) ){
		$content.= $oTpl->parse( 'message_done.tpl' );
	}
	$sSort = $_GET['sort'];
//	$aProducts = $oProduct->listProductsAdmin( );
	$aSearch = Array( 'aSearchCategories' => $oPage->throwCategories( $config['search_category'], $iCategory, 0 ), 'aProducers' => throwProducersForSelect( ), 'aAttributes' => throwAttributesValuesSelects( true ), 'aSelectedAttributes' => $aAttributeValue, );
	if( $aActions['o1'] == 'export' ){
		if( $a == 'list' )
			$aProducts = $oProduct->listProductsAdmin( 'inf' );
		elseif( $a == 'finishing' )
			$aProducts = $oProduct->listProductsAdminFinishing( 'inf' );

		require_once 'libraries/PHPExcel.php';

		$objPHPExcel = PHPExcel_IOFactory::load( DIR_TEMPLATES . 'admin/export.xlsx' );
		$objWorksheet = $objPHPExcel->getActiveSheet( );
		$styleArrayHeader = array( 'font' => array( 'color' => array( 'argb' => 'FFFFFFFF' ), ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FF376091', ), ), );
		$styleArrayProduct = array( 'font' => array( 'bold' => true, ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FF8DB4E3', ), ), );
		$styleArrayVariant1 = array( 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FFD8D8D8', ), ), );
		$styleArrayVariant2 = array( 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FFFFFFFF', ), ), );
		$iRow = 2;
		$objWorksheet->getStyle( 'A' . $iRow . ':H' . $iRow )->applyFromArray( $styleArrayHeader );
		$sStore = $oDB->executeSQL( 'SELECT `sName` FROM `' . $oDB->throwTableName( DB_STORES ) . '` WHERE `iStore` = ' . intval( $iStore ), true, DataBase::SINGLE_VALUE );
		$objWorksheet->getCellByColumnAndRow( 1, 1 )->setValue( $sStore );

		foreach( $aProducts['aList'] as $aProduct ){
			$iProduct = $aProduct['iProduct'];
			$iRow++;
			$objWorksheet->getStyle( 'A' . $iRow . ':H' . $iRow )->applyFromArray( $styleArrayProduct );
			$aData = $oProduct->throwProduct( $iProduct );
			$aProducer = throwProducer( $aData['iProducer'] );
			$objWorksheet->getCellByColumnAndRow( 0, $iRow )->setValue( $aData['iProduct'] );
			$objWorksheet->getCellByColumnAndRow( 2, $iRow )->setValue( $aData['iMainCategory'] );
			$objWorksheet->getCellByColumnAndRow( 3, $iRow )->setValue( $oPage->aPages[$aData['iMainCategory']]['sName'] );
			$objWorksheet->getCellByColumnAndRow( 4, $iRow )->setValue( $aData['sName'] );
			$objWorksheet->getCellByColumnAndRow( 5, $iRow )->setValue( $aProducer['sName'] );
			$objWorksheet->getCellByColumnAndRow( 6, $iRow )->setValue( $aData['fPrice'] );
			list( $aVariants, $aAttributes ) = $oProduct->throwAdminVariants( $aData['iProduct'] );
			$iAlt = true;
			foreach( $aVariants as $aVariant ){
				$iRow++;
				$iAlt = !$iAlt;
				$objWorksheet->getStyle( 'A' . $iRow . ':H' . $iRow )->applyFromArray( $iAlt ? $styleArrayVariant1 : $styleArrayVariant2 );
				$aVariant['sName'] = $aData['sName'];
				foreach( $aAttributes as $aAttribute ){
					if( $aAttribute['bActive'] ){
						foreach( $aAttribute['aValues'] as $iValue => $sValue ){
							if( in_array( $iValue, $aVariant['aValues'] ) ) $aVariant['sName'].= ', ' . $aAttribute['sName'] . ': ' . $sValue;
						}
					}
				}
				$objWorksheet->getCellByColumnAndRow( 0, $iRow )->setValue( $aData['iProduct'] );
				$objWorksheet->getCellByColumnAndRow( 1, $iRow )->setValue( $aVariant['iProductVariant'] );
				$objWorksheet->getCellByColumnAndRow( 4, $iRow )->setValue( $aVariant['sName'] );
				$objWorksheet->getCellByColumnAndRow( 6, $iRow )->setValue( $aVariant['fPrice'] );
				$objWorksheet->getCellByColumnAndRow( 7, $iRow )->setValue( $aVariant['aStore'][$iStore]['iStock'] );
			}
		}
		$objWorksheet->getStyle( 'G2:G' . $iRow )->getNumberFormat( )->setFormatCode( '#,##0.00_-"' . $config['currency_symbol'] . '"' );
		$objWorksheet->getColumnDimension( 'E' )->setAutoSize( true );
		$objWorksheet->getColumnDimension( 'F' )->setAutoSize( true );
		$objWriter = new PHPExcel_Writer_Excel5( $objPHPExcel );
		$objWriter->save( 'upload/export/export.xls' );
		header( 'Content-type: application/vnd.ms-excel' );
		header( 'Content-disposition: attachment; filename=export-' . date( 'Ymd' ) . '.xls' );
		readfile( 'upload/export/export.xls' );
		unlink( 'upload/export/export.xls' );
		exit;
	} else{
		if( $a == 'list' )
			$aProducts = $oProduct->listProductsAdmin( );
		elseif( $a == 'finishing' )
			$aProducts = $oProduct->listProductsAdminFinishing( );
		$aGeneralInfo['aCarriers'] = $oOrder->throwCarriersAdmin( );
		$aGeneralInfo['aUsersGroups'] = throwGroups( );
		$aGeneralInfo['aAdvsearcherColumns'] = $oDB->throwFileArraySmall( DB_ADVSEARCHER_COLUMNS, 'iColumn', 'sName' );
		$aGeneralInfo['aAdvsearcherValues'] = $oDB->throwFileArraySmall( DB_ADVSEARCHER_VALUES, 'iValue', 'sValue', null, Array( 'iColumn' => reset( array_keys( $aGeneralInfo['aAdvsearcherColumns'] ) ) ) );
		$oTpl->assign( 'aStores', $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName', 'iPriority' ) );
		$oTpl->assign( 'a', $a );
		$oTpl->assign( 'aSearch', $aSearch );
		$oTpl->assign( 'aProducts', $aProducts );
		$oTpl->assign( 'aGeneralInfo', $aGeneralInfo );
		$oTpl->assign( 'sSort', $sSort );
		$oTpl->assign( 'sUrlExt', $sUrlExt );
		$content.= $oTpl->parse( 'products_list.tpl' );
	}
} elseif( $a == 'select' ){
	$aSearch = Array( 'aSearchCategories' => $oPage->throwCategories( $config['search_category'], $iCategory, 0 ), 'aProducers' => throwProducersForSelect( ), );
	$aProducts = $oProduct->listProductsAdmin( );
	$oTpl->assign( 'a', $a );
	$oTpl->assign( 'aSearch', $aSearch );
	$oTpl->assign( 'aProducts', $aProducts );
	$oTpl->assign( 'sUrlExt', $sUrlExt );
	echo $oTpl->parse( 'products_select.tpl' );
	exit;
} elseif( $a == 'multiselect' ){
	$aSearch = Array( 'aSearchCategories' => $oPage->throwCategories( $config['search_category'], $iCategory, 0 ), 'aProducers' => throwProducersForSelect( ), );
	$aProducts = $oProduct->listProductsAdmin( );
	$oTpl->assign( 'a', $a );
	$oTpl->assign( 'aSearch', $aSearch );
	$oTpl->assign( 'aProducts', $aProducts );
	$oTpl->assign( 'sUrlExt', $sUrlExt );
	echo $oTpl->parse( 'products_multiselect.tpl' );
	exit;
} elseif( $a == 'statsall' ){
	if( !empty( $_POST['aReferersDomains'] ) ){
		$oDB->deleteInFile( DB_REFERERS );
		foreach( $_POST['aReferersDomains'] as $iReferer => $sDomain ){
			$aReferer = Array( 'sDomain' => $sDomain, 'sColor' => substr( $_POST['aReferersColors'][$iReferer], 1, 6 ), 'fPrice' => $_POST['aReferersPrices'][$iReferer], 'sName' => $_POST['aReferersNames'][$iReferer] );
			$oDB->save( DB_REFERERS, $aReferer );
		}
		foreach( $_POST['aReferersDomainsAdd'] as $iReferer => $sDomain ){
			if( !empty( $_POST['aReferersColorsAdd'][$iReferer] ) || !empty( $_POST['aReferersPricesAdd'][$iReferer] ) || !empty( $_POST['aReferersNamesAdd'][$iReferer] ) ){
				$aReferer = Array( 'sDomain' => $sDomain, 'sColor' => substr( $_POST['aReferersColorsAdd'][$iReferer], 1, 6 ), 'fPrice' => $_POST['aReferersPricesAdd'][$iReferer], 'sName' => $_POST['aReferersNamesAdd'][$iReferer] );
				$oDB->save( DB_REFERERS, $aReferer );
			}
		}
		$content.= $oTpl->parse( 'message_done.tpl' );
	}
	$aReferers = $oDB->throwFileArray( DB_REFERERS );
	$oTpl->assign( 'aReferers', $aReferers );
	$aReferersAdd = $oDB->executeSQL( 'SELECT `sRefererDomain`, `r`.`iElement` FROM ( SELECT DISTINCT `sRefererDomain` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `sRefererDomain` IS NOT NULL AND `sRefererDomain` != \'\' ) AS `sq` LEFT JOIN `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` ON( `sq`.`sRefererDomain` = `r`.`sDomain` ) HAVING `iElement` IS NULL', true, DataBase::SINGLE_COLUMN );
	$oTpl->assign( 'aReferersAdd', $aReferersAdd );


	$aStats['aHourVisits'] = $oDB->executeSQL( 'SELECT HOUR( FROM_UNIXTIME( `iTime` ) ) AS `iHour`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` GROUP BY HOUR( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iHour' );
	$aStats['aHourOrders'] = $oDB->executeSQL( 'SELECT HOUR( FROM_UNIXTIME( `iTime` ) ) AS `iHour`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) GROUP BY HOUR( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iHour' );
	for( $iHour = 0; $iHour < 24; $iHour++ ){
		if( !isset( $aStats['aHourVisits'][$iHour] ) ) $aStats['aHourVisits'][$iHour] = Array( 'iHour' => $iHour, 'iVisits' => 0 );
		if( !isset( $aStats['aHourOrders'][$iHour] ) ) $aStats['aHourOrders'][$iHour] = Array( 'iHour' => $iHour, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	ksort( $aStats['aHourVisits'] );
	ksort( $aStats['aHourOrders'] );

	$aStats['aMonthVisits'] = $oDB->executeSQL( 'SELECT MONTH( FROM_UNIXTIME( `iTime` ) ) AS `iMonth`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` GROUP BY MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iMonth' );
	$aStats['aMonthOrders'] = $oDB->executeSQL( 'SELECT MONTH( FROM_UNIXTIME( `iTime` ) ) AS `iMonth`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) GROUP BY MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iMonth' );
	for( $iMonth = 1; $iMonth <= 12; $iMonth++ ){
		if( !isset( $aStats['aMonthVisits'][$iMonth] ) ) $aStats['aMonthVisits'][$iMonth] = Array( 'iMonth' => $iMonth, 'iVisits' => 0 );
		if( !isset( $aStats['aMonthOrders'][$iMonth] ) ) $aStats['aMonthOrders'][$iMonth] = Array( 'iMonth' => $iMonth, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	ksort( $aStats['aMonthVisits'] );
	ksort( $aStats['aMonthOrders'] );
	
	$aStats['a5YearsVisits'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 5*365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$aStats['a5YearsOrders'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iTime` > UNIX_TIMESTAMP( ) - 5*365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$iFirstYear = date( 'Y' ) - 5;
	$iLastYear = date( 'Y' );
	for( $iYear = $iFirstYear; $iYear <= $iLastYear; $iYear++ ){
		for( $iMonth = ( ( $iYear == $iFirstYear ) ? date( 'n' ) : 1 ); $iMonth <= ( ( $iYear == $iLastYear ) ? date( 'n' ) : 12 ); $iMonth++ ){
			$sMonth = $iYear . '-' . $iMonth;
			if( !isset( $aStats['a5YearsVisits'][$sMonth] ) ) $aStats['a5YearsVisits'][$sMonth] = Array( 'sMonth' => $sMonth, 'iVisits' => 0 );
			if( !isset( $aStats['a5YearsOrders'][$sMonth] ) ) $aStats['a5YearsOrders'][$sMonth] = Array( 'sMonth' => $sMonth, 'iOrders' => 0, 'iQuantitySum' => 0 );
		}
	}
	uksort( $aStats['a5YearsVisits'], 'strnatcasecmp' );
	uksort( $aStats['a5YearsOrders'], 'strnatcasecmp' );

	$aStats['a30DaysVisits'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 30*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$aStats['a62DaysOrders'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iTime` > UNIX_TIMESTAMP( ) - 62*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$iFirstDateTime = time( ) - 30*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['a30DaysVisits'][$sDay] ) ) $aStats['a30DaysVisits'][$sDay] = Array( 'sDay' => $sDay, 'iVisits' => 0 );
	}
	$iFirstDateTime = time( ) - 62*24*3600;
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['a62DaysOrders'][$sDay] ) ) $aStats['a62DaysOrders'][$sDay] = Array( 'sDay' => $sDay, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	uksort( $aStats['a30DaysVisits'], 'strnatcasecmp' );
	uksort( $aStats['a62DaysOrders'], 'strnatcasecmp' );

	$aStats['a90DaysVisits'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 90*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$aStats['a90DaysOrders'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iTime` > UNIX_TIMESTAMP( ) - 90*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$iFirstDateTime = time( ) - 90*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['a90DaysVisits'][$sDay] ) ) $aStats['a90DaysVisits'][$sDay] = Array( 'sDay' => $sDay, 'iVisits' => 0 );
		if( !isset( $aStats['a90DaysOrders'][$sDay] ) ) $aStats['a90DaysOrders'][$sDay] = Array( 'sDay' => $sDay, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	uksort( $aStats['a90DaysVisits'], 'strnatcasecmp' );
	uksort( $aStats['a90DaysOrders'], 'strnatcasecmp' );

	$aStats['aLastYearVisits'] = $oDB->executeSQL( 'SELECT YEARWEEK( FROM_UNIXTIME( `iTime` ) ) AS `sWeek`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEARWEEK( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sWeek' );
	$aStats['aLastYearOrders'] = $oDB->executeSQL( 'SELECT YEARWEEK( FROM_UNIXTIME( `iTime` ) ) AS `sWeek`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEARWEEK( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sWeek' );
	$iFirstDateTime = time( ) - 365*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=7*24*3600 ){
		$sWeek = date( 'oW', $iDateTime );
		if( !isset( $aStats['aLastYearVisits'][$sWeek] ) ) $aStats['aLastYearVisits'][$sWeek] = Array( 'sWeek' => $sWeek, 'iVisits' => 0 );
		if( !isset( $aStats['aLastYearOrders'][$sWeek] ) ) $aStats['aLastYearOrders'][$sWeek] = Array( 'sWeek' => $sWeek, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	uksort( $aStats['aLastYearVisits'], 'strnatcasecmp' );
	uksort( $aStats['aLastYearOrders'], 'strnatcasecmp' );

	$aStats['aRefererStats'] = $oDB->executeSQL( 'SELECT `sRefererDomain` AS `sDomain`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iTime` >= 1487089132 GROUP BY IFNULL( `sRefererDomain`, \'-\' )', true, DataBase::ASSOCIATIVE, 'sDomain' ); // 1487089132 - od tego momentu zapisywane są referery w oponyialufelgi.pl

	$iTimeStart = mktime( 0, 0, 0, date('n')-1, 1 );
	$iTimeEnd = mktime( 0, 0, 0, date('n'), 1 );
	$aStats['aRefVisitsLastMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `ps`.`iElement` ) AS `iVisits`, SUM( `r`.`fPrice` ) AS `fCost` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` `ps` ON( `r`.`sDomain` = `ps`.`sRefererDomain` ) WHERE `ps`.`iTime` BETWEEN '.$iTimeStart.' AND '.$iTimeEnd.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	$aStats['aRefOrdersLastMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `o`.`iOrder` ) AS `iOrders`, SUM( `op`.`iQuantity` ) AS `iSumQuantity`, SUM( `op`.`fPrice` * `op`.`iQuantity` ) AS `fSumPrice`, SUM( ( `op`.`fPrice` - `op`.`fBuyPrice` ) * `op`.`iQuantity` ) AS `fMargin` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` ON( `r`.`sDomain` = `o`.`sOuterRefererDomain` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` USING( `iOrder` ) WHERE `iTime` BETWEEN '.$iTimeStart.' AND '.$iTimeEnd.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	
	$iTimeStart = mktime( 0, 0, 0, date('n'), 1 );
	$aStats['aRefVisitsCurrentMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `ps`.`iElement` ) AS `iVisits`, SUM( `r`.`fPrice` ) AS `fCost` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` `ps` ON( `r`.`sDomain` = `ps`.`sRefererDomain` ) WHERE `ps`.`iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	$aStats['aRefOrdersCurrentMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `o`.`iOrder` ) AS `iOrders`, SUM( `op`.`iQuantity` ) AS `iSumQuantity`, SUM( `op`.`fPrice` * `op`.`iQuantity` ) AS `fSumPrice`, SUM( ( `op`.`fPrice` - `op`.`fBuyPrice` ) * `op`.`iQuantity` ) AS `fMargin` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` ON( `r`.`sDomain` = `o`.`sOuterRefererDomain` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` USING( `iOrder` ) WHERE `iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	
	$iTimeStart = mktime( 0, 0, 0, date('n')-12, 1 );
	$aStats['aRefVisitsCurrentYear'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `ps`.`iElement` ) AS `iVisits`, SUM( `r`.`fPrice` ) AS `fCost` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` `ps` ON( `r`.`sDomain` = `ps`.`sRefererDomain` ) WHERE `ps`.`iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	$aStats['aRefOrdersCurrentYear'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `o`.`iOrder` ) AS `iOrders`, SUM( `op`.`iQuantity` ) AS `iSumQuantity`, SUM( `op`.`fPrice` * `op`.`iQuantity` ) AS `fSumPrice`, SUM( ( `op`.`fPrice` - `op`.`fBuyPrice` ) * `op`.`iQuantity` ) AS `fMargin` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` ON( `r`.`sDomain` = `o`.`sOuterRefererDomain` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` USING( `iOrder` ) WHERE `iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	
	$aStats['aBuyTimes'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, AVG( `iTime` - `iRefererTime` ) AS `iAvgTime`, MIN( `iTime` - `iRefererTime` ) AS `iMinTime`, MAX( `iTime` - `iRefererTime` ) AS `iMaxTime` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$iFirstYear = date( 'Y' ) - 1;
	$iLastYear = date( 'Y' );
	for( $iYear = $iFirstYear; $iYear <= $iLastYear; $iYear++ ){
		for( $iMonth = ( ( $iYear == $iFirstYear ) ? date( 'n' ) : 1 ); $iMonth <= ( ( $iYear == $iLastYear ) ? date( 'n' ) : 12 ); $iMonth++ ){
			$sMonth = $iYear . '-' . $iMonth;
			if( !isset( $aStats['aBuyTimes'][$sMonth] ) ) $aStats['aBuyTimes'][$sMonth] = Array( 'sMonth' => $sMonth, 'iMinTime' => 0, 'iAvgTime' => 0, 'iMaxTime' => 0 );
			
		}
	}
	uksort( $aStats['aBuyTimes'], 'strnatcasecmp' );
	
	$aStats['aBuyTimes2'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, AVG( `iTime` - `iRefererTime` ) AS `iAvgTime`, MIN( `iTime` - `iRefererTime` ) AS `iMinTime`, MAX( `iTime` - `iRefererTime` ) AS `iMaxTime` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 62*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$iFirstDateTime = time( ) - 61*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['aBuyTimes2'][$sDay] ) ) $aStats['aBuyTimes2'][$sDay] = Array( 'sDay' => $sDay, 'iMinTime' => 0, 'iAvgTime' => 0, 'iMaxTime' => 0 );
	}
	uksort( $aStats['aBuyTimes2'], 'strnatcasecmp' );
	
	$aStats['aBuyTimes3'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, COUNT( IF( `iTime` - `iRefererTime` < 1*3600, 1, NULL ) ) AS `iLowerThan1h`, COUNT( IF( `iTime` - `iRefererTime` >= 1*3600 AND `iTime` - `iRefererTime` < 12*3600, 1, NULL ) ) AS `iLowerThan12h`, COUNT( IF( `iTime` - `iRefererTime` >= 12*3600 AND `iTime` - `iRefererTime` < 1*24*3600, 1, NULL ) ) AS `iLowerThan1Day`, COUNT( IF( `iTime` - `iRefererTime` >= 1*24*3600 AND `iTime` - `iRefererTime` < 3*24*3600, 1, NULL ) ) AS `iLowerThan3Days`, COUNT( IF( `iTime` - `iRefererTime` >= 3*24*3600 AND `iTime` - `iRefererTime` < 7*24*3600, 1, NULL ) ) AS `iLowerThan7Days`, COUNT( IF( `iTime` - `iRefererTime` >= 7*24*3600 AND `iTime` - `iRefererTime` < 30*24*3600, 1, NULL ) ) AS `iLowerThan30Days`, COUNT( IF( `iTime` - `iRefererTime` >= 30*24*3600, 1, NULL ) ) AS `iHigherThan30Days` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` WHERE `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$iFirstYear = date( 'Y' ) - 1;
	$iLastYear = date( 'Y' );
	for( $iYear = $iFirstYear; $iYear <= $iLastYear; $iYear++ ){
		for( $iMonth = ( ( $iYear == $iFirstYear ) ? date( 'n' ) : 1 ); $iMonth <= ( ( $iYear == $iLastYear ) ? date( 'n' ) : 12 ); $iMonth++ ){
			$sMonth = $iYear . '-' . $iMonth;
			if( !isset( $aStats['aBuyTimes3'][$sMonth] ) ) $aStats['aBuyTimes3'][$sMonth] = Array( 'sMonth' => $sMonth, 'iLowerThan1h' => 0, 'iLowerThan12h' => 0, 'iLowerThan1Day' => 0, 'iLowerThan3Days' => 0, 'iLowerThan7Days' => 0, 'iLowerThan30Days' => 0, 'iHigherThan30Days' => 0 );
			
		}
	}
	uksort( $aStats['aBuyTimes3'], 'strnatcasecmp' );

	$oTpl->assign( 'aStats', $aStats );
	$aReferersColors = $oDB->throwFileArraySmall( DB_REFERERS, 'sDomain', 'sColor' );
	$oTpl->assign( 'aReferersColors', $aReferersColors );

	$content .= $oTpl->parse( 'products_stats.tpl' );
} elseif( $a == 'form' && $tab == 'product-stats' ){
	$aStats['aHourVisits'] = $oDB->executeSQL( 'SELECT HOUR( FROM_UNIXTIME( `iTime` ) ) AS `iHour`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' GROUP BY HOUR( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iHour' );
	$aStats['aHourOrders'] = $oDB->executeSQL( 'SELECT HOUR( FROM_UNIXTIME( `iTime` ) ) AS `iHour`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iProduct` = ' . intval( $iProduct ) . ' GROUP BY HOUR( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iHour' );
	for( $iHour = 0; $iHour < 24; $iHour++ ){
		if( !isset( $aStats['aHourVisits'][$iHour] ) ) $aStats['aHourVisits'][$iHour] = Array( 'iHour' => $iHour, 'iVisits' => 0 );
		if( !isset( $aStats['aHourOrders'][$iHour] ) ) $aStats['aHourOrders'][$iHour] = Array( 'iHour' => $iHour, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	ksort( $aStats['aHourVisits'] );
	ksort( $aStats['aHourOrders'] );

	$aStats['aMonthVisits'] = $oDB->executeSQL( 'SELECT MONTH( FROM_UNIXTIME( `iTime` ) ) AS `iMonth`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' GROUP BY MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iMonth' );
	$aStats['aMonthOrders'] = $oDB->executeSQL( 'SELECT MONTH( FROM_UNIXTIME( `iTime` ) ) AS `iMonth`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iProduct` = ' . intval( $iProduct ) . ' GROUP BY MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'iMonth' );
	for( $iMonth = 1; $iMonth <= 12; $iMonth++ ){
		if( !isset( $aStats['aMonthVisits'][$iMonth] ) ) $aStats['aMonthVisits'][$iMonth] = Array( 'iMonth' => $iMonth, 'iVisits' => 0 );
		if( !isset( $aStats['aMonthOrders'][$iMonth] ) ) $aStats['aMonthOrders'][$iMonth] = Array( 'iMonth' => $iMonth, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	ksort( $aStats['aMonthVisits'] );
	ksort( $aStats['aMonthOrders'] );
	
	$aStats['a5YearsVisits'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 5*365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$aStats['a5YearsOrders'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 5*365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$iFirstYear = date( 'Y' ) - 5;
	$iLastYear = date( 'Y' );
	for( $iYear = $iFirstYear; $iYear <= $iLastYear; $iYear++ ){
		for( $iMonth = ( ( $iYear == $iFirstYear ) ? date( 'n' ) : 1 ); $iMonth <= ( ( $iYear == $iLastYear ) ? date( 'n' ) : 12 ); $iMonth++ ){
			$sMonth = $iYear . '-' . $iMonth;
			if( !isset( $aStats['a5YearsVisits'][$sMonth] ) ) $aStats['a5YearsVisits'][$sMonth] = Array( 'sMonth' => $sMonth, 'iVisits' => 0 );
			if( !isset( $aStats['a5YearsOrders'][$sMonth] ) ) $aStats['a5YearsOrders'][$sMonth] = Array( 'sMonth' => $sMonth, 'iOrders' => 0, 'iQuantitySum' => 0 );
		}
	}
	uksort( $aStats['a5YearsVisits'], 'strnatcasecmp' );
	uksort( $aStats['a5YearsOrders'], 'strnatcasecmp' );

	$aStats['a30DaysVisits'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 30*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$aStats['a62DaysOrders'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 62*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$iFirstDateTime = time( ) - 30*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['a30DaysVisits'][$sDay] ) ) $aStats['a30DaysVisits'][$sDay] = Array( 'sDay' => $sDay, 'iVisits' => 0 );
	}
	$iFirstDateTime = time( ) - 62*24*3600;
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['a62DaysOrders'][$sDay] ) ) $aStats['a62DaysOrders'][$sDay] = Array( 'sDay' => $sDay, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	uksort( $aStats['a30DaysVisits'], 'strnatcasecmp' );
	uksort( $aStats['a62DaysOrders'], 'strnatcasecmp' );

	$aStats['a90DaysVisits'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 90*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$aStats['a90DaysOrders'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 90*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$iFirstDateTime = time( ) - 90*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['a90DaysVisits'][$sDay] ) ) $aStats['a90DaysVisits'][$sDay] = Array( 'sDay' => $sDay, 'iVisits' => 0 );
		if( !isset( $aStats['a90DaysOrders'][$sDay] ) ) $aStats['a90DaysOrders'][$sDay] = Array( 'sDay' => $sDay, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	uksort( $aStats['a90DaysVisits'], 'strnatcasecmp' );
	uksort( $aStats['a90DaysOrders'], 'strnatcasecmp' );

	$aStats['aLastYearVisits'] = $oDB->executeSQL( 'SELECT YEARWEEK( FROM_UNIXTIME( `iTime` ) ) AS `sWeek`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEARWEEK( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sWeek' );
	$aStats['aLastYearOrders'] = $oDB->executeSQL( 'SELECT YEARWEEK( FROM_UNIXTIME( `iTime` ) ) AS `sWeek`, COUNT( `iOrder` ) AS `iOrders`, SUM( `iQuantity` ) AS `iQuantitySum` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` USING( `iOrder` ) WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEARWEEK( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sWeek' );
	$iFirstDateTime = time( ) - 365*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=7*24*3600 ){
		$sWeek = date( 'oW', $iDateTime );
		if( !isset( $aStats['aLastYearVisits'][$sWeek] ) ) $aStats['aLastYearVisits'][$sWeek] = Array( 'sWeek' => $sWeek, 'iVisits' => 0 );
		if( !isset( $aStats['aLastYearOrders'][$sWeek] ) ) $aStats['aLastYearOrders'][$sWeek] = Array( 'sWeek' => $sWeek, 'iOrders' => 0, 'iQuantitySum' => 0 );
	}
	uksort( $aStats['aLastYearVisits'], 'strnatcasecmp' );
	uksort( $aStats['aLastYearOrders'], 'strnatcasecmp' );

	$aStats['aRefererStats'] = $oDB->executeSQL( 'SELECT `sRefererDomain` AS `sDomain`, COUNT( `iElement` ) AS `iVisits` FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE `iProduct` = ' . intval( $iProduct ) . ' AND `iTime` >= 1487089132 GROUP BY IFNULL( `sRefererDomain`, \'-\' )', true, DataBase::ASSOCIATIVE, 'sDomain' ); // 1487089132 - od tego momentu zapisywane są referery w oponyialufelgi.pl

	$iTimeStart = mktime( 0, 0, 0, date('n')-1, 1 );
	$iTimeEnd = mktime( 0, 0, 0, date('n'), 1 );
	$aStats['aRefVisitsLastMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `ps`.`iElement` ) AS `iVisits`, SUM( `r`.`fPrice` ) AS `fCost` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` `ps` ON( `r`.`sDomain` = `ps`.`sRefererDomain` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `ps`.`iTime` BETWEEN '.$iTimeStart.' AND '.$iTimeEnd.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	$aStats['aRefOrdersLastMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `o`.`iOrder` ) AS `iOrders`, SUM( `op`.`iQuantity` ) AS `iSumQuantity`, SUM( `op`.`fPrice` * `op`.`iQuantity` ) AS `fSumPrice`, SUM( ( `op`.`fPrice` - `op`.`fBuyPrice` ) * `op`.`iQuantity` ) AS `fMargin` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` ON( `r`.`sDomain` = `o`.`sOuterRefererDomain` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` USING( `iOrder` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` USING( `iProductVariant` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `iTime` BETWEEN '.$iTimeStart.' AND '.$iTimeEnd.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	
	$iTimeStart = mktime( 0, 0, 0, date('n'), 1 );
	$aStats['aRefVisitsCurrentMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `ps`.`iElement` ) AS `iVisits`, SUM( `r`.`fPrice` ) AS `fCost` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` `ps` ON( `r`.`sDomain` = `ps`.`sRefererDomain` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `ps`.`iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	$aStats['aRefOrdersCurrentMonth'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `o`.`iOrder` ) AS `iOrders`, SUM( `op`.`iQuantity` ) AS `iSumQuantity`, SUM( `op`.`fPrice` * `op`.`iQuantity` ) AS `fSumPrice`, SUM( ( `op`.`fPrice` - `op`.`fBuyPrice` ) * `op`.`iQuantity` ) AS `fMargin` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` ON( `r`.`sDomain` = `o`.`sOuterRefererDomain` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` USING( `iOrder` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` USING( `iProductVariant` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	
	$iTimeStart = mktime( 0, 0, 0, date('n')-12, 1 );
	$aStats['aRefVisitsCurrentYear'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `ps`.`iElement` ) AS `iVisits`, SUM( `r`.`fPrice` ) AS `fCost` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` `ps` ON( `r`.`sDomain` = `ps`.`sRefererDomain` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `ps`.`iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	$aStats['aRefOrdersCurrentYear'] = $oDB->executeSQL( 'SELECT `r`.`sName`, `r`.`sColor`, COUNT( `o`.`iOrder` ) AS `iOrders`, SUM( `op`.`iQuantity` ) AS `iSumQuantity`, SUM( `op`.`fPrice` * `op`.`iQuantity` ) AS `fSumPrice`, SUM( ( `op`.`fPrice` - `op`.`fBuyPrice` ) * `op`.`iQuantity` ) AS `fMargin` FROM `' . $oDB->throwTableName( DB_REFERERS ) . '` `r` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` ON( `r`.`sDomain` = `o`.`sOuterRefererDomain` ) INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` `op` USING( `iOrder` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` USING( `iProductVariant` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `iTime` > '.$iTimeStart.' GROUP BY `r`.`sName`', true, DataBase::ASSOCIATIVE, 'sName' );
	
	$aStats['aBuyTimes'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, AVG( `iTime` - `iRefererTime` ) AS `iAvgTime`, MIN( `iTime` - `iRefererTime` ) AS `iMinTime`, MAX( `iTime` - `iRefererTime` ) AS `iMaxTime` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iOrder` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` USING( `iProductVariant` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$iFirstYear = date( 'Y' ) - 1;
	$iLastYear = date( 'Y' );
	for( $iYear = $iFirstYear; $iYear <= $iLastYear; $iYear++ ){
		for( $iMonth = ( ( $iYear == $iFirstYear ) ? date( 'n' ) : 1 ); $iMonth <= ( ( $iYear == $iLastYear ) ? date( 'n' ) : 12 ); $iMonth++ ){
			$sMonth = $iYear . '-' . $iMonth;
			if( !isset( $aStats['aBuyTimes'][$sMonth] ) ) $aStats['aBuyTimes'][$sMonth] = Array( 'sMonth' => $sMonth, 'iMinTime' => 0, 'iAvgTime' => 0, 'iMaxTime' => 0 );
			
		}
	}
	uksort( $aStats['aBuyTimes'], 'strnatcasecmp' );
	
	$aStats['aBuyTimes2'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ), \'-\', DAY( FROM_UNIXTIME( `iTime` ) ) ) AS `sDay`, AVG( `iTime` - `iRefererTime` ) AS `iAvgTime`, MIN( `iTime` - `iRefererTime` ) AS `iMinTime`, MAX( `iTime` - `iRefererTime` ) AS `iMaxTime` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iOrder` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` USING( `iProductVariant` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `iTime` > UNIX_TIMESTAMP( ) - 62*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) ), DAY( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sDay' );
	$iFirstDateTime = time( ) - 61*24*3600;
	$iLastDateTime = time( );
	for( $iDateTime = $iFirstDateTime; $iDateTime <= $iLastDateTime; $iDateTime+=24*3600 ){
		$sDay = date( 'Y-n-j', $iDateTime );
		if( !isset( $aStats['aBuyTimes2'][$sDay] ) ) $aStats['aBuyTimes2'][$sDay] = Array( 'sDay' => $sDay, 'iMinTime' => 0, 'iAvgTime' => 0, 'iMaxTime' => 0 );
	}
	uksort( $aStats['aBuyTimes2'], 'strnatcasecmp' );
	
	$aStats['aBuyTimes3'] = $oDB->executeSQL( 'SELECT CONCAT( YEAR( FROM_UNIXTIME( `iTime` ) ), \'-\', MONTH( FROM_UNIXTIME( `iTime` ) ) ) AS `sMonth`, COUNT( IF( `iTime` - `iRefererTime` < 1*3600, 1, NULL ) ) AS `iLowerThan1h`, COUNT( IF( `iTime` - `iRefererTime` >= 1*3600 AND `iTime` - `iRefererTime` < 12*3600, 1, NULL ) ) AS `iLowerThan12h`, COUNT( IF( `iTime` - `iRefererTime` >= 12*3600 AND `iTime` - `iRefererTime` < 1*24*3600, 1, NULL ) ) AS `iLowerThan1Day`, COUNT( IF( `iTime` - `iRefererTime` >= 1*24*3600 AND `iTime` - `iRefererTime` < 3*24*3600, 1, NULL ) ) AS `iLowerThan3Days`, COUNT( IF( `iTime` - `iRefererTime` >= 3*24*3600 AND `iTime` - `iRefererTime` < 7*24*3600, 1, NULL ) ) AS `iLowerThan7Days`, COUNT( IF( `iTime` - `iRefererTime` >= 7*24*3600 AND `iTime` - `iRefererTime` < 30*24*3600, 1, NULL ) ) AS `iLowerThan30Days`, COUNT( IF( `iTime` - `iRefererTime` >= 30*24*3600, 1, NULL ) ) AS `iHigherThan30Days` FROM `' . $oDB->throwTableName( DB_ORDERS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iOrder` ) INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` USING( `iProductVariant` ) WHERE `iProduct` = '.intval( $iProduct ).' AND `iTime` > UNIX_TIMESTAMP( ) - 365*24*3600 GROUP BY YEAR( FROM_UNIXTIME( `iTime` ) ), MONTH( FROM_UNIXTIME( `iTime` ) )', true, DataBase::ASSOCIATIVE, 'sMonth' );
	$iFirstYear = date( 'Y' ) - 1;
	$iLastYear = date( 'Y' );
	for( $iYear = $iFirstYear; $iYear <= $iLastYear; $iYear++ ){
		for( $iMonth = ( ( $iYear == $iFirstYear ) ? date( 'n' ) : 1 ); $iMonth <= ( ( $iYear == $iLastYear ) ? date( 'n' ) : 12 ); $iMonth++ ){
			$sMonth = $iYear . '-' . $iMonth;
			if( !isset( $aStats['aBuyTimes3'][$sMonth] ) ) $aStats['aBuyTimes3'][$sMonth] = Array( 'sMonth' => $sMonth, 'iLowerThan1h' => 0, 'iLowerThan12h' => 0, 'iLowerThan1Day' => 0, 'iLowerThan3Days' => 0, 'iLowerThan7Days' => 0, 'iLowerThan30Days' => 0, 'iHigherThan30Days' => 0 );
			
		}
	}
	uksort( $aStats['aBuyTimes3'], 'strnatcasecmp' );

	$oTpl->assign( 'aStats', $aStats );
	$aReferersColors = $oDB->throwFileArraySmall( DB_REFERERS, 'sDomain', 'sColor' );
	$oTpl->assign( 'aReferersColors', $aReferersColors );
	echo $oTpl->parse( 'products_form_products-stats.tpl' );
	exit;
} elseif( $a == 'form' && $tab == 'product-referers' ){
	$aReferers = $oDB->executeSQL( 'SELECT `sRefererUrl`, COUNT( `iElement` ) FROM `' . $oDB->throwTableName( DB_PRODUCTS_STATS ) . '` WHERE  `iProduct` = ' . intval( $iProduct ) . ' GROUP BY `sRefererUrl`', true, DataBase::ASSOCIATIVE );
	$oTpl->assign( 'aReferers', $aReferers );
	echo $oTpl->parse( 'products_form_products-referers.tpl' );
	exit;
} elseif( $a == 'form' ){
	$config['iWatermark'] = $config['iWatermarkProducts'];
	$oTpl->assign( 'config', $config );
	$json_tags = json_encode( $oDB->executeSQL( 'SELECT DISTINCT `sTag` FROM `' . $oDB->throwTableName( DB_PAGES_TAGS ) . '` UNION SELECT DISTINCT `sTag` FROM `' . $oDB->throwTableName( DB_PRODUCTS_TAGS ) . '`', true, DataBase::SINGLE_COLUMN ) );
	$oTpl->assign( 'json_tags', $json_tags );
	if( isset( $_POST['sOption'] ) ){
		$_POST['iPriceTimeFrom'] = dateToTime( $_POST['sPriceTimeFrom'], 'ymd' );
		$_POST['iPriceTimeTo'] = dateToTime( $_POST['sPriceTimeTo'], 'ymd' );
		if( is_array( $_POST['aPages'] ) ) foreach( $_POST['aPages'] as $iKey => $iPage ){
			if( $iPage == 0 ) unset( $_POST['aPages'][$iKey] );
		}
		$iProduct = $oProduct->saveProduct( $_POST, true );
		deleteProductAttribute( $iProduct );
		saveProductAttribute( $iProduct, $_POST['aProductAttributes'] );
		$oProduct->sendAvailNewsletter();
		header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=' . $p . '&sOption=save&iProduct=' . $iProduct . '&activeTabId=' . $_POST['activeTabId'] );
		exit;
	}
	if( isset( $sOption ) ) $content.= $oTpl->parse( 'message_done.tpl' );
	if( isset( $iProduct ) && is_numeric( $iProduct ) ){
		$aProduct = $oProduct->throwProduct( $iProduct );
	}
	if( !empty( $iProduct ) && !is_array( $aProduct ) ){
		$oTpl->assign( 'sErrorMessage', $lang['Not_existing_product'] );
		$content.= $oTpl->parse( 'message_other_error.tpl' );
	}
	if( isset( $aProduct ) && is_array( $aProduct ) ){
		//Generowanie Metatagów domyślnych
		$aMetaProduct = $aProduct;
		$aMetaProduct['aPagesTree'] = $oProduct->getPagesTree( $aMetaProduct['iProduct'], $aMetaProduct['sName'] );
		$aMetaProduct['sMetaPageTree'] = '';
		if( is_array( $aMetaProduct['aPagesTree']['aPath'] ) ) foreach( $aMetaProduct['aPagesTree']['aPath'] as $aPage ) $aMetaProduct['sMetaPageTree'].= ', ' . $aPage['sName'];
		$aMetaProduct['sTitle'] = strip_tags( $aMetaProduct['sName'] . ' - ' . $aMetaProduct['sProducer'] . ' -' . str_replace( ',', '', $aMetaProduct['sMetaPageTree'] ) . ( !empty( $config['title_4_products'] ) ? ' - ' . $config['title_4_products'] : null ) );
		$aMetaProduct['sKeywords'] = $aMetaProduct['sName'] . ( !empty( $aMetaProduct['sProducer'] ) ? ', ' . $aMetaProduct['sProducer'] : null ) . $aMetaProduct['sMetaPageTree'] . ( !empty( $config['keywords'] ) ? ', ' . $config['keywords'] : null );
		if( empty( $aMetaProduct['sDescriptionFull'] ) ) $aMetaProduct['sDescriptionFull'] = $aMetaProduct['sDescriptionShort'];
		$sMetaDescPart = $aMetaProduct['sDescriptionShort'];
		if( empty( $sMetaDescPart ) ) $sMetaDescPart = $aMetaProduct['sDescriptionFull'];
		$sMetaDescPart = str_replace( '|n|', ' ', strip_tags( $sMetaDescPart ) );
		$sMetaDescPart = preg_replace( '/\\s+/', ' ', $sMetaDescPart );
		$sMetaDescPart = htmlspecialchars( $sMetaDescPart );
		if( strlen( $sMetaDescPart ) > 200 ){
			$sMetaDescPart = substr( $sMetaDescPart, 0, 200 );
			$sMetaDescPart = preg_replace( '/\\s\\S+$/', '', preg_replace( '/&[^;]+$/', '', $sMetaDescPart ) ) . '...';
		}
		$aMetaProduct['sDescription'] = $aMetaProduct['sName'] . ( !empty( $aMetaProduct['sProducer'] ) ? ' - ' . $aMetaProduct['sProducer'] : null ) . ' ' . $sMetaDescPart;
		$oTpl->assign( 'aMetaProduct', $aMetaProduct );
		/* * */
		$aProduct['aAvailNewsletter'] = $oDB->executeSQL( 'SELECT `sEmail`, `sPhone`, `iTime` FROM `' . $oDB->throwTableName( DB_PRODUCTS_AVAIL_NEWSLETTER ) . '` WHERE `iProduct` = ' . $aProduct['iProduct'] . ' AND `iProductVariant` IS NULL AND `iTimeSent` IS NULL ORDER BY `iTime` ASC', true );
		if( !empty( $aProduct['iPriceTimeFrom'] ) ) $aProduct['sPriceTimeFrom'] = date( 'Y-m-d H:i:s', $aProduct['iPriceTimeFrom'] );
		if( !empty( $aProduct['iPriceTimeTo'] ) ) $aProduct['sPriceTimeTo'] = date( 'Y-m-d H:i:s', $aProduct['iPriceTimeTo'] );
		$aProduct['aFiles'] = $oFile->listAllFilesAdmin( $iProduct, 2 );
		$aProduct['sDescriptionShort'] = changeTxt( $aProduct['sDescriptionShort'], 'nlNds' );
		$aProduct['sDescriptionFull'] = changeTxt( $aProduct['sDescriptionFull'], 'nlNds' );
		
		$aProduct['aAdvsearcherValues'] = $oDB->executeSQL( 'SELECT `iValue` FROM `' . $oDB->throwTableName( DB_ADVSEARCHER_PRODUCTS ) . '` WHERE `iProduct` = ' . $aProduct['iProduct'], true, DataBase::ASSOCIATIVE, 'iValue' );
		foreach( $aProduct['aAdvsearcherValues'] as &$mValue ){
			$sText = '';
			$iParentValue = $mValue['iValue'];
			while( !empty( $iParentValue ) ){
				list( $iParentValue, $sTextAdd ) = $oDB->executeSQL( 'SELECT `iParentValue`, `sValue` FROM `' . $oDB->throwTableName( DB_ADVSEARCHER_VALUES ) . '` WHERE `iValue` = ' . intval( $iParentValue ), true, DataBase::SINGLE_RECORD | MYSQLI_NUM );
				$sText = $sTextAdd . ( !empty( $sText ) ? ' &raquo; ' . $sText : null );
			}
			$mValue = $sText;
		}
	} else{
		$iProduct = null;
//		$iPromoted = 0;
		$aProduct['iVisibleAll'] = 1;
		$aProduct['iVisiblePriceAll'] = 1;
		$aProduct['iCanBuyAll'] = 1;
		$aProduct['aCarriersPrices'] = Array( );
		$aProduct['aCategories'] = null;
		$aProduct['aDiscounts'] = Array( );
		$aProduct['iActiveDiscount'] = 1;
		$aProduct['iAdmin'] = $_SESSION['iAdminId'];
		$aProduct['iComments'] = 0;
		$aProduct['iFotolia'] = 0;
		$aProduct['iCompare'] = 1;
		$aProduct['iStatus'] = 1;
		$aProduct['iPosition'] = 0;
		$aProduct['iProducer'] = null;
		$aProduct['sDate'] = date( 'Y-m-d H:i:s' );
		$aProduct['sDescriptionFull'] = null;
		$aProduct['sDescriptionShort'] = null;
	}
	$aGeneralInfo['aCarriers'] = $oOrder->throwCarriersAdmin( );
	$aGeneralInfo['aUsersGroups'] = throwGroups( );
	$aGeneralInfo['aVats'] = throwVats( );
	$aGeneralInfo['aVatsForSelect'] = throwVatsForSelect( );
	$aGeneralInfo['sVatsJSON'] = json_encode( $aGeneralInfo['aVats'] );
	$aGeneralInfo['aPagesFull'] = $oPage->throwProductsPagesAdminFull( );
	$aGeneralInfo['aNewUsed'] = Array( 0 => $lang['New'], 1 => $lang['Used'] );
	$aGeneralInfo['aProducers'] = throwProducersForSelect( );
	$aGeneralInfo['aAdmins'] = throwAdminsForSelect( $_SESSION['iAdminId'] );
	$aGeneralInfo['aFilePosition'] = $aFilePositionProduct;
	$aGeneralInfo['aPhotoPosition'] = $aPhotoPositionProduct;
	$aGeneralInfo['iDefaultFilePosition'] = 7;
	$aGeneralInfo['aAttributes'] = throwAttributesListForSelect( );
	$aGeneralInfo['aAttributesAndValues'] = throwAttributesValuesSelects( );
	$aGeneralInfo['aAttributesGroups'] = throwAttributesGroupsInfo( );
	$aGeneralInfo['aAvailability'] = $oProduct->throwAvailabilityForSelect( );
	$aGeneralInfo['aAvailabilityOnStock'] = $oProduct->throwAvailabilityForSelectOnStock( );
	$aGeneralInfo['aStores'] = $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName', 'iPriority' );
	$aGeneralInfo['aYesNo'] = Array( 0 => $lang['no'], 1 => $lang['yes'] );
	//????????????????????	$sAdminsDisabled = ( $_SESSION['iAdminId'] == - 1 || !isset( $iProduct ) || ( isset( $iProduct ) && $aProduct['iAdmin'] == $_SESSION['iAdminId'] ) ) ? null : 'disabled="disabled"';
	$aProduct['aRelatedProducts'] = $oProduct->throwProductsRelated( $iProduct );
	$aProduct['aAttributesSelected'] = throwSelectedAttributes( $iProduct );
	$aGeneralInfo['aAdvsearcherColumns'] = $oDB->throwFileArraySmall( DB_ADVSEARCHER_COLUMNS, 'iColumn', 'sName' );
	$aGeneralInfo['aAdvsearcherValues'] = $oDB->throwFileArraySmall( DB_ADVSEARCHER_VALUES, 'iValue', 'sValue', null, Array( 'iColumn' => reset( array_keys( $aGeneralInfo['aAdvsearcherColumns'] ) ) ) );
	list( $aProduct['aVariants'], $aProduct['aAttributes'] ) = $oProduct->throwAdminVariants( $iProduct );
	if( !empty( $aProduct['aVariants'] ) ) foreach( $aProduct['aVariants'] as &$aVariant ){
		$aVariant['aAvailNewsletter'] = $oDB->executeSQL( 'SELECT `sEmail`, `sPhone`, `iTime` FROM `' . $oDB->throwTableName( DB_PRODUCTS_AVAIL_NEWSLETTER ) . '` WHERE `iProduct` = ' . $aProduct['iProduct'] . ' AND `iProductVariant` = ' . $aVariant['iProductVariant'] . ' AND `iTimeSent` IS NULL ORDER BY `iTime` ASC', true );
	}
	
	if( isset( $iProduct ) && is_numeric( $iProduct ) ){
		$sQuery = 'SELECT `iAttribute`, `iAttributeValue` FROM `' . $oDB->throwTableName( DB_PRODUCTS_ATTRIBUTES_CONST ) . '` WHERE `iProduct` = ' . $iProduct;	
		$aProductAttributes = $oDB->executeSQL( $sQuery, true );
		
		$aConst = array();
		$aConstList = array();
		
		foreach( $aProductAttributes as $aAttribute ){
			$aConstList[] = $aAttribute['iAttribute'];
			$aConst[ $aAttribute['iAttribute'] ][] = $aAttribute['iAttributeValue'];
		}
		
		$aProduct['aProductAttributes'] = $aConst;
		$aProduct['aProductAttributesList'] = $aConstList;

		$aProduct['aPaymentBlock'] = $oProduct->getPaymentBlock( $aProduct['iProduct'] );
	}
	
	
	$aGeneralInfo['aPayments'] = $oOrder->throwPaymentsAdmin();
	
	$oTpl->assign( 'aProduct', $aProduct );
	$oTpl->assign( 'aGeneralInfo', $aGeneralInfo );
	$content.= $oTpl->parse( 'products_form.tpl' );
} elseif( $a == 'delete' && isset( $iProduct ) && is_numeric( $iProduct ) ){
	$oProduct->deleteProduct( $iProduct );
	header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=' . $aActions['f'] . '-list&sOption=del' );
	exit;
} elseif( $a == 'compare' ){
	if( isset( $sOption ) ) $content.= $oTpl->parse( 'message_done.tpl' );
	$aUrl = parse_url( 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
	if( !empty( $aUrl['path'] ) ){
		$aUrl['path'] = dirname( $aUrl['path'] );
		if( $aUrl['path'] !== "/" ){
			$aUrl['path'] = $aUrl['path'] . '/';
		}
	}
	$oTpl->assign( 'aUrl', $aUrl );
	$PK = file_get_contents( 'index.php' );
	$PK = preg_match( '/.*define\\(\\s*\'PK\'\\s*,\\s*\'([0-9A-Za-z]+)\'\\s*\\);.*/s', $PK, $aMatches );
	$PK = $aMatches[1];
	$oTpl->assign( 'PK', $PK );
	if( isset( $_POST['sOption'] ) ){
		saveVariables( $_POST, DB_CONFIG );
		saveVariables( $_POST, DB_CONFIG_LANG );
		header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=' . $aActions['f'] . '-compare&sOption=save' . '&activeTabId=' . $_POST['activeTabId'] );
		exit;
	} else{
		$content.= $oTpl->parse( 'products_compare_links.tpl' );
	}
} elseif( $a == 'clone' ){
	if( isset( $iProduct ) ){
		if( empty( $iQuantity ) ) $iQuantity = 1;
		if( $iQuantity == 1 ){
			$iProduct = $oProduct->cloneProduct( $iProduct );
			header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=products-form&iProduct=' . $iProduct );
			exit;
		} else{
			for( $i = 1; $i <= $iQuantity; $i++ ){
				$oProduct->cloneProduct( $iProduct );
			}
			header( 'Location: ' . $_SERVER['PHP_SELF'] . '?p=products-list' );
			exit;
		}
	}
} elseif( $a == 'move_variant' && is_numeric( $iVariant ) && is_numeric( $iProduct ) ){
	if( $oProduct->moveVariant( $iVariant, $iProduct ) ){
		echo json_encode( true );
	} else{
		echo json_encode( false );
	}
	$oProduct->sendAvailNewsletter();
	exit;
} elseif( $a == 'variants_ajax' && is_numeric( $iProduct ) ){
	$aProduct = $oProduct->throwProduct( $iProduct );
	list( $aProduct['aVariants'], $aProduct['aAttributes'] ) = $oProduct->throwAdminVariants( $iProduct );
	$oTpl->assign( 'aStores', $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName', 'iPriority' ) );
	$oTpl->assign( 'aProduct', $aProduct );
	echo $oTpl->parse( 'products_ajax_form.tpl' );
	exit;
} elseif( $a == 'variants_ajax_form' ){
	if( isset( $_POST['iProduct'] ) && isset( $_POST['aStocks'] ) ){
		foreach( $_POST['aStocks'] as $iVariant => $aStock ){
			foreach( $aStock as $iStore => $iStock ){
				if( is_numeric( $iVariant ) && is_numeric( $iStore ) && is_numeric( $iStock ) ){
					if( !$oDB->update( DB_STORES_PRODUCTS, Array( 'iStock' => intval( $iStock ) ), Array( 'iProductVariant' => intval( $iVariant ), 'iStore' => intval( $iStore ) ) ) ){
						$oDB->save( DB_STORES_PRODUCTS, Array( 'iStock' => intval( $iStock ), 'iProductVariant' => intval( $iVariant ), 'iStore' => intval( $iStore ) ) );
					}
				} else{
					$oDB->executeSQL( 'DELETE FROM `' . $oDB->throwTableName( DB_STORES_PRODUCTS ) . '` WHERE `iStore` = ' . intval( $iStore ) . ' AND `iProductVariant` = ' . intval( $iVariant ) );
				}
			}
		}
		foreach( $_POST['aPrices'] as $iVariant => $fPrice ){
			if( is_numeric( $iVariant ) && ( is_numeric( $fPrice ) || empty( $fPrice ) ) ) $oDB->update( DB_PRODUCTS_VARIANTS, Array( 'fPrice' => $fPrice ), Array( 'iProductVariant' => intval( $iVariant ), 'iProduct' => intval( $_POST['iProduct'] ) ) );
		}
		if( isset( $_POST['fPrice'] ) && is_numeric( $_POST['fPrice'] ) ){
			$oDB->update( DB_PRODUCTS, Array( 'fPrice' => $_POST['fPrice'] ), Array( 'iProduct' => intval( $_POST['iProduct'] ) ) );
		}
		$oProduct->sendAvailNewsletter();
		$sql = 'SELECT `TiStock` FROM `' . $oDB->throwTableName( DB_PRODUCTS ) . '`
							WHERE `iProduct` = ' . intval( $_POST['iProduct'] );
		$iStock = $oDB->executeSQL( $sql, true, DataBase::SINGLE_VALUE );
		echo ( 't' . $iStock );
	} else{
		echo ( 'e' );
	}
	exit;
} elseif( $a == 'renew_products_variants_names' ){
	$oDB->executeSQL( 'TRUNCATE TABLE `' . $oDB->throwTableName( DB_V_PRODUCTS_VARIANTS_NAMES ) . '`;' );
	$oDB->executeSQL( 'INSERT INTO `' . $oDB->throwTableName( DB_V_PRODUCTS_VARIANTS_NAMES ) . '` ( `iProductVariant`, `sName` )
												SELECT
														`iProductVariant`,
														GROUP_CONCAT( CONCAT( `sName`, \': \', `sValue` ) SEPARATOR \', \' ) AS `sName`
													FROM `' . $oDB->throwTableName( DB_PRODUCTS_ATTRIBUTES ) . '`
														LEFT JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` USING( `iAttributeValue` )
														LEFT JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` USING( `iAttribute` )
													WHERE `iBasketVisible` = 1
													GROUP BY `iProductVariant`;' );
	$content.= $oTpl->parse( 'message_done.tpl' );
} elseif( $a == 'changename' ){
	if( !empty( $_POST['iProduct'] ) && !empty( $_POST['sName'] ) ){
		$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS ) . '` SET `sName` = \'' . $oDB->escape( $_POST['sName'] ) . '\' WHERE `iProduct` = ' . intval( $_POST['iProduct'] ) );
		echo( 'OK' );
	}
	exit;
} elseif( $a == 'delete_duplicate' ){
	$sql = 'SELECT `p2`.`iProduct` FROM `ss11_pl_products` `p1` INNER JOIN `ss11_pl_products` `p2` ON( `p1`.`sProductIndex` = `p2`.`sProductIndex` AND `p1`.`iProduct` < `p2`.`iProduct` )';
	$aProductsToDelete = $oDB->executeSQL( $sql, true );
	$oProduct->massDeleteProducts( $aProductsToDelete );
	#var_dump( $aProductsToDelete );
}
?>