<!-- FormPrefix --><?= $f_AdminCommon ?>
<?php
$netshop = nc_netshop::get_instance($catalogue);
$netshop_forms = $netshop->forms->get_objects();

$currencies = $netshop->get_setting('CurrencyDetails');
$default_currency = (int)$netshop->get_setting('DefaultCurrencyID');
$curency_short_name = $currencies[$default_currency]['NameShort'];

$sql = "SELECT * FROM `Classificator_ShopOrderStatus` ORDER BY `ShopOrderStatus_Priority`";
$statuses = (array)$db->get_results($sql, ARRAY_A);

$delivery_methods = $netshop->delivery->get_all_methods();
?>
<style>
    #nc_objects_filter { display: none; }
    .tpl-property-total-price { white-space: nowrap; }
</style>
<div class="nc-bg-lighten nc-padding-10" style="border-bottom: 1px solid #DDD">
    <form class="nc-form nc--horizontal" method="get">
        <!-- при использовании в качестве обычного шаблона инфоблока: -->
        <input type='hidden' name='admin_mode' value='<?= $admin_mode ?>'/>
        <input type='hidden' name='inside_admin' value='<?= (int)$inside_admin ?>'/>
        <input type='hidden' name='catalogue' value='<?= $catalogue ?>'>
        <input type='hidden' name='sub' value='<?= $sub ?>'>
        <input type='hidden' name='cc' value='<?= $cc ?>'>
        <!-- для работы внутри панели управления модулем: -->
        <input type="hidden" name="controller" value="order">
        <input type="hidden" name="action" value="index">

        <label style="padding: 0 5px"><?= NETCAT_MODULE_NETSHOP_ORDER_STATUS ?></label>
        <select name="order_status">
            <option value="-1"><?= NETCAT_MODULE_NETSHOP_ORDER_ANY ?></option>
            <option value="0"<?= (isset($order_status) && $order_status == 0) ? " selected" : "" ?>>
                <?= NETCAT_MODULE_NETSHOP_ORDER_NEW ?>
            </option>
            <?=
            listQuery("SELECT ShopOrderStatus_ID, ShopOrderStatus_Name FROM Classificator_ShopOrderStatus",
                "<option value='\$data[ShopOrderStatus_ID]'\" .
                 (\$data['ShopOrderStatus_ID']==\$_GET['order_status'] ? ' selected' : '') .
                 \">\$data[ShopOrderStatus_Name]</option>\\n")
            ?>
        </select>
        <table class="nc--wide">
            <tr>
                <td class="nc--wide">
                    <input type="text" name="text_filter" class="nc--wide"
                           style="padding:4px 6px 3px; margin:0; height: 30px"
                           placeholder="<?= htmlspecialchars(NETCAT_MODULE_NETSHOP_ORDER_SEARCH) ?>"
                           value="<?= htmlspecialchars($text_filter) ?>">
                    <i class="nc-icon nc--remove"
                       style="position: absolute; margin:5px 0 0 -25px; cursor: pointer; display: none"></i>
                </td>
            </tr>
        </table>
        <table class="nc--wide">
            <tr>
                <td>
                    <label><?= NETCAT_MODULE_NETSHOP_DATE_FILTER; ?> <?= NETCAT_MODULE_NETSHOP_DATE_FILTER_FROM; ?>
                        <input size="7" type="text" name="date_from" value="<?= htmlspecialchars($date_from) ?>"/></label>
                    <label><?= NETCAT_MODULE_NETSHOP_DATE_FILTER_TO; ?>
                        <input size="7" type="text" name="date_to" value="<?= htmlspecialchars($date_to) ?>"/></label>
                </td>
                <td>
                    <label><?= NETCAT_MODULE_NETSHOP_PRICE_FILTER; ?> <?= NETCAT_MODULE_NETSHOP_PRICE_FILTER_FROM; ?>
                        <input size="7" type="text" name="price_from" value="<?= htmlspecialchars($price_from) ?>"/> <?= $curency_short_name; ?>
                    </label>
                    <label><? NETCAT_MODULE_NETSHOP_PRICE_FILTER_TO; ?>
                        <input size="7" type="text" name="price_to" value="<?= htmlspecialchars($price_to) ?>"/> <?= $curency_short_name; ?>
                    </label>
                </td>
                <td>
                    <label><?= NETCAT_MODULE_NETSHOP_DELIVERY_METHOD_FILTER; ?>
                        <select name="delivery_method" style="width: 200px;">
                            <option value="-1"><?= NETCAT_MODULE_NETSHOP_DELIVERY_METHOD_ALL; ?></option>
                            <? foreach ($delivery_methods as $delivery_method) { ?>
                                <option value="<?= $delivery_method['id']; ?>" <?= $delivery_method['id'] == $_GET['delivery_method'] ? 'selected="selected"' : ''; ?>><?= $delivery_method['name']; ?></option>
                            <? } ?>
                        </select>
                    </label>
                </td>
                <td>
                    <button type="submit" style="height: 30px">OK</button>
                </td>
            </tr>
        </table>
        <script>
            (function () {
                var input = $nc('input[name=text_filter]'),
                    clearButton = input.next(".nc--remove");

                input.on('change keyup',function () {
                    clearButton.css('display', (this.value ? '' : 'none'));
                }).change();

                clearButton.on('click', function () {
                    input.val('');
                    if (input.attr('value')) {
                        input.closest('form').submit();
                    }
                    else {
                        input.change();
                    }
                });
            })();

            $nc(function () {
                $nc('SELECT[name^="Status["').on('change', function (e) {
                    var $this = $nc(e.target);

                    if (confirm('<?= NETCAT_MODULE_NETSHOP_CONFIRM_STATUS_CHANGE; ?>')) {
                        var value = $this.val();
                        $this.attr('data-nc-original', value);
                        var id = /\[(\d+)\]/.exec($this.attr('name'));
                        id = id[1];

                        var checked = $nc('INPUT[name="Checked[' + id + ']"').val();
                        nc.process_start('status_change_' + id);

                        var url = '<?= $SUB_FOLDER . $HTTP_ROOT_PATH . "message.php?inside_admin=1&catalogue=" . $catalogue . "&sub=" . $sub . "&cc=" . $cc . "&classID=" . $classID . "&posting=1" . ($curPos ? "&curPos=" . $curPos : "") . ($admin_mode ? "&admin_mode=1" : ""); ?>';
                        url += '&message=' + id + '&f_Status=' + value + '&f_Checked=' + checked + '&update_status_action=1';

                        $nc.get(url, function () {
                            nc.process_stop('status_change_' + id);
                        });
                    } else {
                        $this.val($this.attr('data-nc-original'));
                    }

                    return true;
                });

                $nc('TH[class*="nc-sort"]').on('click', function () {
                    var $this = $nc(this);
                    var $tbody = $this.closest('TABLE').find('TBODY');
                    $this.siblings().removeClass('nc-sort-desc').removeClass('nc-sort-asc');
                    if ($this.hasClass('nc-sort-asc') || !$this.hasClass('nc-sort-desc')) {
                        $this.removeClass('nc-sort-asc').addClass('nc-sort-desc');
                    } else {
                        $this.removeClass('nc-sort-desc').addClass('nc-sort-asc');
                    }

                    var cell_index = $this.index('TH', $this.closest('TR'));

                    var source_array = [];

                    var i = 0;
                    $this.closest('TABLE').find('TR').not($this.closest('TR')).each(function () {
                        var value = $nc(this).find('TD').eq(cell_index);

                        switch (true) {
                            default:
                                value = value.text();
                                break;
                            case $this.hasClass('nc-sort-date'):
                                value = new Date(value.text().replace(/(\d+)\.(\d+)\.(\d+)/, '$3-$2-$1')).getTime();
                                break;
                            case $this.hasClass('nc-sort-float'):
                                value = parseFloat(value.text().replace(/[^\d\.\,]/g, ''));
                                value = isNaN(value) ? 0 : value;
                                break;
                            case $this.hasClass('nc-sort-select'):
                                value = value.find('OPTION:checked').text();
                                break;
                        }

                        source_array.push([$nc(this).detach(), value]);

                        i++;
                        return true;
                    });

                    source_array.sort(function (a, b) {
                        if (a[1] > b[1]) return 1;
                        else if (a[1] < b[1]) return -1; else return 0;
                    });

                    if ($this.hasClass('nc-sort-desc')) {
                        source_array.reverse();
                    }

                    for (var i in source_array) {
                        $tbody.append(source_array[i][0]);
                    }

                    return true;
                });

                $nc('INPUT[name=date_from], INPUT[name=date_to]').datepicker();
            });
        </script>
    </form>
</div>

<div class="nc-padding-20" style="padding-left:0 !important">
    <table class="nc-table nc--bordered nc--striped nc--wide">
        <thead>
        <tr style="cursor: pointer;">
            <th class="nc-sort-date nc-sort-desc">Дата</th>
            <th class="nc-sort-float">Номер заказа</th>
            <th class="nc-sort-string">Покупатель</th>
            <th class="nc-sort-string">Контакты</th>
            <th class="nc-sort-string">Содержание</th>
            <th class="nc-sort-float">Сумма</th>
            <th class="nc-sort-string">Способ доставки</th>
            <th class="nc-sort-select">Статус</th>
        </tr>
        </thead>
        <tbody><!-- /FormPrefix -->

<!-- RecordTemplate --><?php
        $order = new nc_netshop_order($res[$f_RowNum]);
        $order->set_catalogue_id($catalogue);
        ?>
        <tr>
            <td><?= $f_Created_day; ?>.<?= $f_Created_month; ?>.<?= $f_Created_year; ?></td>
            <td>
                <a href="<?= $f_AdminButtons_change; ?>" title="<?= NETCAT_MODERATION_CHANGE; ?>" onclick="parent.nc_form(this.href); return false;"><?= $f_RowID; ?></a>
            </td>
            <td><?= $f_ContactName; ?></td>
            <td><?= implode(',<br>', array($f_Email, $f_Phone)); ?></td>
            <td>
                <? foreach ($order->get_items() as $item) { ?>
                    <?=
                    htmlspecialchars($item['Vendor']) . " " .
                    htmlspecialchars($item['Name']) . " " .
                    htmlspecialchars($item['VariantName']) ?> - <?= $item['Qty'] ?> <?= $item['Units'] ?><br>
                <? } ?>
            </td>
            <td class="tpl-property-total-price"><?= $order['TotalPriceF']; ?></td>
            <td><?= $order['DeliveryMethodName']; ?></td>
            <td>
                <input type="hidden" name="Checked[<?= $f_RowID; ?>]" value="<?= $f_Checked; ?>"/>
                <select name="Status[<?= $f_RowID; ?>]" data-nc-original="<?= $f_Status_id; ?>">
                    <option value="0"><?= NETCAT_MODULE_NETSHOP_ORDER_NEW; ?></option>
                    <? foreach ($statuses as $status) { ?>
                        <option value="<?= $status['ShopOrderStatus_ID']; ?>" <?= $f_Status_id == $status['ShopOrderStatus_ID'] ? 'selected="selected"' : ''; ?>><?= $status['ShopOrderStatus_Name']; ?></option>
                    <? } ?>
                </select>
            </td>
        </tr><!-- /RecordTemplate -->

<!-- FormSuffix -->        </tbody>
    </table>
</div>
<div style="margin: 15px 0">
    <?=
    browse_messages($cc_env, 15, array(
        'prefix' => "",
        'suffix' => "",
        'active' => "<b>%PAGE</b>",
        'unactive' => "<a href=%URL>%PAGE</a>",
        'divider' => " | ",
    )) ?></div><!-- /FormSuffix -->