<?php
$title = ___("Self-Service Store Configuration");
$this->setLayout('admin/layout.phtml');
?>
<?php foreach ($this->sstypes as $sst): /* @var $sst SelfserviceType */?>
<div class="selfservice-type" data-id="<?php echo $sst->pk() ?>">
    <div class="selfservice-type-title" data-title="<?php p($sst->title)?>">
        <div class="input-ss-wrapper">
            <div class="input-ss-inner-wrapper">
                <input type="text" id="selfservice-type-<?php p($sst->pk()) ?>" class="input-ss" value="<?php p($sst->title)?>" />
                <div class="input-ss-accept">&nbsp;</div>
                <div class="input-ss-decline">&nbsp;</div>
            </div>
        </div>
    </div>

    <div class="in-product product-section">
    <?php $col_title = ___('Products that bring credits'); ?>
    <?php include $this->_script('self-service/admin/_products_filter.phtml'); ?>
    <div class="products">
    <?php foreach ($sst->getProductsRelation(SelfserviceTypeProduct::IN) as $sstp): /* @var $sstp SelfserviceTypeProduct */?>
    <?php renderProductBlock($sstp->getProduct(), $sstp); ?>
    <?php endforeach; ?>
    </div>
    </div>

    <div class="out-product product-section">
    <?php $col_title = ___('Products that can be purchased with credits'); ?>
    <?php include $this->_script('self-service/admin/_products_filter.phtml'); ?>
    <div class="products">
    <?php foreach ($sst->getProductsRelation(SelfserviceTypeProduct::OUT) as $sstp): /* @var $sstp SelfserviceTypeProduct */?>
    <?php renderProductBlock($sstp->getProduct(), $sstp); ?>
    <?php endforeach; ?>
    </div>
    </div>

    <div class="spare-product product-section">
    <?php $col_title = ___('Available Products'); ?>
    <?php include $this->_script('self-service/admin/_products_filter.phtml'); ?>
    <div class="products">
    <?php foreach ($sst->getSpareProducts() as $p): /* @var $sstp SelfserviceTypeProduct */?>
    <?php renderProductBlock($p); ?>
    <?php endforeach; ?>
    </div>
    </div>
</div>
<?php endforeach ?>
<style type="text/css">
<!--
.selfservice-type {
    overflow: hidden;
    background: white;
}
.selfservice-type .selfservice-type-title {
    font-size:120%;
    margin:10px;
}
.selfservice-type .product-section {
    width: 30%;
    float: left;
    padding:10px;
}
.products {
    padding-bottom: 2em;
    max-height: 600px;
    overflow-y: auto;
}

.in-product .products,
.out-product .products {
    min-height: 200px;
    padding: .2em .2em 4em;
    border: 2px dashed #ddd;
}

.product-form { display: none;}
.in-product .in-product-form { display: block; margin-top:0.5em;}
.out-product .out-product-form { display: block; margin-top:0.5em; }
.spare-product .spare-product-form { display: block; }
.product {
    border: solid 1px #e7e7e7;
    margin: 4px;
    padding: 0.4em;
    background: #f1f1f1;
    cursor: move;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
    box-sizing: content-box;
}
.product:hover {
    border-color: #777;
}

.product-terms {
    font-style: italic;
}

.product-header {
    margin-bottom:0.8em;
}
.product-header h3 {
    display: inline;
}

.input-product-filter-wrapper {
    overflow: hidden;
    padding: 0.4em;
    border: 1px solid #c2c2c2;
    margin-bottom: 1em;
    display: none;
}

.input-product-filter-inner-wrapper {
    position: relative;
    padding-right:15px;
}

.input-product-filter-empty {
    position: absolute;
    top:0;
    right:0;
    width: 20px;
    cursor: pointer;
    opacity: .3;
    background: url("<?php echo $this->_scriptImg('icons/decline-d.png') ?>") no-repeat center center transparent;
}

.input-product-filter-empty:hover {
   opacity: 1;
   background-image: url("<?php echo $this->_scriptImg('icons/decline.png') ?>");
}

.input-product-filter-wrapper input.input-product-filter {
    padding:0;
    margin:0;
    border: none;
    width:100%;
    padding-left: 24px;
    background: url("<?php echo $this->_scriptImg('icons/magnify.png') ?>") no-repeat left center;
}

.input-product-filter-wrapper input.input-product-filter:focus {
    border: none;
    box-shadow: none;
}

.input-product-filter-wrapper input.input-product-filter:focus {
    border: none;
    outline: 0;
    background-color: unset;
}

/* type edit */
.input-ss-wrapper {
    overflow: hidden;
    padding: 0.2em 0.4em;
    border: 1px solid #ced4da;
    border-radius: 3px;
    margin-bottom: 1em;
    display: none;
    width:200px
}

.input-ss-inner-wrapper {
    position: relative;
    padding-right:40px;
}

.input-ss-accept {
    position: absolute;
    top:0;
    right:20px;
    text-align: center;
    width: 20px;
    cursor: pointer;
    opacity: .3;
    background: url("<?php echo $this->_scriptImg('icons/accept-d.png') ?>") no-repeat center center transparent;
}

.input-ss-accept:hover {
   opacity: 1;
   background-image: url("<?php echo $this->_scriptImg('icons/accept.png') ?>");
}

.input-ss-decline {
    position: absolute;
    top:0;
    right:0;
    width: 20px;
    cursor: pointer;
    opacity: .3;
    background: url("<?php echo $this->_scriptImg('icons/decline-d.png') ?>") no-repeat center center transparent;
}

.input-ss-decline:hover {
   opacity: 1;
   background-image: url("<?php echo $this->_scriptImg('icons/decline.png') ?>");
}

.input-ss-wrapper input.input-ss {
    padding:0;
    margin:0;
    border: none;
    width:100%;
}

.input-ss-wrapper input.input-ss:focus {
    background: none;
    outline:none;
    box-shadow:none;
}

div.credits_period
{
    display: inline;
}

.selfservice-type .credits_period input,
.selfservice-type .credits_period select  {
    padding: 0.1em
}
.selfservice-type .credits_period select  {
    width:70px;
}
-->
</style>
<?php function renderProductBlock(Product $p, SelfserviceTypeProduct $rel = null) {
$bp = $p->getBillingPlan();
?>
<div class="product"
    data-title="<?php p(mb_strtolower($p->title)); ?>"
    data-product_id="<?php p($p->pk())?>"
    data-billing_plan_id="<?php p($bp->pk())?>">
    <div class="product-title"><strong><?php p($p->title); ?></strong>: <?php p($bp->title) ?></div>
    <div class="product-terms"><?php echo $bp->getTermsText() ?></div>
    <div class="in-product-form product-form">
        <input type="hidden" name="product_id" value="<?php p($p->pk())?>" />
        <input type="hidden" name="billing_plan_id" value="<?php p($bp->pk())?>" />
        <input type="hidden" name="relation" value="in" />
        <?php __e('On purchase') ?>: <input id="product-<?php p($bp->pk()) ?>-value" type="integer" name="value" class="credit-live-edit" data-sign="+" size="3" value="<?php p($rel ? $rel->value : 0) ?>"/> <?php __e('credits') ?><?php if ((float)$bp->second_price) : ?>,
        <?php __e('rebill') ?> <input id="product-<?php p($bp->pk()) ?>-value_second" type="integer" name="value_second" class="credit-live-edit" data-sign="+" size="3" value="<?php p($rel ? $rel->value_second : 0) ?>"/> <?php __e('credits') ?>
        <?php endif; ?><br/>
        <?php __e('Expire credits') ?>
            <?php
            preg_match('/^([0-9]*)?([a-z]+)$/', $rel ? $rel->expire : 'lifetime', $m);
            $c = $m[1];
            $u = $m[2];
            ?>
        <div class="credits_period"><input type="text" name="expire[c]" value="<?php p($c) ?>" size=3>
                <select name="expire[u]" size="1">
                    <?php echo Am_Html::renderOptions([
                            'd' => ___('Days'),
                            'm' => ___('Months'),
                            'y' => ___('Years'),
                            'lifetime' => ___('Lifetime'),
                            'product' => ___('Product Expiration Date')
                    ], $u ); ?>
                </select></div>
    </div>
    <div class="out-product-form product-form">
        <input type="hidden" name="product_id" value="<?php p($p->pk())?>" />
        <input type="hidden" name="billing_plan_id" value="<?php p($bp->pk())?>" />
        <input type="hidden" name="relation" value="out" />
        <?php __e('To purchase') ?>: <input id="product-<?php p($bp->pk()) ?>-value" type="integer" name="value" class="credit-live-edit" data-sign="&minus;" size="3" value="<?php p( $rel ? $rel->value : 0 ) ?>"/> <?php __e('credits') ?>
    </div>
    <div class="spare-product-form product-form">
        <input type="hidden" name="product_id" value="<?php p($p->pk())?>" />
        <input type="hidden" name="billing_plan_id" value="<?php p($bp->pk())?>" />
        <input type="hidden" name="relation" value="null" />
    </div>
</div>
<?php }; ?>

<script type="text/javascript">
jQuery(function($){
function saveItem(item)
{
    var vars = item.find(".product-form:visible :input").serializeArray();
    vars.push( { name: "type_id" , 'value' : item.closest(".selfservice-type").data('id')} );
    var url = amUrl('/self-service/admin-products/ajax-save', 1);
    jQuery.post(url[0], jQuery.merge(vars, url[1]));
}

jQuery(".products").sortable({
    connectWith: ".products",
    receive: function(event, ui) {
        saveItem(jQuery(ui.item));
    },
    stop: function(event, ui) {
        var pref = [];
        jQuery('.out-product .product').each(function(){
            pref.push(jQuery(this).data('billing_plan_id'));
        });
        var vars = {
            order: pref
        };
        var url = amUrl('/self-service/admin-products/ajax-sort', 1);
        jQuery.post(url[0], jQuery.merge(vars, url[1]));
    }
});

jQuery(".product :input").change(function(){
    var item = jQuery(this).closest(".product");
    saveItem(item);
});

jQuery('.input-product-filter-link').click(function(){
    jQuery('.input-product-filter-wrapper', jQuery(this).closest('.product-section')).toggle();
    if (jQuery(this).hasClass('closed'))
            jQuery('.input-product-filter-wrapper input', jQuery(this).closest('.product-section')).focus();
    jQuery(this).toggleClass('opened closed')
    jQuery('.input-product-filter', jQuery(this).closest('.product-section')).val('').change();
});

jQuery(document).on('keyup change','.input-product-filter', function(){
     var $context = jQuery(this).closest('.product-section');
     jQuery('.input-product-filter-empty', $context).toggle(jQuery(this).val().length != 0);

     if (jQuery(this).val()) {
         jQuery('.product', $context).hide();
         jQuery('.product[data-title*="' + jQuery(this).val().toLowerCase() + '"]', $context).show();
     } else {
         jQuery('.product', $context).show();
     }
});

jQuery('.input-product-filter-empty').click(function(){
    jQuery(this).closest('.input-product-filter-wrapper').find('.input-product-filter').val('').change();
    jQuery(this).hide();
});

jQuery('.credit-live-edit').each(function(){
    var $a = jQuery('<a href="javascript:;" class="local">' + jQuery(this).data('sign') + jQuery(this).val() + '</a>');
    jQuery(this).hide().after($a);
    var $input = jQuery(this);

    var close = function(){
        jQuery("body").unbind("click." + $input.attr('id'));
        $a.text($input.data('sign') + $input.val()).show();
        $input.blur().hide();
    };

    $input.bind('keyup', function(e){
        var code = e.keyCode || e.which;
        if (code == 13) close();
    });

    $a.click(function(event){
        $a.hide();
        $input.show().focus()[0].select();
        var curEvent = event;
        // bind outerclick event
        jQuery("body").bind("click." + $input.attr('id'), function(event){
            if (event.originalEvent != curEvent.originalEvent && event.target != $input[0]) {
                close()
            }
        });
    });
});

jQuery(function(){
   jQuery('select', '.credits_period').change(function(){
       jQuery('input[type=text]', jQuery(this).parent()).toggle(!['lifetime', 'product'].includes(jQuery(this).val()));
   }).change();
});

jQuery('.input-ss-wrapper').each(function(){
    var $scope = jQuery(this);
    var $input = jQuery('input', $scope);
    var $a = jQuery('<a href="javascript:;" class="local">' + $input.val() + '</a>');
    $scope.hide().after($a);

    var updateWidth = function() {
        $scope.css({width: 100 + $input.val().length * 9 + 'px'})
    };

    updateWidth();

    $input.bind('keyup', function() {
        updateWidth();
    });

    jQuery('.input-ss-decline', $scope).click(function(){
        $a.show();
        $input.val($input.data('prev-value'));
        $scope.hide();
    });

    jQuery('.input-ss-accept', $scope).click(function(){
        $a.text($input.val()).show();
        $input.data('prev-value', $input.val());
        $scope.hide();
        var url = amUrl('/self-service/admin-products/ajax-type', 1);
        var vars = [
            {name: "id",    value: $a.closest('.selfservice-type').data('id')},
            {name: "title", value: $input.val()}
        ];
        jQuery.post(url[0], jQuery.merge(vars, url[1]));
    });

    $a.click(function(event){
        $a.hide();
        $input.data('prev-value', $input.val()).focus()[0].select();
        $scope.show();
        $input.focus()[0].select();
    });
});

});
</script>