<?php

define('PS_MBE_DIR', getcwd());

include_once(PS_MBE_DIR . '/../../config/config.inc.php');
include_once(PS_MBE_DIR . '/../../init.php');

include_once(_PS_MODULE_DIR_ . 'mbeshipping/classes/custom/helper/Data.php');
include_once(_PS_MODULE_DIR_ . 'mbeshipping/classes/custom/Ws.php');

if (Configuration::get('shipments_closure_mode') == Mbe_Shipping_Helper_Data::MBE_CLOSURE_MODE_AUTOMATICALLY) {

    $ws = new Mbe_Shipping_Model_Ws();
    if ($ws->mustCloseShipments()) {

        define('PS_MBE_SCRIPT', true);
        $toClosedIds = array();
        $alreadyClosedIds = array();
        $withoutTracking = array();

        $helper = new Mbe_Shipping_Helper_Data();

        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            if( $helper->isEnabledCustomMapping())
            {
                $customMapping = $helper->getCustomMappingCarriers();
                $sql = 'SELECT o.`id_order` FROM ' . _DB_PREFIX_ . 'orders as a  LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (c.`id_customer` = a.`id_customer`) LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.`id_order` = a.`id_order`) INNER JOIN `' . _DB_PREFIX_ . 'carrier` ca ON ca.`id_carrier` = oc.`id_carrier` WHERE (ca.`external_module_name` = "mbeshipping") OR (oc.`id_carrier` IN (' . implode($customMapping,',') .')';
            }
            else {
                $sql = 'SELECT o.`id_order` FROM ' . _DB_PREFIX_ . 'orders as a  LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (c.`id_customer` = a.`id_customer`) LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.`id_order` = a.`id_order`) INNER JOIN `' . _DB_PREFIX_ . 'carrier` ca ON (ca.`id_carrier` = oc.`id_carrier` AND (ca.`external_module_name` = "mbeshipping"))';
            }
        }
        else {
            if( $helper->isEnabledCustomMapping())
            {
                $customMapping = $helper->getCustomMappingCarriers();
                $sql = 'SELECT o.`id_order` FROM ' . _DB_PREFIX_ . 'orders as a LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (c.`id_customer` = a.`id_customer`) LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.`id_order` = a.`id_order`) INNER JOIN `' . _DB_PREFIX_ . 'order_carrier` oc ON (o.`id_order` = oc.`id_order`) AND (oc.`id_carrier` IN (' . implode($customMapping,',') .') OR oc.`id_carrier` IN (SELECT `id_carrier` from `' . _DB_PREFIX_ . 'carrier` where `external_module_name` = "mbeshipping")) INNER JOIN `' . _DB_PREFIX_ . 'carrier` ca ON (ca.`id_carrier` = oc.`id_carrier`)';
            }
            else {
                $sql = 'SELECT o.`id_order` FROM ' . _DB_PREFIX_ . 'orders as a LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON (c.`id_customer` = a.`id_customer`) LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.`id_order` = a.`id_order`) INNER JOIN `' . _DB_PREFIX_ . 'order_carrier` oc ON (o.`id_order` = oc.`id_order`) AND oc.`id_carrier` IN (SELECT `id_carrier` from `' . _DB_PREFIX_ . 'carrier` where `external_module_name` = "mbeshipping") INNER JOIN `' . _DB_PREFIX_ . 'carrier` ca ON (ca.`id_carrier` = oc.`id_carrier`)';
            }

        }

        $results = Db::getInstance()->executeS($sql);

        $boxes = array();
        foreach ($results as $r) {
            $boxes[] = $r['id_order'];
        }

        foreach ($boxes as $shipmentId) {
            if (!$helper->hasTracking($shipmentId)) {
                array_push($withoutTracking, $shipmentId);
            }
            elseif ($helper->isShippingOpen($shipmentId)) {
                array_push($toClosedIds, $shipmentId);
            }
            else {
                array_push($alreadyClosedIds, $shipmentId);
            }
        }

        $ws->closeShipping($toClosedIds);

        if (count($withoutTracking) > 0) {
            echo sprintf(('%s - Total of %d order(s) without tracking number yet.'), date('Y-m-d H:i:s'), count($withoutTracking)) . "\n";
        }

        if (count($toClosedIds) > 0) {
            echo sprintf(('%s - Total of %d order(s) have been closed.'), date('Y-m-d H:i:s'), count($toClosedIds)) . "\n";
        }

        if (count($alreadyClosedIds) > 0) {
            echo sprintf(('%s - Total of %d order(s) was already closed'), date('Y-m-d H:i:s'), count($alreadyClosedIds)) . "\n";
        }
    }
}
else {
    echo 'You selected manually mode in the configuration';
}