<?php
//define this module's name and path
$mn = "odyshop_admin_related_products";
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">

$(document).ready(function(){

	$('#select_products').fancybox({
		beforeShow: function(){
			
		},
		afterClose: function(){
			var IDs = odyshop.IDs;
			odyshop.IDs = null;
			if(IDs.length){
				var IDs = IDs.join(",");
				jQuery.ajax({
					type: "POST",
					url: "ajax_related_products.php",
					data: "IDs="+IDs+"&productID=<?php echo $productID;?>&action=save",
					success: function(response){
						response = response.trim();
						//console.log(response);
						if(response.indexOf("ok") != -1){
							getRelatedProducts();
						}else{
							popup(response, "popup-warning");
						}
					}
				});	
			}
		},		
		width: 900,
		minHeight: 600,
		maxWidth: '98%',
		arrows: false,
		type : 'iframe',
		modal : true,
		helpers : {
			overlay : {
				css : {
					'background' : 'rgba(0, 0, 0, 0.8)'
				}
			},
			title: null
		}
	});
	
});

function massRelatedProductsActions(action){
	var IDs = [];
	$('#relatedProducts input[type="checkbox"]').each(function(){
		if($(this).prop('checked')){
			var id = $(this).attr("id").split("selectedID_")[1];
			IDs.push(id);
			$(this).prop("checked", false);
			$('#select_all_related_products input[type="checkbox"]').prop("checked", false);
		}
	});
	if(!IDs.length){
		popup("<?php echo t("Δεν έχετε επιλέξει κανένα προϊόν");?>", "popup-warning");
		return false;
	}
	
	if(action == "delete"){
		if(IDs.length > 1){
			if(!confirm("<?php echo t("Θέλετε να αφαιρέσετε την συσχέτιση με τα επιλεγμένα προϊόντα;");?>")) return false;
		}else{
			if(!confirm("<?php echo t("Θέλετε να αφαιρέσετε την συσχέτιση με το επιλεγμένο προϊόν;");?>")) return false;
		}
	}	
	IDs = IDs.join(",");
	jQuery.ajax({
		type: "POST",
		url: "ajax_related_products.php",
		data: "productID=<?php echo $productID;?>&action="+action+"&IDs="+IDs,
		async: false,
		success: function(response){
			response = response.trim();
			IDs= IDs.split(",");
			if(response == "ok"){
				for(var n=0; n<IDs.length; n++){
					var id=IDs[n];
					$('div.record_row[data-id="'+id+'"]').each(function(){
						if(action == "delete"){
							$(this).remove();
						}						
					});
				}
				if(!$('#relatedProducts div.record_row').length){
					massRelatedProductsControls('hide');
				}
			}else{
				popup(response, "popup-warning");
			}
		}
	});	
}

function massRelatedProductsControls(mode){
	if(mode == "show"){
		$('#no_related_products_content').hide();
		$('#select_all_related_products').show();
		$('#massRelatedProductsButtons').show();
	}
	if(mode == "hide"){
		if(!$('#relatedProducts div.record_row').length) $('#no_related_products_content').show();
		$('#select_all_related_products').hide();
		$('#massRelatedProductsButtons').hide();			
	}		
}


function getRelatedProducts(){
	jQuery.ajax({
		type: "POST",
		url: "ajax_related_products.php",
		data: "action=get&productID=<?php echo $productID;?>",
		async: false,
		success: function(response){
			//console.log(response);
			response = jQuery.parseJSON(response);
			var mode = (!response.length) ? "hide" : "show";
			massRelatedProductsControls(mode);
			if(typeof(response) == "object"){
				var totalRelatedProducts = 0;
				for(i in response){
					var record = response[i];
					var id = record.id;
					var image = (record.image) ? "../mediabank/thumbs/small_" + record.image : "";
					var title = record.title;
					var relatedID = record.relatedID;
					var exists = false;	
					$('#relatedProducts').find('.record_row').each(function(){
						if($(this).attr('data-id') == id){
							exists = true;
							return false;
						}
					});
					if(!exists){
						totalRelatedProducts++;
						var template=$("#tplRelatedProducts").html();					
						$('#relatedProducts').prepend(template.format(id, image, title, relatedID));
					}
				}
			}else{
				popup("Error: " + response, "popup-warning"); // ajax error
			}			
		}
	});		
}


</script>
<script type="text/template" id="tplRelatedProducts">
    <div class="record_row" data-id="{0}" data-relatedID="{3}">
        <div>
            <div style="clear:both"></div>
            <div class="chk_container">
                <input type="checkbox" name="selectedID[]" id="selectedID_{0}" value="{0}">
            </div>
        </div>
        <a class="edit_category product related_product" href="sections.php?action=form&category=<?php echo $category;?>&section=<?php echo $section;?>&itemID={3}">
            <div><img src="{1}"></div>
            <span>{2}</span>
        </a> 
    </div>
</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; padding:3px;">
<?php
echo t("Επιλέξτε τα προϊόντα που θέλετε να εμφανίζονται ως σχετιζόμενα με το συγκεκριμένο προϊόν. Με τον τρόπο αυτό, ο επισκέπτης σας θα ενημερώνεται για μια σειρά άλλων προϊόντων που πιθανά τον ενδιαφέρουν...");
?>
</div>

<div id="add_related_products">
    <a id="select_products" href="getProducts.php?productID=<?php echo $productID;?>" onclick="this.blur()"><?php echo t("Προσθήκη προϊόντων");?></a>
</div>

<div id="no_related_products_content"><?php echo t("Δεν υπάρχουν ακόμα καταχωρημένα σχετιζόμενα προϊόντα");?></div>
<script type="text/javascript">jQuery(function($){getRelatedProducts()});</script>

<div class="admin_form_element" id="select_all_related_products" style="margin:-10px 0 20px 6px">
    <div class="admin_checkbox_wrapper">
    <input style="position:absolute; top :-2px;" onclick="selectAllcb(this)" type="checkbox">
    <p style="font-size: .8em; color: grey; font-style:italic"><?php echo t("Επιλογή όλων");?></p>
    </div>
</div> 

<div id="relatedProducts"></div> 
<div id="massRelatedProductsButtons"><?php echo t("με τα επιλεγμένα");?>: 
    <span style="white-space: nowrap">
    <input type="button" 
    id="massRelatedProductsDelete" 
    value="<?php echo t("Αφαίρεση");?>" 
    class="btn btn-danger btn-medium" 
    onClick="massRelatedProductsActions('delete')">
    </span>
</div>

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