<?php
//define this module's name and path
$mn = "odyshop_admin_inventory";
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;
$inactiveTitle = t("Ο συνδυασμός αυτός είναι ανενεργός");
$activeTitle = t("Κάντε κλικ για τροποποίηση των δεδομένων αυτού του συνδυασμού");

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">

odyshop.rebuilding = false;

$(document).ready(function(){

	$("#combinations-list").sortable({
		handle : '.handle',
		axis: 'y',
		update : function (){
			var order = $('#combinations-list').sortable('serialize');
			$("#sortCombinationsInfo").load("sort.php?"+order+"&table=inventory");
		},
        start: function(evt, ui){
			var link = ui.item.find('div.ui-sortable-handle');
            handleDrag(link, 'start');
        },
        stop: function(evt, ui){
			var link = ui.item.find('div.ui-sortable-handle');
			handleDrag(link, 'stop');
        }		
	});
	
	
	$('#open_create_combination').fancybox({
		afterShow: function(){
			jQuery.ajax({
				type: "POST",
				url: "ajax_combination_create_form.php",
				data: "productID=<?php echo $productID;?>",
				async: true,
				success: function(response){
					$('#create_combinations_wrapper').html(response);
				}
			});
		},
		afterClose: function(){
			$('#create_combinations_wrapper').html('<img src="images/loading_page.gif" width="50" height="50" alt="loading..." style="margin:100px">');
		},
		width: 900,
		arrows: false,
		helpers : {
			overlay : {
				css : {
					'background' : 'rgba(0, 0, 0, 0.8)'
				}
			},
			title: null
		}
	});
	
	$("#combinations-list").on("focusin", function(){
		$('a[data-rel="combinations_mediabank"]').each(function(){
			$(this).fancybox({
				beforeShow: function(){
					odyshop.combination = $(this.element.context);
				},
				afterClose: function(){
					if(odyshop.combinationThumb) updateCombinationImage(odyshop.combination, odyshop.combinationThumb);
				},
				width : 870,
				height : 600,
				type : 'iframe',
				arrows: false,
				modal: true,
				helpers : {
					overlay : {
						css : {
							'background' : 'rgba(0, 0, 0, 0.8)'
						}
					},
					title: null
				}
			});	
		});		
	});		
		
});

function updateCombinationImage(combination, combinationThumb){
	if(!combinationThumb) return;
	var img_container = combination.prev();
	img_container.css("background-image", "url(../mediabank/thumbs/small_"+combinationThumb+")");
	img_container.find('img').attr("src", "../mediabank/thumbs/small_"+combinationThumb);
	combination.next().css("visibility", "visible").next('input[type="hidden"]').val(combinationThumb);
	var browse = combination.parent('.combination_inner').find('a[data-rel="combinations_mediabank"]');
	browse.html("<?php echo t("Αλλαγή εικόνας");?>");
}

function massCombinationsControls(action){
	if(action == "show"){
		$('#no_combinations_content').hide();
		$('.combinations_select_all').show();
		$('#massCombinationButtons').show();
		$('#saveCombinations').show();
	}
	if(action == "hide"){
		if(!$('#combinations-list li').length) $('#no_combinations_content').show();
		$('.combinations_select_all').hide();
		$('#massCombinationButtons').hide();	
		$('#saveCombinations').hide();		
	}		
}

function selectAllCombinations(elm){
	setTimeout(function(){
		$('#combinations-list').find('[name^=selectedCombinationID]').each(function(){
			$(this).prop("checked", !$(this).prop("checked"));
		});
	}, 50);		
}

function doCombinationsActions(elm){
	var action = ($(elm).hasClass("record_on")) ? "deactivate" : "activate";
	var checkbox = $(elm).prev('input[type="checkbox"]');
	checkbox.prop("checked", true);
	setTimeout(function(){
		massCombinationActions(action);
	}, 100);
	var editLink = $(elm).parents('.record_row').find('a[data-type="open_combination_details"]');
	if(action == "activate"){
		$(elm).removeClass("record_off").addClass("record_on");
		editLink.removeClass("edit_category_deactivate").addClass("edit_category").attr("title", "<?php echo $activeTitle;?>");	
	}else{
		$(elm).removeClass("record_on").addClass("record_off");
		editLink.removeClass("edit_category").addClass("edit_category_deactivate").attr("title", "<?php echo $inactiveTitle;?>");	
		var id = editLink.attr('data-ocd');	
		$('#listItem_'+id).find('.combination_details').hide('fast');			
	}
}

function getCombinationOptions(){
	jQuery.ajax({
		type: "POST",
		url: "ajax_combination_options.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";
			massCombinationsControls(mode);
			if(typeof(response) == "object"){
				var totalCombinations = 0;
				for(i in response){
					var record = response[i];
					var id = record.id;
					var active = record.active;
					active = (active != "0") ? "" : "_deactivate";
					var on_off = (active) ? "off" : "on";
					var image = (record.image && record.image != 'undefined') ? record.image : "";
					var title = record.title;
					var code = record.code;
					var quantity = record.quantity;	
					var combination = record.combination;
					var exists = false;	
					$('#combinations-list').find('li').each(function(){
						if($(this).attr('data-combination') == combination){
							exists = true;
							return false;
						}
					});
					if(!exists){
						totalCombinations++;
						title += " <span class='quantity_info'>(" + quantity + ")</span>";
						var template=$("#tplCombinations").html();					
						$('#combinations-list').prepend(
							template.format(
								id,
								title,
								code,
								quantity,
								active,
								image,
								combination,
								on_off
							)
						);
						if(image){
							var combination = $('#combinations-list').children(":first").find('a[data-rel="combinations_mediabank"]');
							updateCombinationImage(combination, image, id);
						}
					}
				}
				if(odyshop.rebuilding){
					if(totalCombinations){
						popup(totalCombinations + " <?php echo t("συνδυασμοί προστέθηκαν αυτόματα");?>", "popup-info");
					}else{
						popup("<?php echo t("Όλοι οι διαθέσιμοι συνδυασμοί υπάρχουν ήδη");?>", "popup-info");
					}
					odyshop.rebuilding = false;
				}
			}else{
				popup("Error: " + response, "popup-warning"); // ajax error
			}			
		}
	});	
}

function toggleCombination(elm){
	if($(elm).hasClass('edit_category_deactivate')){
		popup("<?php echo t("Ο συνδυασμός αυτό είναι απενεργοποιημένος. Για επεξεργασία των στοιχείων του, θα πρέπει πρώτα να τον ενεργοποιήσετε");?>", "popup-warning");
		return false;
	}
	$('#combinations-list li').each(function(){
		var obj = $(this).find('a.edit_category');
		if(obj.next().is(':visible') && obj.attr('data-ocd') != $(elm).attr('data-ocd')){
			obj.next().hide('fast');
		}
	});
		
	$(elm).next().toggle('fast', function(){
		$('html,body').animate({
			scrollTop: $(elm).offset().top - 120 // 120 is the total height of sticky header
		}, 'slow');		
	});
}

function removeCombinationImage(elm){
	$(elm).next().val(''); 
	$(elm).css('visibility', 'hidden');
	$(elm).parent('.combination_inner').find('a[data-rel="combinations_mediabank"]').html("<?php echo t("Ορισμός εικόνας");?>");
	$(elm).parent('.combination_inner')
	.find('.combination_image_preview').css("background-image", "url(image/blank.gif)")
	.find('img').attr("src", "images/blank.gif");
}

function massCombinationActions(action){
	var IDs = [];
	$('#combinations-list input[type="checkbox"]').each(function(){
		if($(this).prop('checked')){
			var id = $(this).attr("id").split("combinationID")[1];
			IDs.push(id);
			$(this).prop("checked", false);
			$('#selectAllCombinationscb').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_combination_options.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];
					$('a[data-id="'+id+'"]').each(function(){
						if(action == "activate"){
							$(this).removeClass("record_off").addClass("record_on");
							var editLink = $(this).parents('.record_row').find('a[data-type="open_combination_details"]');
							editLink.removeClass("edit_category_deactivate").addClass("edit_category").attr("title", "<?php echo $activeTitle;?>");
						}
						if(action == "deactivate"){
							$(this).removeClass("record_on").addClass("record_off");
							var editLink = $(this).parents('.record_row').find('a[data-type="open_combination_details"]');
							editLink.removeClass("edit_category").addClass("edit_category_deactivate").attr("title", "<?php echo $inactiveTitle;?>");
							var id = $(this).attr('id');	
							$('#listItem_'+id).find('.combination_details').hide('fast');					
						}
						if(action == "delete"){
							$(this).parents('.record_row').remove();
						}						
					});
				}
				if(!$('#combinations-list li').length){
					massCombinationsControls('hide');
				}
			}else{
				popup(response, "popup-warning");
			}
		}
	});	
}

function addProductCombination(){
	var qs = [];
	var form_data = $('#createCombinations').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_combination_options.php",
		data: qs+"&action=create&productID=<?php echo $productID;?>",
		success: function(response){
			response = response.trim();
			//console.log(response);
			if(response == "ok"){
				getCombinationOptions();
				$.fancybox.close();
			}else{
				alert(response);
			}
		}
	});
}

function updateProductCombinations(){
	var qs = [];
	var form_data = $('#combinations-list').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_combination_options.php",
		data: qs+"&action=update&productID=<?php echo $productID;?>",
		success: function(response){
			response = response.trim();
			if(response == "ok"){
				var total_quantity = 0;
				$("input[name^='quantity']").each(function(){
					total_quantity += parseInt($(this).val());
				});
				$('#instock').val(total_quantity);
				popup("<?php echo t("Οι συνδυασμοί του προϊόντος ενημερώθηκαν με επιτυχία");?>", "popup-info");
				$.fancybox.close();
			}else{
				alert(response);
			}
		}
	});
}

function rebuildCombinations(){
	jQuery.ajax({
		type: "POST",
		url: "ajax_combinations_generate.php",
		data: "productID=<?php echo $productID;?>",
		success: function(response){
			response = response.trim();
			//console.log(response);
			if(response == "ok"){
				getCombinationOptions();
				$.fancybox.close();
			}else{
				popup(response, "popup-iwarning");
				//alert(response);
			}
		}
	});	
}

</script>
<script type="text/template" id="tplCombinations">
	<li class="record_row" id="listItem_{0}" data-combination="{6}">
		<div>
			<div style="clear:both"></div>
			<div class="chk_container">
				<input type="checkbox" id="combinationID{0}" name="selectedCombinationID[]" value="{0}">
				<a href="javascript:void(0)" 
				data-id="{0}" 
				class="toggler record_{7}" 
				onClick="doCombinationsActions(this);">
				</a>
			</div>
			<div class="handle ui-sortable-handle" style="float:left; margin: 5px 8px 0 60px">
				<img src="images/arrow.png" alt="move" align="absmiddle" height="24" width="24">
			</div>
		</div>
		<a data-type="open_combination_details" href="javascript:void(0)" onclick="toggleCombination(this)" data-ocd="{0}" class="edit_category{4}">{1}</a>
		<div class="combination_details">
			<div class="combination_inner">
				<div class="admin_form_element" data-combinationfvn="code">
					<div class="admin_label ">
					<?php echo t("Κωδικός προϊόντος");?> : 
					</div>
					<div class="normal_wrapper">
						<input name="code[]" class="listbox" id="code_id_{0}" value="{2}" type="text">
					 </div>            
				</div>
			</div>
			<div class="combination_inner"> 
				<div class="admin_form_element" data-combinationfvn="quantity">
					<div class="admin_label ">
					<?php echo t("Ποσότητα αποθέματος");?> : 
					</div>
					<div class="normal_wrapper">
						<input name="quantity[]" class="listbox" id="quantity_id_{0}" value="{3}" type="text">
					 </div>            
				</div>
			</div>
			<div class="combination_inner">
				<div class="combination_image_preview"><img src="images/blank.gif"></div>
				<a href="attachments_combinations.php?action=add" data-rel="combinations_mediabank" type="button" class="btn btn-info">
				<?php echo t("Ορισμός εικόνας");?>
				</a>  
				<a href="javascript:void(0)" onclick="removeCombinationImage(this)" class="remove_image"></a>
				<input type="hidden" id="combinations_image_{0}" name="combinations_image[]" value="{5}">
				<input type="hidden" id="combinations_{0}" name="combinations[id_{0}]" value="{6}">
			</div>                                            
		</div>
	</li>
</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="inventory_forbidden">
	<a id="open_inventory_forbidden" href="#tab7" onclick="setSelected(document.getElementById('option7')); this.blur();"><?php echo t("Απαγορευμένοι Συνδυασμοί");?></a>
</div>
<div id="rebuild_combinations">
    <a data-rel="rebuild_combinations" href="javascript:void(0)" onclick="this.blur(); odyshop.rebuilding=true; rebuildCombinations()">
		<?php echo t("Αυτόματη δημιουργία όλων");?>
	</a>
</div>    
<div id="create_combination">
    <a id="open_create_combination" href="#createCombinations" onclick="this.blur();"><?php echo t("Δημιουργία νέου συνδυασμού");?></a>
</div> 

<div id="productCombinations">
    <div id="no_combinations_content"><?php echo t("Δεν υπάρχουν ακόμα καταχωρημένοι συνδυασμοί");?></div>
    <script type="text/javascript">jQuery(function($){getCombinationOptions()});</script>	
   
    
    <div class="admin_form_element combinations_select_all">
        <div class="admin_checkbox_wrapper">
        <input id="selectAllCombinationscb" type="checkbox" onclick="selectAllCombinations(this);" style="margin-top: 1px !important">
        <p style="font-size: .8em; color: grey; font-style:italic"><?php echo t("Επιλογή όλων");?></p>
        </div>
    </div>        
    <div id="inventory_results_info"></div>
    <ul class="ui-sortable" id="combinations-list"></ul>    
</div>
<div id="massCombinationButtons"><?php echo t("με τα επιλεγμένα");?>:
    <span style="white-space: nowrap">
    <input type="button" 
    id="massCombinationsDelete" 
    value="<?php echo t("Αφαίρεση");?>" 
    class="btn btn-danger btn-medium" 
    onClick="massCombinationActions('delete')">
    <input type="button" 
    id="massCombinationsActivate" 
    value="<?php echo t("Ενεργοποίηση");?>" 
    class="btn btn-success btn-medium" 
    onClick="massCombinationActions('activate')">
    <input type="button" 
    id="massCombinationsDeactivate" 
    value="<?php echo t("Απενεργοποίηση");?>" 
    class="btn btn-inverse btn-medium" 
    onClick="massCombinationActions('deactivate')">            
    </span>
</div>
<div id="saveCombinations">
    <input value="<?php echo t("Αποθήκευση αλλαγών");?>" onclick="updateProductCombinations()" class="btn btn-success" type="button"> 
</div>
 


<div id="createCombinations">
     <div class="section_title" style="min-width: 270px; margin-bottom: 30px"><?php echo t("Δημιουργία συνδυασμού προϊόντος");?></div>
     <div id="create_combinations_wrapper">
     	<img src="images/loading_page.gif" width="50" height="50" alt="loading..." style="margin:100px">
     </div>
</div>   

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