<?php


$orders = $data[Tags::RESULT];
$pagination = $data['pagination'];
$this->load->model("user/user_model", "mUserModel");


?>


<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <!-- Message Error -->
            <div class="col-sm-12">
                <?php $this->load->view(AdminPanel::TemplatePath."/include/messages"); ?>
            </div>

        </div>

        <div class="row">
            <div class="col-xs-12">
                <div class="box box-solid">
                    <div class="box-header" style="width : 100%;">
                        <div class=" row ">
                            <div class="pull-left col-md-7 box-title">
                                <b><?= Translate::sprint("Orders Management") ?></b>
                            </div>
                            <div class="pull-right col-md-5">
                                <div class="row">
                                    <div class="pull-right col-sm-4">
                                        <a class="btn btn-outline bg-primary" style="display: block" href="#" data-toggle="modal" data-toggle="tooltip"
                                           data-target="#modal-default-filter">
                                            <i class="mdi mdi-filter"></i>&nbsp;<?=_lang('Filter orders')?>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <!-- /.box-header -->
                    <div class="box-body table-responsive">

                        <?php if(
                                RequestInput::get('select_owner')!="" OR
                                RequestInput::get('date_start')!="" OR
                                RequestInput::get('date_end')!="" OR
                                RequestInput::get('select_order_status')!="" OR
                                RequestInput::get('select_payment_status')!="" OR
                                RequestInput::get('select_owner')!=""
                        ): ?>
                        <div id="orders-filter-result-tags" class="margin-bottom">
                            <?=_lang("Filter")?>:
                            <?php if(RequestInput::get('product')!=""): ?>
                                <span class="badge badge-filter"><a href="#" data-name="product"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Product')?>: <?=RequestInput::get('product')?></span>
                            <?php endif; ?>
                            <?php if(RequestInput::get('client_name')!=""):?>
                                <span class="badge badge-filter"><a href="#" data-name="client_name"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Client')?>: <?=RequestInput::get('client_name'); ?></span>
                            <?php endif; ?>
                            <?php if(RequestInput::get('select_owner')>0):?>

                                <?php
                                $sc = parseUrlParam('select_owner');
                                ?>
                                <span class="badge badge-filter"><a href="#" data-name="select_owner"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Owner')?>: <?=implode(' | ',$sc)?></span>
                            <?php endif; ?>
                            <?php if(RequestInput::get('date_start')!=""):?>
                                <span class="badge badge-filter"><a href="#" data-name="date_start"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Date start')?>: <?=RequestInput::get('date_start')?></span>
                            <?php endif; ?>
                            <?php if(RequestInput::get('date_end')!=""):?>
                                <span class="badge badge-filter"><a href="#" data-name="date_end"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Date end')?>: <?=RequestInput::get('date_end')?></span>
                            <?php endif; ?>

                            <?php if(RequestInput::get('select_order_status') != ""):?>
                                <?php
                                $sc = parseUrlParam('select_order_status');
                                ?>
                                <span class="badge badge-filter"><a href="#" data-name="select_order_status"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Order status')?>: <?=implode(' | ',OrderHelper::convertInToStatus($sc))?></span>
                            <?php endif; ?>
                            <?php if(RequestInput::get('select_payment_status') != ""):?>
                                <?php
                                $sc = parseUrlParam('select_payment_status');
                                ?>
                                <span class="badge badge-filter"><a href="#" data-name="select_payment_status"><i class="mdi mdi-close"></i></a>&nbsp;&nbsp;<?=_lang('Payment')?>: <?=implode(' | ',$sc)?></span>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                        <table id="" class="table table-bordered table-hover">
                            <thead>
                            <tr>
                                <th><?= Translate::sprint("Order ID") ?></th>
                                <th><?= Translate::sprint("Client") ?></th>
                                <th><?= Translate::sprint("Business Owner") ?></th>
                                <th><?= Translate::sprint("Status") ?></th>
                                <th><?= Translate::sprint("Payment") ?></th>
                                <th><?= Translate::sprint("Sub-Total") ?></th>
                                <?php if (ConfigManager::getValue('ORDER_COMMISSION_ENABLED') == TRUE): ?>
                                    <th><?= Translate::sprint("Commission") ?></th>
                                    <th><?= Translate::sprint("Profit") ?></th>
                                <?php endif; ?>

                                <th><?= Translate::sprint("Date") ?></th>
                                <th>

                                    <?php

                                    $export_plugin = $this->exim_tool->plugin_export(array(
                                        'module' => 'orders'
                                    ));

                                    echo $export_plugin['html'];
                                    AdminTemplateManager::addScript($export_plugin['script']);

                                    ?>

                                </th>
                            </tr>
                            </thead>
                            <tbody id="list">

                            <?php

                            $total_commission = 0;
                            $total_amount = 0;

                            ?>
                            <?php if (!empty($orders)) : ?>

                                <?php foreach ($orders as $key => $order): ?>

                                <?php $invoice = $this->mOrderModel->getInvoiceID($order['id']); ?>

                                    <?php

                                    $token = $this->mUserBrowser->setToken(Text::encrypt($order['id']));
                                    ?>

                                    <tr class="store_<?= $token ?>" role="row" class="odd">
                                        <td>
                                            <span style="font-size: 14px">  <b> <?= "#" . str_pad($order['id'], 6, 0, STR_PAD_LEFT) ?> </b> </span>
                                        </td>
                                        <td>
                                            <u><?= ucfirst($this->mUserModel->getUserFieldData("name", $order['user_id'])) ?></u>
                                            <?php if (GroupAccess::isGranted("user", MANAGE_USERS)): ?>
                                                &nbsp;&nbsp;<a target="_blank"
                                                               href="<?= admin_url("user/edit?id=" . $order['user_id']) ?>"><i
                                                            class="mdi mdi-open-in-new"></i></a>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php $store = $this->mOrder->getStoreFromCart($order['id']);?>
                                            <a target="_blank"
                                               href="<?= admin_url("user/edit?id=" . $store['user_id']) ?>"><?= ucfirst($this->mUserModel->getUserNameById($store['user_id'])) ?>
                                                <i class="mdi mdi-open-in-new"></i></a></a>
                                        </td>
                                        <td>
                                            <?php
                                            if (isset($order['status']) && $order['status'] != "") {
                                                $statusParser = explode(";", $order['status']);
                                                echo "<span class=badge style='background:" . $statusParser[1] . "'>" . $statusParser[0] . "</span>";
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <?php

                                            $pcode = $order['payment_status'];
                                            $payments = Order_payment::PAYMENT_STATUS;
                                            if($pcode == "cod_paid"){
                                                echo "<span class='badge' style='background-color: " . $payments[$pcode]['color'] . "'>"._lang("Paid on delivery")."</span>";
                                            }else if($pcode == "cod"){
                                                echo "<span class='badge'  style='background-color: " . $payments[$pcode]['color'] . "'>"._lang("Cash on delivery")."</span>";
                                            }else if (isset($payments[$pcode])) {
                                                echo "<span class='badge' style='background-color: " . $payments[$pcode]['color'] . "'>" . ucfirst(_lang($payments[$pcode]['label'])) . "</span>";
                                            }

                                            ?>
                                        </td>


                                            <?php

                                            $cart = json_decode($order['cart'], JSON_OBJECT_AS_ARRAY);
                                            $sub_total = 0;
                                            $currency = DEFAULT_CURRENCY;

                                            $commission = 0;

                                            foreach ($cart as $item) {
                                                $callback = NSModuleLinkers::find($item['module'], 'getData');
                                                if ($callback != NULL) {
                                                    $params = array(
                                                        'id' => $item['module_id']
                                                    );
                                                    $result = call_user_func($callback, $params);
                                                    if (!empty($result['currency']) && is_array($result['currency'])) {
                                                        $currency = $result['currency']['code'];
                                                    } else if (isset($result['currency'] ) && is_string($result['currency'])) {
                                                        $currency = $result['currency'];
                                                    }else{
                                                        $currency = DEFAULT_CURRENCY;
                                                    }
                                                }

                                                $sub_total = $sub_total + ($item['amount'] * $item['qty']);
                                                $total_amount = $total_amount + $sub_total;
                                                //Order Has commission
                                                if($order['commission']>0){
                                                    $commission = $sub_total/$order['commission'];
                                                    $total_commission += $commission;
                                                }
                                            }

                                            if (defined('DEFAULT_TAX') and DEFAULT_TAX > 0) {
                                                $percent = 0;
                                                $tax = $this->mTaxModel->getTax(DEFAULT_TAX);
                                                if ($tax != NULL) {
                                                    $percent = $tax['value'];
                                                }
                                            }

                                            if($invoice!=null){
                                                $discounts = json_decode($invoice['discounts'], JSON_OBJECT_AS_ARRAY);
                                                if (isset($discounts) && !empty($discounts)){
                                                    foreach ($discounts as $k22 => $value){
                                                        $sub_total = $value + $sub_total;
                                                    }
                                                }
                                            }

                                            $amount = $this->mOrder->getTotalOrder($order['id']);

                                            ?>



                                        <td>
                                            <?="<b>" . Currency::parseCurrencyFormat($sub_total, $currency) . "</b>"?>
                                        </td>

                                        <?php if (ConfigManager::getValue('ORDER_COMMISSION_ENABLED') == TRUE): ?>
                                            <td><?= Currency::parseCurrencyFormat($commission, $currency); ?></td>
                                            <td>
                                                <strong class="text-green">+<?= Currency::parseCurrencyFormat(($sub_total - $commission), $currency); ?></strong>
                                            </td>
                                        <?php endif; ?>

                                        <td>
                                            <span style="font-size: 14px">  <?= MyDateUtils::convert($order['updated_at'], "UTC", TimeZoneManager::getTimeZone(), "d M, Y h:i A") ?>  </span>
                                        </td>


                                        <td align="right">
                                            <?php if (ModulesChecker::isEnabled("order_payment") && $order['user_id'] == SessionManager::getData("id_user")): ?>
                                                <?php if ($invoice != NULL && ($order['payment_status'] == "" or $order['payment_status'] == "unpaid")): ?>
                                                    <a class="btn btn-sm btn-primary"
                                                       href="<?= site_url("payment/make_payment?id=" . $invoice['id']) ?>">
                                                        <?= _lang("Pay") ?>
                                                    </a>
                                                    &nbsp;
                                                <?php endif; ?>
                                            <?php endif; ?>
                                            <a class="btn btn-default" data-toggle="tooltip"
                                               href="<?= admin_url("nsorder/myOrderDetail?id=" . $order['id']) ?>"
                                               title="<?= Translate::sprint("Edit") ?>">
                                                <i class="mdi mdi-pencil"></i>
                                            </a>
                                        </td>
                                    </tr>

                                    <?php

                                    $store = $this->mOrder->getStoreFromCart($order['id']);
                                    $pcode = $order['payment_status'];
                                    $payments = Order_payment::PAYMENT_STATUS;
                                    $statusParser = explode(";", $order['status']);

                                    $array  = array(
                                        'order_id' => "#" . str_pad($order['id'], 6, 0, STR_PAD_LEFT),
                                        'client' => ucfirst($this->mUserModel->getFieldById("name", $order['user_id'])),
                                        'client_phone' => ucfirst($this->mUserModel->getFieldById("telephone", $order['user_id'])),
                                        'business_owner' => ucfirst($this->mUserModel->getUserNameById($store['user_id'])),
                                        'order_status' => $statusParser[0],
                                        'payment' => isset($payments[$pcode]) ? ucfirst(_lang($payments[$pcode]['label'])) : "",
                                        'amount' => $total_amount,
                                        'commission' => $total_commission,
                                        'date' => $order['updated_at'],
                                    );

                                    if (ModulesChecker::isEnabled('delivery')
                                        && $order['delivery_status'] == 3){
                                        $array['delivery_fees'] = $order['delivery_commission'];
                                    }

                                    echo Exim_toolManager::setupRows($array);

                                    ?>

                                <?php endforeach; ?>

                            <?php else: ?>
                                <tr>
                                    <td colspan="7" align="center">
                                        <div style="text-align: center"><?= Translate::sprint("No data found", "") ?></div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                        <?php if (GroupAccess::isGranted('nsorder', MANAGE_ORDERS)): ?>
                            <table class="table table-bordered table-hover">
                                <tr>
                                    <td width="50%"></td>
                                    <td width="25%" align="right"><b><?= _lang("Total") ?></b></td>
                                    <td width="25%"> <?= Currency::parseCurrencyFormat($total_amount, DEFAULT_CURRENCY) ?></td>
                                </tr>
                                <?php if ($total_commission > 0): ?>
                                    <tr>
                                        <td width="50%"></td>
                                        <td width="25%" align="right"><b><?= _lang("Commission") ?> (<?=$order['commission']?>%)</b></td>
                                        <td width="25%"><?= Currency::parseCurrencyFormat($total_commission, DEFAULT_CURRENCY) ?></td>
                                    </tr>
                                    <tr>
                                        <td width="50%"></td>
                                        <td width="25%" align="right"><b><?= _lang("Profit") ?></b>
                                        </td>
                                        <td width="25%"> <?= Currency::parseCurrencyFormat($total_amount - $total_commission, DEFAULT_CURRENCY) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <?php if (ModulesChecker::isEnabled('delivery') && isset($delivery_fees)): ?>
                                    <tr>
                                        <td width="50%"></td>
                                        <td width="25%" align="right"><b><?= _lang("Delivery fees") ?></b>
                                        </td>
                                        <td width="25%"> <?= Currency::parseCurrencyFormat($delivery_fees, DEFAULT_CURRENCY) ?></td>
                                    </tr>
                                <?php endif; ?>
                            </table>
                        <?php endif; ?>

                        <div class="row">
                            <div class="col-sm-12">
                                <div class="dataTables_paginate paging_simple_numbers" id="example2_paginate">
                                    <?php
                                    echo $pagination->links(array(
                                        "status" => intval(RequestInput::get("status")),
                                        "search" => RequestInput::get("search"),
                                        "owner_id" => intval(RequestInput::get("owner_id")),
                                    ), $pagination_url);
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
        <!-- /.row -->
</div>


<?php

$this->load->view('nsorder/backend/filter-modal');
$script = $this->load->view('nsorder/backend/scripts/orders-script', NULL, TRUE);
AdminTemplateManager::addScript($script);

?>
