<?php

if( $a == 'newsletter' ){
	$timestart = microtime( true );
	$sql = 'SELECT `n`.`sEmail`, GROUP_CONCAT( DISTINCT `u`.`iUser` SEPARATOR \',\' ) AS `aUsers`
						FROM (
								`' . $oDB->throwTableName( DB_NEWSLETTER ) . '` `n`
								LEFT JOIN `' . $oDB->throwTableName( DB_USERS ) . '` `u` ON( `u`.`sEmail` = `n`.`sEmail` AND `u`.`sPass` IS NOT NULL )
							)
							INNER JOIN `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` `ua` ON( `ua`.`iUser` = `u`.`iUser` OR `ua`.`sEmail` = `n`.`sEmail` )';
	if( !empty( $_POST['sOption'] ) ){
		if( !is_array( $_POST['aEmails'] ) ){
			$sql .= ' WHERE 0';
		} else{
			foreach( $_POST['aEmails'] as &$sEmail ){
				$sEmail = '\'' . $oDB->escape( $sEmail ) . '\'';
			}
			$sql .= ' WHERE `n`.`sEmail` IN( ' . implode( ', ', $_POST['aEmails'] ) . ' )';
		}
	}	
	$sql .=	'	GROUP BY `sEmail`';
	$aUsers = $oDB->executeSQL( $sql, true );
//	var_dump( $sql, microtime( true ) - $timestart );
	
//	var_dump( $aUsers );
//	exit;
	foreach( $aUsers as &$aUser ){
		$aUser['iUser'] = 'NULL';
		foreach( explode( ',', $aUser['aUsers'] ) as $iUser ){
			if( $iUser ){ $aUser['iUser'] = intval( $iUser ); break; }
		}
		$iUser = $aUser['iUser'];
//		var_dump( $aUser['iUser'] );
		$sql = 'SELECT `p`.`iProduct`, `p`.`sName`, IF( `p`.`iPriceTimeFrom` < UNIX_TIMESTAMP() AND `p`.`iPriceTimeTo` > UNIX_TIMESTAMP() AND `p`.`fPriceTimeValue` < `p`.`fPrice`, `p`.`fPriceTimeValue`, `p`.`fPrice` ) AS `fCurrentPrice`, `ua`.`fPrice` AS `fOldPrice`, `p`.`TiAvailable`, `ua`.`iAvailable`, `ua`.`iTime`
							FROM `' . $oDB->throwTableName( DB_PRODUCTS ) . '` AS `p`
								INNER JOIN `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` `ua` USING( `iProduct` )
							WHERE ( `ua`.`iUser` = ' . intval( $aUser['iUser'] ) . ' OR `ua`.`sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' )
								AND ( IF( `p`.`iPriceTimeFrom` < UNIX_TIMESTAMP() AND `p`.`iPriceTimeTo` > UNIX_TIMESTAMP() AND `p`.`fPriceTimeValue` < `p`.`fPrice`, `p`.`fPriceTimeValue`, `p`.`fPrice` ) < `ua`.`fPrice` OR `p`.`TiAvailable` < `ua`.`iAvailable` )
								AND NOT EXISTS ( SELECT 1
																	FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` `pv`
																		INNER JOIN `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` USING( `iProductVariant` )
																		INNER JOIN `' . $oDB->throwTableName( DB_ORDERS ) . '` `o` USING( `iOrder` )
																	WHERE `pv`.`iProduct` = `p`.`iProduct`
																		AND ( ' . ( is_numeric( $aUser['iUser'] ) ? '`o`.`iUser` = ' . $aUser['iUser'] . ' OR ' : null ) . '`o`.`sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' )
																)
								AND NOT EXISTS ( SELECT 1
																	FROM `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` `uas`
																	WHERE ( ' . ( is_numeric( $aUser['iUser'] ) ? '`uas`.`iUser` = ' . $aUser['iUser'] . ' OR ' : null ) . '`uas`.`sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' )
																		AND `uas`.`iProduct` = `ua`.`iProduct`
																		AND `uas`.`iTime` > `ua`.`iTime`
																)
							ORDER BY `ua`.`iTime` DESC';
		$aProducts = $oDB->executeSQL( $sql, true );
//		var_dump( $sql, microtime( true ) - $timestart );

		$aSmartoffer['aFilter'] = $oDB->executeSQL( 'SELECT `p`.`iPage`, `p`.`sName`, `ua`.`sParameters`, `ua`.`iTime` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` AS `p` INNER JOIN `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` `ua` USING( `iPage` ) WHERE `p`.`iProducts` > 0 AND `ua`.`sParameters` LIKE \'%fFilterPriceFrom=%\' AND ( `ua`.`iUser` = ' . intval( $iUser ) . ' OR `ua`.`sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' ) ORDER BY `ua`.`iTime` DESC, `sName` ASC, `iPage` ASC', true );
		foreach( $aSmartoffer['aFilter'] as &$SOaPage ){
			$SOaPage['aPageTree'] = $oPage->getPagesTree( $SOaPage['iPage'] );
			$oldGet = $_GET;
			$_GET = Array();
			parse_str( $SOaPage['sParameters'], $_GET );

			if( isset( $_GET['aFilterAttributes'] ) || isset( $_GET['aFilterSelectAttributes'] ) ){
				if( is_array( $_GET['aFilterSelectAttributes'] ) ) foreach( $_GET['aFilterSelectAttributes'] as $iAttribute => &$aValues ){
					if( is_numeric( $iAttribute ) ){
						if( is_array( $aValues ) ) foreach( $aValues as $iValue ){
							$_GET['aFilterAttributes'][$iAttribute][$iValue] = 1;
						}
					}
				}
				if( is_array( $_GET['aFilterAttributes'] ) ) foreach( $_GET['aFilterAttributes'] as $iAttribute => &$aValues ){
					if( is_numeric( $iAttribute ) ){
						if( is_numeric( $aValues ) || ( is_string( $aValues ) && preg_match( '/^g[0-9]+$/', $aValues ) ) ){
							$aValues = Array( $aValues => 1 );
						}
						if( !is_array( $aValues ) ){
							$aValues = null;
							unset( $_GET['aFilterAttributes'][$iAttribute] );
						}
					}
				}
			}
			$SOaPage['aSearch'] = $_GET;
			
			foreach( $SOaPage['aSearch']['aFilterAttributes'] as $iAttribute => $aValues ){
				$aValues = array_keys( $aValues );
				foreach( $aValues as $iValue ){
					if( $iAttribute == 0 ){
						$SOaPage['aSearch']['aProducers'][] = $oDB->executeSQL( 'SELECT `sName` FROM `' . $oDB->throwTableName( DB_PRODUCERS ) . '` WHERE `iProducer` = ' . intval( $iValue ), true, DataBase::SINGLE_VALUE );;
					} else{
						$SOaPage['aSearch']['asAttributeValue'][ $oDB->executeSQL( 'SELECT `sName` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` WHERE `iAttribute` = ' . intval( $iAttribute ), true, DataBase::SINGLE_VALUE ) ][] = $oDB->executeSQL( 'SELECT `sValue` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` WHERE `iAttributeValue` = ' . intval( $iValue ), true, DataBase::SINGLE_VALUE );
					}
				}
			}

			$oPage->mData = null;
			$SOaPage['aProducts'] = $oProduct->throwProducts( $SOaPage['iPage'], 1000 );
			$SOaPage['aVisitedProducts'] = $oDB->executeSQL( 'SELECT `iProduct` FROM `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` WHERE ( `iUser` = ' . intval( $iUser ) . ' OR `sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' ) AND `iTime` > ' . $SOaPage['iTime'], true, DataBase::SINGLE_COLUMN );
			foreach( $SOaPage['aProducts']['aList'] as $aProduct ){
				if( $aProduct['iTime'] > $SOaPage['iTime'] && $aProduct['TiCanBuy'] && !in_array( $aProduct['iProduct'], $SOaPage['aVisitedProducts'] ) ){
					$aProduct['fCurrentPrice'] = $aProduct['fCatalogPrice'];
					$aProduct['iAvailable'] = null;
					$aProducts[] = $aProduct;
				}
			}
			$_GET = $oldGet;
		}
//		echo( 'filter' );
//		var_dump( $sql, microtime( true ) - $timestart );
		$aSmartoffer['aSearch'] = $oDB->executeSQL( 'SELECT `p`.`iPage`, `p`.`sName`, `ua`.`sParameters`, `ua`.`iTime` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` AS `p` INNER JOIN `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` `ua` USING( `iPage` ) WHERE `ua`.`sParameters` LIKE \'%sPhrase=%\' AND ( `ua`.`iUser` = ' . intval( $iUser ) . ' OR `ua`.`sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' ) ORDER BY `ua`.`iTime` DESC, `sName` ASC, `iPage` ASC', true );
		foreach( $aSmartoffer['aSearch'] as &$SOaPage ){
			$SOaPage['aPageTree'] = $oPage->getPagesTree( $SOaPage['iPage'] );
			$oldGet = $_GET;
			$_GET = Array();
			parse_str( $SOaPage['sParameters'], $_GET );
			parse_str( $SOaPage['sParameters'] );
			$SOaPage['aSearch'] = $_GET;
			if( !empty( $SOaPage['aSearch']['iProducer'] ) ){
				$SOaPage['aSearch']['sProducer'] = $oDB->executeSQL( 'SELECT `sName` FROM `' . $oDB->throwTableName( DB_PRODUCERS ) . '` WHERE `iProducer` = ' . intval( $SOaPage['aSearch']['iProducer'] ), true, DataBase::SINGLE_VALUE );;
			}
			if( is_array( $SOaPage['aSearch']['aAttributeValue'] ) ) foreach( $SOaPage['aSearch']['aAttributeValue'] as $iAttribute => $iValue ){
				$SOaPage['aSearch']['asAttributeValue'][ $oDB->executeSQL( 'SELECT `sName` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` WHERE `iAttribute` = ' . intval( $iAttribute ), true, DataBase::SINGLE_VALUE ) ] = $oDB->executeSQL( 'SELECT `sValue` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` WHERE `iAttributeValue` = ' . intval( $iValue ), true, DataBase::SINGLE_VALUE );
			}
			if( !empty( $SOaPage['aSearch']['iCategory'] ) ){
				$SOaPage['aSearch']['aCategory'] = $oPage->throwPage( $SOaPage['aSearch']['iCategory'] );
			}
			$oPage->mData = null;
			$SOaPage['aProducts'] = $oProduct->throwProducts( $SOaPage['iPage'], 1000 );
			foreach( $_GET as $param => $val ){
				unset( $GLOBALS[$param] );
			}
			$SOaPage['aVisitedProducts'] = $oDB->executeSQL( 'SELECT `iProduct` FROM `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` WHERE ( `iUser` = ' . intval( $iUser ) . ' OR `sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' ) AND `iTime` > ' . $SOaPage['iTime'], true, DataBase::SINGLE_COLUMN );
			foreach( $SOaPage['aProducts']['aList'] as $aProduct ){
				if( $aProduct['iTime'] > $SOaPage['iTime'] && $aProduct['TiCanBuy'] && !in_array( $aProduct['iProduct'], $SOaPage['aVisitedProducts'] ) ){
					$aProduct['fCurrentPrice'] = $aProduct['fCatalogPrice'];
					$aProduct['iAvailable'] = null;
					$aProducts[] = $aProduct;
				}
			}
			$_GET = $oldGet;
		}
//		echo( 'searcher' );
//		var_dump( $sql, microtime( true ) - $timestart );

		$aSmartoffer['aSearch'] = $oDB->executeSQL( 'SELECT `p`.`iPage`, `p`.`sName`, `ua`.`sAdvsearcher`, `ua`.`iTime` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` AS `p` INNER JOIN `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` `ua` USING( `iPage` ) WHERE `p`.`iProducts` > 0 AND `ua`.`sAdvsearcher` IS NOT NULL AND ( `ua`.`iUser` = ' . intval( $iUser ) . ' OR `ua`.`sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' ) ORDER BY `ua`.`iTime` DESC, `sName` ASC, `iPage` ASC', true );
		$aAdvsearcherColumns = $oDB->throwFileArraySmall( DB_ADVSEARCHER_COLUMNS, 'iColumn', 'sName' );
		foreach( $aSmartoffer['aSearch'] as &$SOaPage ){
			$SOaPage['aPageTree'] = $oPage->getPagesTree( $SOaPage['iPage'] );
			$oldSession = $_SESSION;
			$_SESSION = Array();
			$aAdvsearcher = json_decode( $SOaPage['sAdvsearcher'], true );
			foreach( $aAdvsearcher as $iColumn => &$mValue ){
				$_SESSION['iAdvsearcherValue_' . intval( $iColumn )] = intval( $mValue );
				$mValue = $aAdvsearcherColumns[$iColumn] . ': <strong>' . $oDB->executeSQL( 'SELECT `sValue` FROM `' . $oDB->throwTableName( DB_ADVSEARCHER_VALUES ) . '` WHERE `iValue` = ' . intval( $mValue ), true, DataBase::SINGLE_VALUE ) . '</strong>';
			}
			$SOaPage['aAdvsearcher'] = $aAdvsearcher;
			$SOaPage['aSearch'] = $_SESSION;
			$oPage->mData = null;
			$SOaPage['aProducts'] = $oProduct->throwProducts( $SOaPage['iPage'], 1000 );
			$SOaPage['aVisitedProducts'] = $oDB->executeSQL( 'SELECT `iProduct` FROM `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` WHERE ( `iUser` = ' . intval( $iUser ) . ' OR `sEmail` = \'' . $oDB->escape( $aUser['sEmail'] ) . '\' ) AND `iTime` > ' . $SOaPage['iTime'], true, DataBase::SINGLE_COLUMN );
			foreach( $SOaPage['aProducts']['aList'] as $aProduct ){
				if( $aProduct['iTime'] > $SOaPage['iTime'] && $aProduct['TiCanBuy'] && !in_array( $aProduct['iProduct'], $SOaPage['aVisitedProducts'] ) ){
					$aProduct['fCurrentPrice'] = $aProduct['fCatalogPrice'];
					$aProduct['iAvailable'] = null;
					$aProducts[] = $aProduct;
				}
			}
			$_SESSION = $oldSession;
		}
//		echo( 'advsearcher' );
//		var_dump( $sql, microtime( true ) - $timestart );

		$aUser['aProducts'] = $aProducts;
	}
	if( !empty( $_POST['sOption'] ) ){
		require_once( $GLOBALS['config']['dir_libraries'] . 'emogrifier.php' );
		$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 );
		include( DIR_LANG . LANGUAGE . '.php' );
		$oTpl->assign( 'lang', $lang );
		
		foreach( $aUsers as &$aUser ){
			foreach( $aUser['aProducts'] as &$aProduct ){
				if( isset( $aProduct['fCurrentPrice'] ) ) $aProduct['fPrice'] = $aProduct['fCurrentPrice'];
				elseif( !empty( $aProduct['iPriceTimeRemain'] ) ) $aProduct['fPrice'] = $aProduct['fTimePriceValue'];
				else $aProduct['fPrice'] = $aProduct['fCatalogPrice'];
				if( !isset( $aProduct['aDataImage'] ) && isset( $oFile->aImagesDefault[2][$aProduct['iProduct']] ) ){
					$aProduct['aDataImage'] = $oFile->aImagesDefault[2][$aProduct['iProduct']];
				}
				$aProduct['sLinkName'] = throwPageUrl( $aProduct['iProduct'] . ',' . change2Url( $aProduct['sName'] ) );
			}
			$oTpl->assign( 'aProducts', $aUser['aProducts'] );
			$aSSSend['sTopic'] = $oTpl->parse( 'sendSmartofferToClient_title.tpl' );
			$sHtml = $oTpl->parse( 'sendSmartofferToClient_html.tpl' );
			$aSSSend['sMailContent'] = strip_tags( $sHtml );
			$sCss = file_get_contents( DIR_TEMPLATES . 'admin/style_sendSmartofferToClient.css' );
			$oEm = new Emogrifier( $sHtml, $sCss );
			$aSSSend['sHtmlContent'] = $oEm->emogrify( );
			$aSSSend['sSender'] = $GLOBALS['config']['email'];
			if( sendEmail( $aSSSend, $aUser['sEmail'] ) ){
				foreach( $aUser['aProducts'] as &$aProduct ){
//					var_dump( $aProduct );
					$oDB->save( DB_USER_ACTIONS, Array( 'iUser' => intval( $aUser['iUser'] ), 'sEmail' => $aUser['sEmail'], 'iProduct' => $aProduct['iProduct'], 'iType' => 1, 'iTime' => time(), 'fPrice' => $aProduct['fPrice'], 'iAvailable' => $aProduct['TiAvailable'] ) );
				}
			}
		}
		header( 'Location: admin.php?p=smartoffer-newsletter&sOption=sent' );
		exit;
	} else{
		$oTpl->assign( 'aUsers', $aUsers );
		$oTpl->assign( 'aAvailabilities', $oDB->throwFileArraySmall( DB_PRODUCTS_AVAILABLE, 'iAvailable', 'sText', 'iAvailable' ) );
		$oTpl->assign( 'gen_time', microtime( true ) - $timestart );
		if( $sOption ) $content .= $oTpl->parse( 'message_done.tpl' );
		$content .= $oTpl->parse( 'smartoffer_newsletter.tpl' );
	}
}