<?php
//define this module's name and path
$mn = basename(__FILE__ , ".php");
include("modules/modules.php");

/*
Available variables:
All system classes
All request variables
$p (the template path)
$mp (the module path)
$sufixID (id sufix for this module's divs)
*/

$marginTop = ($moduleParameters['marginTop'] == "__EMPTY__" || empty($moduleParameters['marginTop'])) ? 0 : $moduleParameters['marginTop'];
$marginRight = ($moduleParameters['marginRight'] == "__EMPTY__" || empty($moduleParameters['marginRight'])) ? 0 : $moduleParameters['marginRight'];
$marginBottom = ($moduleParameters['marginBottom'] == "__EMPTY__" || empty($moduleParameters['marginBottom'])) ? 0 : $moduleParameters['marginBottom'];
$marginLeft = ($moduleParameters['marginLeft'] == "__EMPTY__" || empty($moduleParameters['marginLeft'])) ? 0 : $moduleParameters['marginLeft'];
$paddingTop = ($moduleParameters['paddingTop'] == "__EMPTY__" || empty($moduleParameters['paddingTop'])) ? 0 : $moduleParameters['paddingTop'];
$paddingRight = ($moduleParameters['paddingRight'] == "__EMPTY__" || empty($moduleParameters['paddingRight'])) ? 0 : $moduleParameters['paddingRight'];
$paddingBottom = ($moduleParameters['paddingBottom'] == "__EMPTY__" || empty($moduleParameters['paddingBottom'])) ? 0 : $moduleParameters['paddingBottom'];
$paddingLeft = ($moduleParameters['paddingLeft'] == "__EMPTY__" || empty($moduleParameters['paddingLeft'])) ? 0 : $moduleParameters['paddingLeft'];
$useModuleContainer = ($moduleParameters['useModuleContainer'] == "__EMPTY__" || empty($moduleParameters['useModuleContainer'])) ? 0 : (int)$moduleParameters['useModuleContainer'];
$widthInPixels = ($moduleParameters['widthInPixels'] == "__EMPTY__" || empty($moduleParameters['widthInPixels'])) ? null : (int)$moduleParameters['widthInPixels'];

if(empty($marginTop) && empty($marginRight) && empty($marginBottom) && empty($marginLeft)){
	$Mmargin = "0";
}else{
	$Mmargin = $marginTop." ".$marginRight." ".$marginBottom." ".$marginLeft." ";
}
if(empty($paddingTop) && empty($paddingRight) && empty($paddingBottom) && empty($paddingLeft)){
	$Mpadding = "0";
}else{
	$Mpadding = $paddingTop." ".$paddingRight." ".$paddingBottom." ".$paddingLeft." ";
}

global $row; // access to product data
if(!$row){
	echo "Critical Error! No product data found";
	return;
}
$productID = $row->id;


if($useModuleContainer ){
?>
<div id="<?php echo $mn.$sufixID;?>" data-editable="editable">
<?php
}
?>

<style  type="text/css">
<?php
if($useModuleContainer ){
	?>
#<?php echo $mn.$sufixID;?>{
	<?php 
	$alignRule = ($moduleParameters['moduleAlign'] == "center") ? "text-align" : "float";
	echo $alignRule.": ".$moduleParameters['moduleAlign'].";".PHP_EOL;
	?>
	margin : <?php echo $Mmargin;?>;
	padding : <?php echo $Mpadding;?>;
<?php
if($widthInPixels){
	?>
	width: <?php echo $widthInPixels;?>px;
	<?php 
}	

if($moduleParameters['moduleAlign'] && $moduleParameters['moduleHR']){ // there are system parameters...

if($moduleParameters['moduleHR'] == "top" || $moduleParameters['moduleHR'] == "bottom"){
?>
	border-<?php echo $moduleParameters['moduleHR'];?> : 1px solid black;
<?php 
}
}
?>
}
<?php
}
?>
</style>
<link href="../modules/<?php echo $mn;?>/css/styles.css" rel="stylesheet" type="text/css">

<script type="text/javascript">
jQuery(function($){
	loadRules();
});

function addQdRule(id, quantity, value, type, users_typeID, mode){
	quantity = quantity || 1;
	type = type || "A"; // set type as "Absolute" for default value
	users_typeID = users_typeID || "2"; // set user type as "Guests" for default value
	if(id)	id = 'id_'+id;
	var template=$("#tplQuantityDiscounts").html();	
	var elm = template.format(id, quantity, value);
	if(mode == "bottom"){
		var new_element = $(elm).insertBefore('#qd_footer');
	}else{
		var new_element = $(elm).insertAfter('#qd thead');
	}
	new_element.find('select[data-rel="type"]').val(type);
	new_element.find('select[data-rel="users_typeID"]').val(users_typeID);
	if(!id) new_element.find('input, select').removeAttr('id');
}

function removeQdRule(elm){
	$(elm).parents('tr').find('input, select').each(function(){
		$(this).prop("disabled", !$(this).prop("disabled"));
	});
}

function removeDisabledRules(){
	//remove disabled in order to be removed from database
	$('#qd').find('input, select').each(function(){
		if($(this).prop("disabled")) $(this).remove();
	});
}

function cloneQdRule(elm){
	var tr = $(elm).parents('tr');
	var quantity = tr.find('[data-rel="quantity"]').val();
	var value = tr.find('[data-rel="value"]').val();
	var type = tr.find('[data-rel="type"]').val();
	var users_typeID = tr.find('[data-rel="users_typeID"]').val();
	addQdRule('', quantity, value, type, users_typeID, "bottom");
}

function loadRules(reload){
	if(typeof(reload) == 'undefined') reload = false;
	jQuery.ajax({
		type: "POST",
		url: "ajax_quantity_discounts.php",
		data: "action=load&productID="+<?php echo $productID;?>,
		async: false,
		success: function(response){
			response = jQuery.parseJSON(response);
			if(typeof(response) == "object"){
				if(reload){
					// remove registered rules from screen, and reload all
					$('tr[data-rel="rule"]').each(function(){
						$(this).remove();
					});
				}
				for(i in response){
					var record = response[i];
					var id = record.id;
					var quantity = record.quantity;
					var value = parseFloat(record.value).toString();
					var type = record.type;
					var users_typeID = record.users_typeID;
					addQdRule(id, quantity, value, type, users_typeID, "top");
				}
				if(!response.length) addQdRule('', '', '', '', '', 'bottom'); // add a blank row if no other rules exist
				
				if(reload){
					//popup(response, "popup-info");
					popup("<?php echo t("Οι κανόνες των ποσοτικών εκπτώσεων του προϊόντος ενημερώθηκαν με επιτυχία");?>", "popup-info");
				}
			}else{
				popup("Error: " + response, "popup-warning"); // ajax error
			}
		}
	});	
}

function checkForDuplicates(){
	var combinations = [];
	$('tr[data-rel="rule"]').each(function(){
		var quantity =  $(this).find('input[data-rel="quantity"]:enabled').val();
		var value =  $(this).find('input[data-rel="value"]:enabled').val();
		var type =  $(this).find('select[data-rel="type"]:enabled').val();
		var users_typeID =  $(this).find('select[data-rel="users_typeID"]:enabled').val();
		if(!value) return true;
		var line = quantity+"|"+value+"|"+type+"|"+users_typeID;
		combinations.push(line);
	});
	return checkArrayForDuplicates(combinations);
}	

function saveRules(){
	var valid = checkForDuplicates();
	if(!valid){
		popup("<?php echo t("Βρέθηκαν δύο ή περισσότεροι όμοιοι εκπτωτικοί κανόνες. Παρακαλούμε ελέγξτε τις τιμές και προσπαθήστε ξανά");?>", "popup-warning");
		return false;
	}
	removeDisabledRules();
	var qs = [];
	var form_data = $('#qd').find("*").serializeArray();
	for(i in form_data) qs.push(form_data[i].name + '=' + form_data[i].value);
	qs=qs.join("&");
	jQuery.ajax({
		type: "POST",
		url: "ajax_quantity_discounts.php",
		data: qs+"&productID=<?php echo $productID;?>&action=save",
		success: function(response){
			response = response.trim();
			if(response.indexOf("ok") != -1){
				loadRules(true);
			}else{
				popup(response, "popup-warning");
			}
		}
	});	
}

function checkQuantity(elm){
	var quantity = parseInt($(elm).val());
	quantity = quantity || 1;
	$(elm).val(quantity);
}
</script>

<script type="text/template" id="tplQuantityDiscounts">
    <tr data-rel="rule">
        <td data-title="<?php echo t("Ποσότητα");?>">
			<input data-rel="quantity" type="text" name="qd[quantity][{0}]" id="qd_quantity_{0}" style="width:60px" class="listbox" value="{1}" onblur="checkQuantity(this)">
		</td>
        <td data-title="<?php echo t("Έκπτωση");?>">
			<input data-rel="value" type="text" name="qd[value][{0}]" id="qd_value_{0}" style="width:80px" class="listbox" value="{2}">
		</td>
        <td data-title="<?php echo t("Τύπος");?>">
			<select data-rel="type" name="qd[type][{0}]" id="qd_type_{0}" class="listbox">
				<option value="A">€</option>
				<option value="P">%</option>
			</select>
        </td>
        <td data-title="<?php echo t("Στην ομάδα χρηστών");?>">
			<select data-rel="users_typeID" class="listbox" name="qd[users_typeID][{0}]" id="qd_users_typeID_{0}">
			<?php
			$q = "select ut.id, cut.title from users_types as ut, content_users_types as cut where 
						ut.id=cut.mainID 
						and cut.langID='$langID' 
						and ut.active=1 
						order by ut.sort";
			$users_types = $db->getRecords($q);
			foreach($users_types as $ut){
				$ut_id = $ut->id;
				$ut_title = $ut->title;					
				?>
				<option value="<?php echo $ut_id;?>"><?php echo $ut_title;?></option>
				<?php
			}
			?>
			</select>
        </td>
        <td>
			<div style="display:inline-block;">
				<a href="javascript:void(0)" onclick="cloneQdRule(this)" class="small_icon small_icon_clone tooltip" title="<?php echo t("Κλωνοποίηση");?>"></a>
				<a href="javascript:void(0)" onclick="removeQdRule(this)" class="small_icon small_icon_remove tooltip" title="<?php echo t("Αφαίρεση");?>"></a>
			</div>
        </td>
    </tr>
</script>

<div style="position:relative">   
	<div class="admin_module_title" style="top: -65px"><h4><?php echo t("Ποσοτικές εκπτώσεις");?></h4></div>  
</div>

<div style="max-width:520px; margin: 20px auto 40px auto;">
<?php
echo t("Ορίστε τους κανόνες έκπτωσης που θα ισχύουν γι' αυτό το προϊόν, ανάλογα την ποσότητα της παραγγελίας του. Μπορείτε να προσθέσετε όσους κανόνες επιθυμείτε, για να ισχύουν διαφορετικές εκπτώσεις σε διαφορετικές ποσότητες");
?>
</div>
<table id="qd">
    <thead>
        <tr>
            <th><?php echo t("Ποσότητα");?></th>
            <th><?php echo t("Έκπτωση");?></th>
            <th><?php echo t("Τύπος");?></th>
            <th><?php echo t("Στην ομάδα χρηστών");?></th>
            <th>&nbsp;</th>
        </tr>
    </thead>
    <tr id="qd_footer">
        <td colspan="5" style="text-align:right"><a href="javascript:void(0)" onclick="addQdRule('', '', '', '', '', 'bottom')" class="add_new tooltip" title="<?php echo t("Προσθήκη νέου κανόνα");?>"></a></td>
    </tr>    
</table>
<div style="text-align: right; margin-top: 20px; padding-top: 5px; border-top: 2px solid silver;">
<input type="button" 
id="saveRules" 
value="<?php echo t("Εφαρμογή κανόνων");?>" 
onclick="saveRules()" 
class="btn btn-success"> 
</div>

<?php
if($useModuleContainer ){
?>
</div>
<?php 
}
?>
