<?php

if (version_compare(_PS_VERSION_, '1.5', '<')) {
    include_once(PS_ADMIN_DIR . '/tabs/AdminOrders.php');

    require_once(_PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . 'Ws.php');
    require_once(_PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . 'helper' . DIRECTORY_SEPARATOR . 'Data.php');
    require_once(_PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . 'helper' . DIRECTORY_SEPARATOR . 'Order.php');

    class AdminMbeShipping extends AdminOrders
    {

        public function __construct()
        {
            if (isset($_GET['creationorder'])) {
                $this->creationShipment();
            }

            if (Tools::isSubmit('processBulkSendedorder')) {
                $this->processBulkSended(Tools::getValue('orderBox'));
            }

            if (isset($_GET['submitAction']) && $_GET['submitAction'] == 'generateDelivery') {
                $this->generateDelivery($_GET['id_order']);
            }

            global $cookie;
            parent::__construct();

            $this->table = 'order';
            $this->className = 'Order';
            $ws = new Mbe_Shipping_Model_Ws();
            $mustClose = $ws->mustCloseShipments();
            if ($mustClose) {
                if (Configuration::get('shipments_closure_mode') == Mbe_Shipping_Helper_Data::MBE_CLOSURE_MODE_MANUALLY) {
                    $this->delete = true;
                    $this->noLink = true;
                    $this->_listSkipDelete = array();
                }
            }

            if (Configuration::get('shipments_creation_mode') == Mbe_Shipping_Helper_Data::MBE_CREATION_MODE_MANUALLY) {
                $this->creation = true;
            }

            $this->view = true;
            $this->colorOnBackground = true;
            $this->_select = 'a.date_add as dadd, o.shipping_number sn, CONCAT(c.`firstname`, \' \', c.`lastname`) AS `customer` , o.`id_order` AS `buttons`, o.`id_order` as status';
            $this->_join = ' LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (c.`id_customer` = a.`id_customer`) ';
            $this->_join .= ' LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.`id_order` = a.`id_order`) ';
            $this->_join .= ' INNER JOIN `' . _DB_PREFIX_ . 'carrier` ca ON (ca.`id_carrier` = o.`id_carrier`) AND (ca.`external_module_name` = "mbeshipping")';


            $carriers = Db::getInstance()->ExecuteS('select * from ' . _DB_PREFIX_ . 'carrier where external_module_name = "mbeshipping"');
            $carrierArray = array();
            foreach ($carriers as $carrier)
                $carrierArray[$carrier['id_carrier']] = $carrier['name'];

            $this->fieldsDisplay = array('customer' => array('title' => $this->l('Customer'), 'widthColumn' => 160, 'width' => 140, 'filter_key' => 'customer', 'tmpTableFilter' => true));
            if ($mustClose) {
                $this->fieldsDisplay['status'] = array('title' => $this->l('Status'), 'widthColumn' => 160, 'width' => 140, 'orderby' => false, 'search' => false, 'callback' => 'checkClose');
            }
            $this->fieldsDisplay['payment'] = array('title' => $this->l('Payment'), 'width' => 100, 'filter_key' => 'o!payment');
            $this->fieldsDisplay['date_add'] = array('title' => $this->l('Date'), 'width' => 100, 'align' => 'right', 'type' => 'datetime', 'filter_key' => 'a!date_add');
            $this->fieldsDisplay['total_paid'] = array('title' => $this->l('Total'), 'width' => 70, 'align' => 'right', 'prefix' => '<b>', 'suffix' => '</b>', 'price' => true, 'currency' => true, 'filter_key' => 'o!total_paid');
            $this->fieldsDisplay['id_carrier'] = array('title' => $this->l('Carrier'), 'type' => 'select', 'select' => $carrierArray, 'callback' => 'getCarrierName', 'filter_key' => 'o!id_carrier');
            $this->fieldsDisplay['sn'] = array('title' => $this->l('Tracking'), 'widthColumn' => 160, 'width' => 140, 'filter_key' => 'sn', 'tmpTableFilter' => true);
            $this->fieldsDisplay['id_order'] = array('title' => $this->l('PDF'), 'callback' => 'printPDFIconsButton', 'orderby' => false, 'search' => false);

        }

        public function creationShipment()
        {

            $idOrder = Tools::getValue('id_order');
            if ($idOrder) {
                $order = new Order($idOrder);
                if ($order->shipping_number != '') {
                    $this->errors[] = Tools::displayError($this->l('The shipment was already created'));
                } else {
                    $service = Configuration::get('carrier_' . $order->id_carrier);
                    if(!$service || $service==='')
                    {
                        $helper = new Mbe_Shipping_Helper_Data();
                        $carrier = new Carrier($order->id_carrier);
                        $service = $helper->getCustomMappingService($carrier->id);
                    }
                    $orderHelper =  new Mbe_Shipping_Helper_Order();
                    $errors = $orderHelper->addShipping($order,$service);
                    if (isset($errors) && is_array($errors) && count($errors)) {
                        $this->errors = $errors;
                    }
                    else {
                        $this->confirmations[] = $this->l('The shipment was successfully created');
                    }
                }
            }
        }

        public function generateDelivery($id_order)
        {
            $helper = new Mbe_Shipping_Helper_Data();
            $orderHelper =  new Mbe_Shipping_Helper_Order();

            $order = new Order((int)$id_order);;
            if (!Validate::isLoadedObject($order)) {
                throw new PrestaShopException('Can\'t load Order object');
            }

            $ts = explode(' ', $order->shipping_number);
            $files = '';
            foreach ($ts as $t) {
                $filenames[] = $helper->getMediaPath() . $orderHelper->getFileName($order,$t);
            }

            $helper->generateDelivery($filenames);
        }

        protected function processBulkSended($orders)
        {
            if (is_array($orders) && !empty($orders)) {
                $toClosedIds = array();
                $alreadyClosedIds = array();

                $helper = new Mbe_Shipping_Helper_Data();

                $ws = new Mbe_Shipping_Model_Ws();


                foreach ($orders as $shipmentId) {
                    if ($helper->isShippingOpen($shipmentId)) {
                        array_push($toClosedIds, $shipmentId);
                    } else {
                        array_push($alreadyClosedIds, $shipmentId);
                    }
                }

                $ws->closeShipping($toClosedIds);

                if (count($toClosedIds) > 0) {
                    $this->_confirmations[] = sprintf($this->l('Total of %d shipment(s) have been closed.'), count($toClosedIds));
                }

                if (count($alreadyClosedIds) > 1) {
                    $this->_confirmations[] = sprintf($this->l('Total of %d shipment(s) was already closed.'), count($alreadyClosedIds));
                }
            } else {
                $this->_errors[] = Tools::displayError($this->l('Please select items.'));
            }
        }


        public function displayListContent($token = null)
        {
            /* Display results in a table
             *
             * align  : determine value alignment
             * prefix : displayed before value
             * suffix : displayed after value
             * image  : object image
             * icon   : icon determined by values
             * active : allow to toggle status
             */

            global $currentIndex, $cookie;

            if (version_compare(_PS_VERSION_, '1.5', '<')) {
                $curIndex = $currentIndex;
            }
            else {
                $curIndex = AdminController::$currentIndex;
            }

            $currency = new Currency(_PS_CURRENCY_DEFAULT_);

            $id_category = 1; // default categ

            $irow = 0;
            if ($this->_list AND isset($this->fieldsDisplay['position'])) {
                $positions = array_map(create_function('$elem', 'return (int)($elem[\'position\']);'), $this->_list);
                sort($positions);
            }
            if ($this->_list) {
                $isCms = false;
                if (preg_match('/cms/Ui', $this->identifier))
                    $isCms = true;
                $keyToGet = 'id_' . ($isCms ? 'cms_' : '') . 'category' . (in_array($this->identifier, array('id_category', 'id_cms_category')) ? '_parent' : '');
                foreach ($this->_list as $tr) {
                    $id = $tr[$this->identifier];
                    echo '<tr' . (array_key_exists($this->identifier, $this->identifiersDnd) ? ' id="tr_' . (($id_category = (int)(Tools::getValue('id_' . ($isCms ? 'cms_' : '') . 'category', '1'))) ? $id_category : '') . '_' . $id . '_' . $tr['position'] . '"' : '') . ($irow++ % 2 ? ' class="alt_row"' : '') . ' ' . ((isset($tr['color']) AND $this->colorOnBackground) ? 'style="background-color: ' . $tr['color'] . '"' : '') . '>
                                <td class="center">';
                    if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
                        echo '<input type="checkbox" name="' . $this->table . 'Box[]" value="' . $id . '" class="noborder" />';
                    echo '</td>';

                    foreach ($this->fieldsDisplay as $key => $params) {
                        $tmp = explode('!', $key);
                        $key = isset($tmp[1]) ? $tmp[1] : $tmp[0];
                        echo '
                        <td ' . (isset($params['position']) ? ' id="td_' . (isset($id_category) AND $id_category ? $id_category : 0) . '_' . $id . '"' : '') . ' class="' . ((!isset($this->noLink) OR !$this->noLink) ? 'pointer' : '') . ((isset($params['position']) AND $this->_orderBy == 'position') ? ' dragHandle' : '') . (isset($params['align']) ? ' ' . $params['align'] : '') . '" ';
                        if (!isset($params['position']) AND (!isset($this->noLink) OR !$this->noLink))
                            echo ' onclick="document.location = \'' . $curIndex . '&' . $this->identifier . '=' . $id . ($this->view ? '&view' : '&update') . $this->table . '&token=' . ($token != null ? $token : $this->token) . '\'">' . (isset($params['prefix']) ? $params['prefix'] : '');
                        else
                            echo '>';
                        if (isset($params['active']) AND isset($tr[$key]))
                            $this->_displayEnableLink($token, $id, $tr[$key], $params['active'], Tools::getValue('id_category'), Tools::getValue('id_product'));
                        elseif (isset($params['activeVisu']) AND isset($tr[$key]))
                            echo '<img src="../img/admin/' . ($tr[$key] ? 'enabled.gif' : 'disabled.gif') . '"
                            alt="' . ($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')) . '" title="' . ($tr[$key] ? $this->l('Enabled') : $this->l('Disabled')) . '" />';
                        elseif (isset($params['position'])) {
                            if ($this->_orderBy == 'position' AND $this->_orderWay != 'DESC') {
                                echo '<a' . (!($tr[$key] != $positions[sizeof($positions) - 1]) ? ' style="display: none;"' : '') . ' href="' . $curIndex .
                                    '&' . $keyToGet . '=' . (int)($id_category) . '&' . $this->identifiersDnd[$this->identifier] . '=' . $id . '
                                        &way=1&position=' . (int)($tr['position'] + 1) . '&token=' . ($token != null ? $token : $this->token) . '">
                                        <img src="../img/admin/' . ($this->_orderWay == 'ASC' ? 'down' : 'up') . '.gif"
                                        alt="' . $this->l('Down') . '" title="' . $this->l('Down') . '" /></a>';

                                echo '<a' . (!($tr[$key] != $positions[0]) ? ' style="display: none;"' : '') . ' href="' . $curIndex .
                                    '&' . $keyToGet . '=' . (int)($id_category) . '&' . $this->identifiersDnd[$this->identifier] . '=' . $id . '
                                        &way=0&position=' . (int)($tr['position'] - 1) . '&token=' . ($token != null ? $token : $this->token) . '">
                                        <img src="../img/admin/' . ($this->_orderWay == 'ASC' ? 'up' : 'down') . '.gif"
                                        alt="' . $this->l('Up') . '" title="' . $this->l('Up') . '" /></a>';
                            } else
                                echo (int)($tr[$key] + 1);
                        } elseif (isset($params['image'])) {
                            // item_id is the product id in a product image context, else it is the image id.
                            $item_id = isset($params['image_id']) ? $tr[$params['image_id']] : $id;
                            // If it's a product image
                            if (isset($tr['id_image'])) {
                                $image = new Image((int)$tr['id_image']);
                                $path_to_image = _PS_IMG_DIR_ . $params['image'] . '/' . $image->getExistingImgPath() . '.' . $this->imageType;
                            } else
                                $path_to_image = _PS_IMG_DIR_ . $params['image'] . '/' . $item_id . (isset($tr['id_image']) ? '-' . (int)($tr['id_image']) : '') . '.' . $this->imageType;

                            echo cacheImage($path_to_image, $this->table . '_mini_' . $item_id . '.' . $this->imageType, 45, $this->imageType);
                        } elseif (isset($params['icon']) AND (isset($params['icon'][$tr[$key]]) OR isset($params['icon']['default'])))
                            echo '<img src="../img/admin/' . (isset($params['icon'][$tr[$key]]) ? $params['icon'][$tr[$key]] : $params['icon']['default'] . '" alt="' . $tr[$key]) . '" title="' . $tr[$key] . '" />';
                        elseif (isset($params['price']))
                            echo Tools::displayPrice($tr[$key], (isset($params['currency']) ? Currency::getCurrencyInstance((int)($tr['id_currency'])) : $currency), false);
                        elseif (isset($params['float']))
                            echo rtrim(rtrim($tr[$key], '0'), '.');
                        elseif (isset($params['type']) AND $params['type'] == 'date')
                            echo Tools::displayDate($tr[$key], (int)$cookie->id_lang);
                        elseif (isset($params['type']) AND $params['type'] == 'datetime')
                            echo Tools::displayDate($tr[$key], (int)$cookie->id_lang, true);
                        elseif (isset($tr[$key])) {
                            $echo = ($key == 'price' ? round($tr[$key], 2) : isset($params['maxlength']) ? Tools::substr($tr[$key], 0, $params['maxlength']) . '...' : $tr[$key]);
                            echo isset($params['callback']) ? call_user_func_array(array('Mbe_Shipping_Helper_Order', $params['callback']), array($echo, $tr)) : $echo;
                        } else
                            echo '--';

                        echo (isset($params['suffix']) ? $params['suffix'] : '') .
                            '</td>';
                    }

                    if ($this->edit OR $this->delete OR ($this->view AND $this->view !== 'noActionColumn')) {
                        echo '<td class="center" style="white-space: nowrap;">';
                        if ($this->view)
                            $this->_displayViewLink($token, $id);
                        if ($this->creation)
                            $this->_displayCreationLink($token, $id);
                        if ($this->edit)
                            $this->_displayEditLink($token, $id);
                        if ($this->delete AND (!isset($this->_listSkipDelete) OR !in_array($id, $this->_listSkipDelete)))
                            //                        $this->_displayDeleteLink($token, $id);
                            if ($this->duplicate)
                                $this->_displayDuplicate($token, $id);

                        $this->_displayShippingLabelsLink($token, $id);
                        echo '</td>';
                    }
                    echo '</tr>';
                }
            }
        }

        protected function _displayCreationLink($token = null, $id)
        {
            global $currentIndex;

            if (version_compare(_PS_VERSION_, '1.5', '<')) {
                $curIndex = $currentIndex;
            }
            else {
                $curIndex = AdminController::$currentIndex;
            }

            $_cacheLang['Creation'] = $this->l('Creation');

            echo '
			<a href="'.$curIndex.'&'.$this->identifier.'='.$id.'&creation'.$this->table.'&token='.($token ? $token : $this->token).'">
			<img src="../img/admin/add.gif" alt="'.$_cacheLang['Creation'].'" title="'.$_cacheLang['Creation'].'" /></a>';
        }

        public function displayListFooter($token = null)
        {
            echo '</table>';
            if ($this->delete)
                echo '<p><input type="submit" class="button" name="processBulkSended' . $this->table . '" value="' . $this->l('Close selection') . '" onclick="return confirm(\'' . $this->l('Close selected items?', __CLASS__, true, false) . '\');" /></p>';
            echo '
                    </td>
                </tr>
            </table>
            <input type="hidden" name="token" value="' . ($token ? $token : $this->token) . '" />
            </form>';
            if (isset($this->_includeTab) && count($this->_includeTab))
                echo '<br /><br />';
        }

    }
} else {
    require_once(_PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'AdminMbeShippingController.php');

    class AdminMbeShipping extends AdminMbeShippingController
    {

    }
}