<?php

$sBasketLink = $oPage->getLinkName( $config['basket_page'] );
$oTpl->assign( 'sBasketLink', $sBasketLink );
if( !empty( $config['recaptcha_private'] ) && !empty( $config['recaptcha_public'] ) ) $oReCaptcha = new recaptchalib($config['recaptcha_private']);

if( $a == 'update_basket' ){
	header( 'Content-type: text/json' );
	if( isset( $_GET['sProductsJSON'] ) ){
		$aForm = Array( );
		$aProducts = json_decode( $_GET['sProductsJSON'], true );
		if( is_array( $aProducts ) ) foreach( $aProducts as $aProduct ){
			if( is_array( $aProduct ) && isset( $aProduct['iProductVariant'] ) && isset( $aProduct['iQuantity'] ) ){
				$aForm['aProducts'][$aProduct['iProductVariant']] = $aProduct['iQuantity'];
			}
		}
		$aErrors = $oOrder->saveBasket( $aForm );
		echo ( json_encode( $aErrors ) );
	}
	exit;
} elseif( $a == 'verify_discount_coupon' && isset( $_GET['sCode'] ) ){
	header( 'Content-type: text/json' );
	$_GET['sCode'] = trim( $_GET['sCode'] );
	echo ( json_encode( $oDB->executeSQL( 'SELECT `sDiscountValue`, `pr`.`iProducer`, `pr`.`sName` AS `sProducer` FROM `' . $oDB->throwTableName( DB_DISCOUNT_COUPONS ) . '` LEFT JOIN `' . $oDB->throwTableName( DB_PRODUCERS ) . '` `pr` USING( `iProducer` ) WHERE `sCode` = \'' . $oDB->escape( $_GET['sCode'] ) . '\' AND `iUsed` < 1 AND `iTimeTo` > ' . time( ), true, DataBase::SINGLE_RECORD ) ) );
	exit;
} elseif( $a == 'get_brothers' && is_numeric( $iPage ) ){
	$sql = 'SELECT `p`.`iPage`, `p`.`sName` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `p` WHERE `iPage` = ' . intval( $iPage ) . ' AND `iStatus` >= ' . throwStatus();
	$aPage = $oDB->executeSQL( $sql, true, DataBase::SINGLE_RECORD );
	echo ( '<strong><a href="' . $oPage->getLinkName( $aPage['iPage'], $aPage['sName'] ) . '">' . $aPage['sName'] . '</a></strong>' );
	$sql = 'SELECT `p`.`iPage`, `p`.`sName` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `p` INNER JOIN `' . $oDB->throwTableName( DB_PAGES ) . '` `pw` ON( IFNULL( `p`.`iPageParent`, 0 ) = IFNULL( `pw`.`iPageParent`, 0 ) AND ( `p`.`iPageParent` != 0 OR `p`.`iType` = `pw`.`iType` ) ) WHERE `pw`.`iPage` = ' . intval( $iPage ) . ' AND `p`.`iStatus` >= ' . throwStatus() . ' ORDER BY `p`.`iPosition` ASC, `p`.`sName` ASC, `p`.`iPage` ASC';
	$aPages = $oDB->executeSQL( $sql, true );
	echo ( '<ul>' );
	foreach( $aPages as $aPage ){
		echo ( '<li><a href="' . $oPage->getLinkName( $aPage['iPage'], $aPage['sName'] ) . '">' . $aPage['sName'] . '</a></li>' );
	}
	echo ( '</ul>' );
	exit;
} elseif( $a == 'add_to_basket' && is_numeric( $iProduct ) ){
	header( 'Content-type: text/json' );
	$sBasketError = $oOrder->addToBasket( $iProduct, !is_numeric( $iQuantity ) ? 1 : $iQuantity, null );
	$aProduct = $oProduct->throwProduct( $iProduct );
	$oOrder->generateBasket( );
	$aBasketInfo = $oOrder->listProductsBasketInfo( );
	if( $oSalesManago->checkSettings() === true && isset( $_SESSION['sUserEmail'] ) && $_SESSION['sUserEmail'] != "" ) $oSalesManago->addEventContact( 'CART', $aBasketInfo['aProducts'], $_SESSION );
	$oTpl->assign( 'aBasketInfo', $aBasketInfo );
	$aInfo['basket_small'] = $oTpl->parse( 'basket_small_json.tpl' );
	$aInfo['iOrderProducts'] = isset( $_SESSION['iOrderQuantity' . LANGUAGE] ) ? $_SESSION['iOrderQuantity' . LANGUAGE] : 0;
	$aInfo['fOrderSummary'] = isset( $_SESSION['fOrderSummary' . LANGUAGE] ) ? displayPrice( $_SESSION['fOrderSummary' . LANGUAGE] ) : displayPrice( 0 );
	echo ( json_encode( $aInfo ) );
	exit;
} elseif( $a == 'fastbasket' ){
		if (!$oReCaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR'])){
			echo $lang['Captcha_incorrect'].' '.join('<br />',$oReCaptcha->getErrors());
			exit;
		}

	$aForm = Array();
	foreach( $_POST as $sKey => $sValue ) if( preg_match( '/^fo_(.*)$/', $sKey, $aMatches ) ){
		$aForm[$aMatches[1]] = $sValue;
	}
	if( empty( $aForm['sName'] ) || empty( $aForm['sStreet'] ) || empty( $aForm['sZipCode'] ) || empty( $aForm['sCity'] ) || empty( $aForm['sEmail'] ) || empty( $aForm['sPhone'] ) || empty( $aForm['sOrder'] ) ){
		echo( $lang['Not_filled_fields'] );
	} else{
		$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` SET `sEmail` = \'' . $oDB->escape( $aForm['sEmail'] ) . '\' WHERE `sEmail` IS NULL AND `iCustomer` = ' . $_SESSION['iCustomer' . LANGUAGE] );

		$aForm['iOrder'] = null;
		$aForm['iOrder'] = $oDB->save( DB_FAST_ORDERS, $aForm );
		$sContent = $lang['Speedorder_notify'] . '
			<table><tr><th>' . $lang['First_and_last_name'] . ' / ' . $lang['Company'] . ':</th><td>' . $aForm['sName'] . '</td></tr>
			<tr><th>' . $lang['Street'] . ':</th><td>' . $aForm['sStreet'] . '</td></tr>
			<tr><th>' . $lang['Zip_code'] . ':</th><td>' . $aForm['sZipCode'] . '</td></tr>
			<tr><th>' . $lang['City'] . ':</th><td>' . $aForm['sCity'] . '</td></tr>
			<tr><th>' . $lang['Email'] . ':</th><td>' . $aForm['sEmail'] . '</td></tr>
			<tr><th>' . $lang['Phone'] . ':</th><td>' . $aForm['sPhone'] . '</td></tr>
			<tr><th>' . $lang['Order_content'] . ':</th><td>' . $aForm['sOrder'] . '</td></tr></table>';
		$sent = true;
		$sent = $sent && sendEmail( Array( 'sTopic' => $lang['Speedorder'], 'sMailContent' => $sContent, 'sSender' => $aForm['sEmail'] ), $config['orders_email'] );
		
		$sContent = $lang['Speedorder_confirm'] . '
			<table><tr><th>' . $lang['First_and_last_name'] . ' / ' . $lang['Company'] . ':</th><td>' . $aForm['sName'] . '</td></tr>
			<tr><th>' . $lang['Street'] . ':</th><td>' . $aForm['sStreet'] . '</td></tr>
			<tr><th>' . $lang['Zip_code'] . ':</th><td>' . $aForm['sZipCode'] . '</td></tr>
			<tr><th>' . $lang['City'] . ':</th><td>' . $aForm['sCity'] . '</td></tr>
			<tr><th>' . $lang['Email'] . ':</th><td>' . $aForm['sEmail'] . '</td></tr>
			<tr><th>' . $lang['Phone'] . ':</th><td>' . $aForm['sPhone'] . '</td></tr>
			<tr><th>' . $lang['Order_content'] . ':</th><td>' . $aForm['sOrder'] . '</td></tr></table>';
		$sent = $sent && sendEmail( Array( 'sTopic' => $lang['Speedorder'], 'sMailContent' => $sContent, 'sSender' => $config['orders_email'] ), $aForm['sEmail'] );
		if( !$sent ){
			echo( $lang['Send_error'] );
		} else{
			echo( $lang['Send_ok'] );
		}
	}
	exit;
} elseif( $a == 'add_to_storage' && is_numeric( $_GET['iProduct'] ) ){
	$oProduct->addToStorage( $_GET['iProduct'] );
	$aProduct = $oProduct->throwProduct( $_GET['iProduct'] );
	saveUserAction( Array( 'iProduct' => $_GET['iProduct'], 'iType' => 3 /* 1 - otworzenie, 2 - por�wnanie, 3 - dodanie do schowka, 4 - dodanie do koszyka */, 'fPrice' => $aProduct['bTimePromotionActive'] ? $aProduct['fTimePrice'] : $aProduct['fCatalogPrice'], 'iAvailable' => $aProduct['TiAvailable'] ) );
	$aStorageInfo['aProducts'] = $oProduct->listProductsStorage( );
	if( $oSalesManago->checkSettings() === true && count( $aStorageInfo['aProducts'] ) >0 && isset( $_SESSION['sUserEmail'] ) && $_SESSION['sUserEmail'] != "" ) $oSalesManago->addEventContact( 'OTHER', $aStorageInfo['aProducts'], $_SESSION );
	header( 'Content-type: text/json' );
	echo( count( $oProduct->throwProductsStorage() ) );
	exit;
} elseif( $a == 'remove_from_storage' && is_numeric( $_GET['iProduct'] ) ){
	$oProduct->removeFromStorage( $_GET['iProduct'] );
	header( 'Content-type: text/json' );
	echo( count( $oProduct->throwProductsStorage() ) );
	exit;
} elseif( $a == 'search_quick' && !empty( $sPhrase ) ){
	preg_match_all( '/(-?)((\\"([^\\"]+)\\")|([^\\"\\s][^\\s]*))/', htmlspecialchars_decode( $sPhrase ), $aWords, PREG_SET_ORDER );
	$aSearchP = Array( );
	foreach( $aWords as $aWord ){
		$sWord = $aWord[4];
		if( empty( $sWord ) ) $sWord = $aWord[5];
		$sWord = $oDB->escape( $sWord );
		if( $aWord[1] == '-' ){
			$aSearchProducts[] = '( `products`.`sName` NOT LIKE \'%' . $sWord . '%\' AND `products`.`sCatalogNumber` NOT LIKE \'%' . $sWord . '%\' AND `sProductIndex` NOT LIKE \'%' . $sWord . '%\' )';
			$aSearchPages[] = '( `pages`.`sName` NOT LIKE \'%' . $sWord . '%\' )';
			$aSearchProducers[] = '( `producers`.`sName` NOT LIKE \'%' . $sWord . '%\' )';
		} else{
			$aSearchProducts[] = '( `products`.`sName` LIKE \'%' . $sWord . '%\' OR `products`.`sCatalogNumber` LIKE \'%' . $sWord . '%\' OR `sProductIndex` LIKE \'%' . $sWord . '%\' )';
			$aSearchPages[] = '( `pages`.`sName` LIKE \'%' . $sWord . '%\' )';
			$aSearchProducers[] = '( `producers`.`sName` LIKE \'%' . $sWord . '%\' )';
		}
	}

	$aProducts = $oDB->executeSQL( 'SELECT `iProduct`, `sName` FROM `' . $oDB->throwTableName( DB_PRODUCTS ) . '` `products` WHERE ( ' . implode( ' AND ', $aSearchProducts ) . ' ) LIMIT 8', true );
	$aPages = $oDB->executeSQL( 'SELECT `iPage`, `sName` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `pages` WHERE ( ' . implode( ' AND ', $aSearchPages ) . ' ) LIMIT 5', true );
	$aProducers = $oDB->executeSQL( 'SELECT `iProducer`, `sName` FROM `' . $oDB->throwTableName( DB_PRODUCERS ) . '` `producers` WHERE ( ' . implode( ' AND ', $aSearchProducers ) . ' ) LIMIT 5', true );

	foreach( $aProducts as &$aProduct ){
		$aProduct['sLinkName'] = throwPageUrl( $aProduct['iProduct'] . ',' . change2Url( $aProduct['sName'] ) );
		if( isset( $oFile->aImagesDefault[2][$aProduct['iProduct']] ) ){
			$aProduct['aDataImage'] = $oFile->aImagesDefault[2][$aProduct['iProduct']];
		}
		foreach( $aWords as $aWord ){
			$sWord = $aWord[4];
			if( empty( $sWord ) ) $sWord = $aWord[5];
			$sWord = str_replace( Array( '\\', '^', '.', '$', '|', '(', ')', '[', ']', '*', '+', '?', '{', '}', ',' ), Array( '\\\\', '\\^', '\\.', '\\$', '\\|', '\\(', '\\)', '\\[', '\\]', '\\*', '\\+', '\\?', '\\{', '\\}', '\\,' ), $sWord );
			$aProduct['sName'] = preg_replace( '/(' . $sWord . ')/i', '<strong>$1</strong>', $aProduct['sName'] );
		}
	}
	
	foreach( $aPages as &$aPage ){
		$aPage['sLinkName'] = $oPage->getLinkName( $aPage['iPage'], $aPage['sName'] );
		foreach( $aWords as $aWord ){
			$sWord = $aWord[4];
			if( empty( $sWord ) ) $sWord = $aWord[5];
			$sWord = str_replace( Array( '\\', '^', '.', '$', '|', '(', ')', '[', ']', '*', '+', '?', '{', '}', ',' ), Array( '\\\\', '\\^', '\\.', '\\$', '\\|', '\\(', '\\)', '\\[', '\\]', '\\*', '\\+', '\\?', '\\{', '\\}', '\\,' ), $sWord );
			$aPage['sName'] = preg_replace( '/(' . $sWord . ')/i', '<strong>$1</strong>', $aPage['sName'] );
		}
	}
	
	foreach( $aProducers as &$aProducer ){
		foreach( $aWords as $aWord ){
			$sWord = $aWord[4];
			if( empty( $sWord ) ) $sWord = $aWord[5];
			$sWord = str_replace( Array( '\\', '^', '.', '$', '|', '(', ')', '[', ']', '*', '+', '?', '{', '}', ',' ), Array( '\\\\', '\\^', '\\.', '\\$', '\\|', '\\(', '\\)', '\\[', '\\]', '\\*', '\\+', '\\?', '\\{', '\\}', '\\,' ), $sWord );
			$aProducer['sName'] = preg_replace( '/(' . $sWord . ')/i', '<strong>$1</strong>', $aProducer['sName'] );
		}
	}
	
	$oTpl->assign( 'aProducts', $aProducts );
	$oTpl->assign( 'aPages', $aPages );
	$oTpl->assign( 'aProducers', $aProducers );
	
	echo $oTpl->parse( 'search_quick.tpl' );
	exit;
}
?>