<?php if (!hasKbAmazonApiDetails()) { ?>
    <div class="alert alert-danger">
        <span class="glyphicon glyphicon-fire"></span>
        <a href="?page=kbAmz&kbAction=settingsAmazonApi">
            <?php echo __('Click to setup you Amazon API Configuration.'); ?>
        </a>
    </div>
    <?php
}

if (!getKbAmz()->getOption('KbAmazonDropShipManagerOptionsSet')) {
    echo '<div class="alert alert-danger">Configure your <a href="?'.  http_build_query(array_merge($_GET, array('kbAction' => 'settingsGeneral'))).'">options</a> to continue.</div>';
    return;
}

if (getKbAmz()->getOption('deleteProductOnNoQuantity')
&& !getKbAmz()->getOption('DropShipManagerDontShowDeleteOnNoQuantity')) {
    echo '<div role="alert" class="alert alert-warning alert-dismissible fade in">Delete Product(post) on no quantity is turned on. This may result in not importing products with no quantity. You can change this option from <a href="?'.  http_build_query(array_merge($_GET, array('kbAction' => 'settingsGeneral'))).'">options</a>. <button aria-label="Close" data-dismiss="alert" class="close" type="button" data-option="DropShipManagerDontShowDeleteOnNoQuantity" data-option-value="1"><span aria-hidden="true">×</span></button></div>';
}


$posts = getKbDropShipManagerPosts();


echo '<table class="wp-list-table widefat fixed kbamz-items table">';
echo '<thead>';
    echo '<tr>';
        echo '<th style="width:5ex;">&nbsp;</th>';
        echo '<th style="width:10ex;">#</th>';
        echo '<th style="width:7ex;">&nbsp;</th>';
        echo '<th style="width:20ex;text-align:center;">ASIN</th>';
        echo '<th>Item Name</th>';
        echo '<th style="width:12ex;text-align:right;">Import Price</th>';
        echo '<th style="width:13ex;text-align:right;">Current Price</th>';
        echo '<th style="width:15ex;text-align:right;">Available</th>';
        echo '<th style="width:12ex;text-align:right;">Date</th>';
        echo '<th style="width:4ex;"><a href="#" class="all-product-refresh"><span class="glyphicon glyphicon-refresh" aria-hidden="true" title="refresh"></span></a></th>';
        echo '<th style="width:4ex;"></th>';
    echo '</tr>';
echo '</thead>';

if (empty($posts)) {
    echo '<tr><td colspan="5">No items added.</td></tr>';
}

$i = 0;
foreach ($posts as $key => $post)
{
    echo '<tr class="'.($key % 2 === 0? 'alt' : 'no-alt').'">';
    echo getDropShipManagerTableRow($post, array('index' => ++$i));
    echo '</tr>';
}

echo '</table>';
?>
<style type="text/css">
.table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td {
    padding: 5px;
}
</style>

<!-- Modal -->
<div class="modal fade" id="product-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 50%;min-width: 600px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Product Data</h4>
            </div>
            <div class="modal-body">
                <div class="progress">
                    Loading...
                </div>
                <div class="data">
                    
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


<script>
    (function($, data, url) {
        $(function(){
            $('body').on('click', 'a.product-modal', function(e) {
                e.preventDefault();
                var $this = $(this);
                $('#product-modal').modal('show');
                $('#product-modal .progress').show();
                $('#product-modal .data').hide();
                
                $.ajax({
                    type: "POST",
                    url : url,
                    data: {
                        'action' : 'KbAmazonDropShipManagerProductDataAction',
                        'post' : $this.data('post')
                    }
                }).done(function(data) {
                    $('#product-modal .progress').hide();
                    $('#product-modal .data').html(data).show();
                }).error(function(){
                    alert('Unable to connect to the server. Please try again.');
                });
                
            });

            function refreshItem(callback, $tr)
            {
                $('body').addClass('loading');
                
                var $a      = $tr.find('a[data-asin]');
                var asin    = $a.attr('data-asin');
                var postId  = $a.attr('data-post');
                
                $tr.addClass('info');
                $.ajax({
                    type: "POST",
                    url : url,
                    dataType: 'json',
                    data: {
                        'action' : 'KbAmazonDropShipManagerrefreshAction',
                        'asin'   : asin,
                        'postId' : postId
                    }
                }).done(function(data) {
                    if (data && data.success && data.success === true) {
                        $tr.html(data.row);
                        $tr.addClass('success');
                    } else {
                        $tr.addClass('danger');
                    }
                }).error(function(){
                    $tr.addClass('danger');
                }).always(function () {
                    $('body').removeClass('loading');
                    $tr.removeClass('info');
                    callback();
                    
                    setTimeout(function () {
                        $tr.removeClass('info danger success');
                    }, 10000);
                });
            }
            
            
            $('body').on('click', 'a.product-refresh', function(e) {
                e.preventDefault();
                refreshItem(function () {
                    
                }, $(this).closest('tr'));
                return false;
            });
            
            function recursionUpdateItem($tr)
            {
                if (!$tr.length) {
                    return;
                }
                refreshItem(function () {
                    recursionUpdateItem($tr.next('tr'));
                }, $tr);
            }
            
            $('body').on('click', '.all-product-refresh', function (e) {
                e.preventDefault();
                recursionUpdateItem($('.kbamz-items tbody tr').first());
                return false;
            });
            
            $('body').on('click', 'a.product-remove', function() {
                
                if (!confirm('I want to remove this item.')) {
                    return;
                }
                
                $('body').addClass('loading');
                var $this = $(this);
                $.ajax({
                    type: "POST",
                    url : url,
                    dataType: 'json',
                    data: {
                        'action' : 'KbAmazonDropShipManagerRemoveAction',
                        'post' : $this.data('post')
                    }
                }).done(function(data) {
                    if (!data.success) {
                        alert('An error appeared. Please try again.');
                    } else {
                       window.location.reload();
                    }
                    $('body').removeClass('loading');
                }).error(function(){
                    alert('Unable to connect to the server. Please try again.');
                    $('body').removeClass('loading');
                });
            });
        });
        
        var iddleTimeout;
        $('*').bind('mousemove keydown scroll', function () {
            clearTimeout(iddleTimeout);
            iddleTimeout = setTimeout(function () {
                if ($('body').hasCLass('loading')) {
                    $('.all-product-refresh').click();
                }
            }, 1000 * 60 * 10);
        });

    })(jQuery, '<?php echo $this->postData; ?>', '<?php echo getKbAmzAjaxUrl(); ?>');
</script>