<?php
function drk_add_telegram_channels_meta_boxes(){
	add_meta_box(
		"post_metadata_telegram_channel_id",
		"Telegram channels",
		"drk_meta_box_telegram_channels",
        array("markets","venders",'tlg_channels','other_services','top_forums'),
		"normal",
		'default'
	);
}

add_action('add_meta_boxes', "drk_add_telegram_channels_meta_boxes");

function drk_meta_box_telegram_channels() {
	global $post;
	wp_enqueue_script("jquery");
	$telegram_channels = get_post_meta($post->ID, '_telegram_channels',true);
	?>
	<div class="DrkEntriesContainer" data-count="<?php echo count($telegram_channels); ?>" id="itemsList">
		<?php
		$cnt = 0;

		foreach($telegram_channels as $channel)
		{
			++$cnt;
			?>
			<div id="_telegram_channels[<?php echo $cnt; ?>]" class="newItem">
				<input name="_telegram_channels[<?php echo $cnt; ?>]" type="text" value="<?php echo $channel?>"/> 
				<button data-element="_telegram_channels[<?php echo $cnt; ?>]" class="btn btn-sm drk_delete" onclick="drk_remove('_telegram_channels[<?php echo $cnt; ?>]')">Remove</button>
			</div>
			<?php
		}
		?>
	</div>
	<input type="button" value="Add new Channel" class="button" id="addNewTelegramChannel" />
	<script>
		function drk_remove(elId){
			document.getElementById(elId).remove();
		}
		jQuery(document).ready(
    function($)
    {
		var ttlItems = parseInt(jQuery('#itemsList').attr('data-count'));
        jQuery('#addNewTelegramChannel').on(
            'click.darkey',
            function(e)
            {
                e.preventDefault();
                ttlItems++;
                var $newItem = '<div id="_telegram_channels['+ttlItems+']" class="newItem">' +
                    '<input name="_telegram_channels[' + ttlItems + ']" type="text" />' +
					'<button data-element="_telegram_channels['+ttlItems+']" class="btn btn-sm drk_delete" '+
					'onclick=document.getElementById("_telegram_channels['+ttlItems+']").remove();>Remove</button>'+
					'<br/><br/></div>';

				jQuery('#itemsList').append($newItem);
            }
        );
    }
);
	</script>
<?php
}

function drk_save_telegram_meta_boxes(){
	global $post;
	if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
		return;
	}
	update_post_meta($post->ID,"_telegram_channels", $_POST["_telegram_channels"]);
	
}

add_action("save_post", "drk_save_telegram_meta_boxes");