<?
	$support = $this->support;
	$order = $support->order();

	$this->title = 'Support';
	$this->titleicon = 'comments';
	$this->titleLink = '/support';

	$this->title2 = 'Issue #'.$this->support->id_support;
	$this->title2icon = 'warning-sign';

?>

<!-- support page -->
<div class="container-fluid padded">
	<div class="row-fluid">
		<div class="span6">
			<?=$this->display('support/info')?>
			<?=$this->display('support/actions')?>
			<?=$this->display('support/update')?>
		</div>
		<div class="span6">
			<?=$this->display('support/conversation')?>
			<?=$this->display('support/addnote')?>
		</div>
	</div>
	<div class="row-fluid">
		<div class="box">
			<div class="box-header">
				<span class="title">Orders from <?php echo $this->support->phone(); ?></span>
			</div>
			<div class="box-content" id="orders">
				<div class="padded">
					<button class="btn btn-green" onclick="loadOrders();">Show orders from <?php echo $this->support->phone(); ?></button>
				</div>
			</div>
		</div>
	</div>
</div>
<!-- // end support page -->
<script>
/* Shows the feedbacks */
function showAlert( box, css, message ){
	var alert = $( box );
	alert.removeClass( 'alert-error' );
	alert.removeClass( 'alert-success' );
	alert.addClass( 'alert-' + css );
	alert.find( '.alert-message' ).html( message );
	alert.show();
	setTimeout( function(){
		$( '.alert' ).hide();
	}, 3000 );
};

function loadOrders(){
	var url = '/orders/content?search=+<?php echo $this->support->phone; ?>';
	$( '#orders' ).html( '<div class="padded"><i class="icon-spinner icon-spin"></i></div>' );
	$.ajax( { url: url } ).done( function( content ) {
		$( '#orders' ).html( content );
	} );
};


/* Update the Log history */
function updateConversationHistory(){
	var url = '/support/<?php echo $support->id_support; ?>/history';
	$.ajax( {
		url: url
	} ).done( function( content ) {
		$( '#history' ).html( content );
	} );
}

function showNameForm(){
	$( '#add-name-fields' ).show();
	$( '#add-name-input' ).focus();
}

function saveName(){
	var name = $( '#add-name-input' ).val();
	if( $.trim( name ) == '' ){
		alert( 'Please type the customer name' );
		$( '#add-name-input' ).focus();
		return;
	}
	var url = '/api/support/add-name/';
	$.ajax( {
		type : 'POST',
		dataType: 'json',
		data : { 'id_support' : '<?php echo $support->id_support; ?>', 'name' :  name },
		url: url,
		complete: function( json ) {
			if( json.success ){
				window.location.reload();
			} else{
				alert( 'Oops!' );
			}

		}
	} );
};

$(function() {

	App.orders.createEvents();

	/* Control the conversation's filter */
	$( '.show-conversation' ).on( 'ifChanged', function( event ){
		var allChecked = true;
		var checkbox = $( this );
		/* If the user choose show-all check all */
		if( checkbox.attr( 'id' ) == 'show-all' && checkbox.is( ':checked' ) ){
			allChecked = true;
			$( '.show-conversation' ).iCheck( 'check' );
		} else {
			$( '#show-system, #show-client, #show-rep' ).each( function(){
				var checkbox = $( this );
				if( !checkbox.is( ':checked' ) ){
					allChecked = false;
				}
			} );
			if( allChecked ){
				$( '.show-conversation' ).iCheck( 'check' );
			} else {
				$( '#show-all' ).iCheck( 'uncheck' );
			}
		}
		/* Apply the filter */
		$( '.show-conversation' ).each( function(){
			var checkbox = $( this );
			var css = '.conversation-' + checkbox.val();
			if( checkbox.is( ':checked' ) ){
				$( css ).show();
			} else {
				$( css ).hide();
			}
		} );
	} );

	/* Form reply conversation */
	$( document ).on( 'click', '.btn-conversation-reply', function(){

		var text = $( '#text-conversation-reply' );
		var val = text.val();

		if( $.trim( val ) == '' ){
			alert( 'Please type the text!' );
			text.focus();
			return;
		}

		text.val( 'Sending...' );
		text.prop( 'enabled', false );

		$.post('/support/<?php echo $support->id_support; ?>/conversation', {
			text: val
		}, function( ) {
			text.prop( 'enabled',true );
			text.val( '' );
			updateConversationHistory();
		} );
		return;
	} );

	/* Show the hidden field */
	$( document ).on( 'change', '#user_perspective', function(){
		if( $( this ).val() == 'Other' ){
			$( ".user_perspective_other" ).show();
		} else {
			$( ".user_perspective_other" ).hide();
		}
	} );

	/* Form update */
	$(document).on('click', '.button-update', function() {

		$( '.alert' ).hide();

		var status = ( $('#status').is(':checked') ? 'open' : 'closed' );

		var data = { 'status' : status };

		var url = '/support/<?php echo $support->id_support; ?>/update';
		$.ajax({
			type: 'POST',
			dataType: 'json',
			data: data,
			url: url,
			success: function(content) {
				showAlert( '.alert-update', 'success', '<strong>Ok!</strong> Support saved!' );
				updateConversationHistory();
			},
			error: function( ){
				showAlert( '.alert-update', 'error', '<strong>Oops!</strong> Failed to save, please try it again' );
				updateConversationHistory();
			}
		});
	} );

	/* Form add note */
	$(document).on('click', '.button-add-note', function() {

		$( '.alert' ).hide();

		if( $( '.add-note-field' ).css('display') != 'none' ){
			var text = $( '#add-note-text' );
			var val = text.val();
			if( $.trim( val ) == '' ){
				alert( 'Please type the text!' );
				text.focus();
				return;
			}
			text.val( 'Sending...' );
			text.prop( 'enabled', false );

			$.post('/support/<?php echo $support->id_support; ?>/note', {
				text: val
			}, function( ) {
				text.prop( 'enabled',true );
				text.val( '' );
				updateConversationHistory();
				$( '.add-note-field' ).hide();
				$( '.button-add-note' ).html( $( '.button-add-note' ).attr( 'text-backup' ) );
				showAlert( '.alert-note', 'success', '<strong>Ok!</strong> Note saved!' );
			} );

		} else {
			$( '.add-note-field' ).show();
			$( '.button-add-note' ).attr( 'text-backup', $( '.button-add-note' ).html() );
			$( '#add-note-text' ).focus();
			$( '.button-add-note' ).html( 'Save note' );
		}

	} );

	/* Button refund */
	$(document).on('click', '.button-refund', function() {

		$( '.alert' ).hide();

		var el = $( this );
		var parent = el.parent();

		var question = 'Are you sure you want to refund this?';
		if( parseFloat( el.attr( 'data-gift' ) ) > 0 ){
			question += "\n";
			question += 'A gift card was used at this order the refund value will be $' + el.attr( 'data-charged' ) + ' + $' + el.attr( 'data-gift' ) + ' as gift card.' ;
		}
		if (!confirm( question )) {
			return;
		}

		var button = parent.html();

		parent.html( '<i class="icon-cogs"></i> Processing' );

		$.getJSON('/api/order/' + el.attr('data-uuid') + '/refund', function( json ) {
			showAlert( '.alert-refund', 'success', '<strong>Ok!</strong> Order refunded!' );
			parent.html( '<b>Order refunded.</b>' );
			updateConversationHistory();
		});
	});

	var restaurants = [];
	<? foreach (Restaurant::q('select * from restaurant where active=true order by name') as $restaurant) : ?>
		restaurants.push({
			id: '<?=$restaurant->id_restaurant?>',
			text: '<?=str_replace("'","\'",$restaurant->name)?>'
		});
	<? endforeach ; ?>

	$('.editable-restaurants').editable({
		inputclass: "input-large",
		source: restaurants
	});

	updateConversationHistory();

});

function unlinkRep(){
	if( confirm( 'Confirm unlink rep?' ) ){
		$.ajax( {
			url: '/support/<?php echo $support->id_support; ?>/remove-rep',
			complete: function( content ) {
				location.reload();
			}
		} );
	}
}

function unlinkOrder(){
	if( confirm( 'Confirm unlink order?' ) ){
		$.ajax( {
			url: '/support/<?php echo $support->id_support; ?>/remove-order',
			complete: function( content ) {
				location.reload();
			}
		} );
	}
}

function linkRepShow(){
	$( '#link-rep' ).show();
}

function linkRepSave(){

	var id_admin = $( '#id_admin' ).val();

	if( $.trim( id_admin ) == '' ){
		alert( 'Please, choose a rep!' );
		$( '#id_admin' ).focus();
		return;
	}

	var url = '/support/<?php echo $support->id_support; ?>/link-rep';
	$.ajax( {
		type: 'POST',
		dataType: 'json',
		data: { id_admin : id_admin },
		url: url,
		complete: function( content ) {
			if( content.responseText == 'ok' ){
				location.reload();
			} else {
				alert('Oops! An error ocurred.' );
			}
		}
	} );
}

function linkOrder(){

	var id_order = prompt( 'Please type the order id' );

	if( $.trim( id_order ) == '' ){
		return;
	}

	var url = '/support/<?php echo $support->id_support; ?>/link-order';
	$.ajax( {
		type: 'POST',
		dataType: 'json',
		data: { id_order : id_order },
		url: url,
		complete: function( content ) {
			if( content.responseText == 'ok' ){
				location.reload();
			} else {
				alert('Oops! An error ocurred.' );
			}
		}
	} );
}
</script>
<style type="text/css">
	.box-note-system, .box-note{
		-webkit-border-radius: 3px;
		-moz-border-radius: 3px;
		border-radius: 3px;
		background: #f0fff4;
		border: 1px solid #a8b3ab;
		padding:5px 15px;
		margin:15px 15px;
	}
	.box-note-system{
		color: #666;
		background: #F5F5F5;
		border: 1px solid #CCC;
	}
</style>
<script type="text/javascript" src="/assets/js/admin.js?v=<?=$_ENV['HEROKU_SLUG_COMMIT']?>"></script>
<script type="text/javascript" src="/assets/js/admin.support.js?v=<?=$_ENV['HEROKU_SLUG_COMMIT']?>"></script>