<?php

###################################################################################################
###################################################################################################
## SERVICE OFFER SCRIPT ###########################################################################
###################################################################################################
###################################################################################################

// TODO: offer form of payment must be displaued in the interface

// TODO: access level Modules/Orders/ServiceOffers-blockImportedServicePrices - not implemented in ServiceOffer::update()

// TODO: transforma toate coloanele din DB de la oferta, din DOUBLE in DECIMAL; atentie la nr zecimale

///////////////////////////////////////////////////////////////////////////////////////////////////
// GLOBAL INCLUDES ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
include("_config/addCfg.php");
include("_includes/addInc.php");

// trace visit
$userTrailItem->updateEntityOld('service', $R['idService']);

///////////////////////////////////////////////////////////////////////////////////////////////////
// TEST THAT ID SERVICE IS OKAY, AND SAVE IT INTO $idService //////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////


// IF NO ID SERVICE
if (!$R['idService'] or $R['idService']<=10000001){
	header("Location: ../");
	exit;
}

// copy the idService into $idService
$idService=$R['idService'];

// get the table tail for this service
$tableTime=\App\Utils\Db\TablesUtils::getInstance()->getYmFromId($idService);


///////////////////////////////////////////////////////////////////////////////////////////////////
// GET DETAILS ABOUT THIS SERVICE /////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
$getServiceDetailsSQL="
	SELECT
		idPackageService, packageOfferMode, idReservation, serviceCode, service, category, productType, multiplier, idSupplierProduct,
		idCustomers, startDate, endDate, duration, departureCountryCode, departureCityId, destinationCountryCode, destinationCityId, statusOp
	FROM `$DBTReservationServices$tableTime`
	WHERE id='".$idService."'
";
$serviceDetails=$db->GetRow($getServiceDetailsSQL);

// test sql
if (!is_array($serviceDetails))
	writeLog("Service details could not be retrieved. SQL:".$getServiceDetailsSQL, 'events', 10);

// GET OTHER SERVICE DETAILS //////////////////////////////////////////////////////////////////////
$serviceCode=$serviceDetails['serviceCode'];

$catAttr = \App\Config\Services_GeneralAttributes::getInstance()->getServiceCategory($serviceCode);
if ($catAttr['type'] == 'list') {
	$serviceDetails['categoryReadable']=\App\Config\Services_GeneralAttributes::getInstance()->getServiceCategoryReadable($serviceCode,explodeClean('|', $serviceDetails['category']));
}
else {
	$serviceDetails['categoryReadable']=\App\Config\Services_GeneralAttributes::getInstance()->getServiceCategoryReadable($serviceCode,$serviceDetails['category']);
}

$prodTypeAttr = \App\Config\Services_GeneralAttributes::getInstance()->getServiceProductType($serviceCode);
if ($prodTypeAttr['type'] == 'list') {
	$serviceDetails['productTypeReadable']=\App\Config\Services_GeneralAttributes::getInstance()->getServiceProductTypeReadable($serviceCode,explodeClean('|', $serviceDetails['productType']));
}
else {
	$serviceDetails['productTypeReadable']=\App\Config\Services_GeneralAttributes::getInstance()->getServiceProductTypeReadable($serviceCode,$serviceDetails['productType']);
}

if (is_numeric($serviceDetails['multiplier'])) {
	$serviceMultiplier=$serviceDetails['multiplier'];
} else {
	$serviceMultiplier= [];
	$multipl=explodeClean('|', $serviceDetails['multiplier']);
	foreach($multipl as $thisMultipl){
		$multipDet=explode('*', $thisMultipl);
		if ($multipDet[0])
			$serviceMultiplier[$multipDet[1]]=$multipDet[0];
	}
}
$serviceDetails['multiplierReadable']=\App\Config\Services_GeneralAttributes::getInstance()->getServiceMultiplierReadable($serviceCode, $serviceMultiplier);
$serviceDetails['durationType']=\App\Config\Services_Fields::getInstance()->getServiceFieldType($serviceCode, 'durationType');
// add supplier product details
if ($serviceDetails['idSupplierProduct']) {
	$serviceDetails['supplierProductDetails']=getSupplierProductDetails($serviceDetails['idSupplierProduct']);
}

// indicates determines if autocomplete should also have supplier services or just suppliers
$serviceProductNameCfg=\App\Config\Services_GeneralAttributes::getInstance()->getServiceProductName($serviceCode);
if ($serviceProductNameCfg['type']=='none')
	$autocompleteType="suppliers";
else
	$autocompleteType="suppliersAndServices";


// set the current working reservation
if ($serviceDetails['idReservation'])
	$S['reservations']['currentIdReservation']=$serviceDetails['idReservation'];


///////////////////////////////////////////////////////////////////////////////////////////////////
// GET SERVICE OFFER TYPES ////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
$offerTypes=\App\Config\Services_OfferTypes::getInstance()->get($serviceCode);
foreach($offerTypes as $offerTypeCode=>$offerTypeName) {
	if (!$CFG['offers']['listAllOfferTypes'][$offerTypeCode]) {
		unset($offerTypes[$offerTypeCode]);
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// DETERMINE LOCATIONS AND CALCULATION TYPES //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// GET ALL CALCUALTION TYPES - FOR THIS SERVICE
$allCalculationTypes= [];
foreach(\App\Config\Services_Calculations::getInstance()->getServiceDetails($serviceCode) as $loc=>$calcList) {
	foreach($calcList as $calcCode=>$calcDet) {
		$allCalculationTypes[$loc][$calcCode]=$calcDet['name'];
	}
}


// determine if we should display the calculation (if only one calculation don't display the selector - and get the one calculation possible)
$calcTtl=0; // ttl no of calculations
foreach($allCalculationTypes as $locCode=>$locationCalc) {
	foreach($locationCalc as $calcCode=>$calcName) {
		$calcTtl++;
		$defaultCalculation=$locCode.'|'.$calcCode;
	}
}
if ($calcTtl==1)
	$displayCalculations=0;
else
	$displayCalculations=1;



// DETERMINE OFFER CRITERION BY DEPARTURE AND DESTINATION CRITERIA ////////////////////////////////

// departure criterion
$departureCriterion=\Entity\Country::select($serviceDetails['departureCountryCode'])->criterion;
if (!$departureCriterion) $departureCriterion='int';

// destination criterion
$destinationCriterion=\Entity\Country::select($serviceDetails['destinationCountryCode'])->criterion;
if (!$destinationCriterion) $destinationCriterion='int';

$locationsList= [];
$locationsList[]=$departureCriterion;
$locationsList[]=$destinationCriterion;
// get suggested criterion
$suggestedCriterion=\App\Utils\Place::getCountryCriterionFromCriteriaList($locationsList);

// --- choose only the correct location ---
if ($CFG['reservations']['offers']['displayOnlyCorrectLocations'] and $displayCalculations and $suggestedCriterion) {
	foreach($allCalculationTypes as $thisLoc=>$locDet) {
		if ($suggestedCriterion!=$thisLoc) unset($allCalculationTypes[$thisLoc]);
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// GET CUSTOMER FREQUENT BUYER CARDS FOR CURRENT CUSTOMERS ////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
$fbCardsList= [];
$custIds=explodeClean('|', $serviceDetails['idCustomers']);
// if some customers set on this service
if ($custIds) {
	foreach($custIds as $thisIdCust) {
		$custFbCards = \Entity\Customer::selectForUpdate($thisIdCust)->frequentBuyerCards;
		if ($custFbCards)
			$fbCardsList[$thisIdCust]=$custFbCards;
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// GET SUPPLIER SERVICES SUGGESTIONS //////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// 1. SUPPLIER PRODUCT FROM ORDER /////////////////////////////////////////////////////////////////
if ($serviceDetails['idSupplierProduct']) {
	$suppServDet=getSupplierProductDetails($serviceDetails['idSupplierProduct']);
	$supplierProductFromOrder = [
		'idSupplierProduct'=>$serviceDetails['idSupplierProduct'],
		'supplierProductName'=>$suppServDet['productName'],
	];
}



###################################################################################################
###################################################################################################
## SMARTY ASSIGNMENTS #############################################################################
###################################################################################################
###################################################################################################

// service id
$smarty->assign('idService', $idService);

// service details
$smarty->assign("serviceDetails", $serviceDetails);

// calculation types
$smarty->assign("allCalculationTypes", $allCalculationTypes);
$smarty->assign("displayCalculations", $displayCalculations);

if (!$displayCalculations) // used only if displayCalculations is 0
	$smarty->assign("defaultCalculation", $defaultCalculation);

$smarty->assign("suggestedCriterion", $suggestedCriterion);

// autocomplete type
$smarty->assign("autocompleteType", $autocompleteType);

// service offers types
$smarty->assign("offerTypes", $offerTypes);

// psg fb cards
$smarty->assign("fbCardsList", $fbCardsList);

// supplier service from order / customer profile
$smarty->assign('supplierProductFromOrder', $supplierProductFromOrder);


// titles
$smarty->assign("pageTitle", $_LANG['reservations']['serviceOffers']['pageTitle']);
$smarty->assign("headerPageTitle", $_LANG['reservations']['serviceOffers']['headerTitle']);


// TEMPLATE DISPLAY --------------------------------------------------------------------------------
$smarty->display("index.tpl");

?>