<?php
require_once(_PS_MODULE_DIR_ . 'mbeshipping' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . 'Ws.php');

class Carrier extends CarrierCore
{

    const TESTTEST = 'Dont remove';


    public $mbe_module = true;

    public static function getCarriers($id_lang, $active = false, $delete = false, $id_zone = false, $ids_group = null, $modules_filters = self::PS_CARRIERS_ONLY, $cart_par = null)
    {
        $ratesHelper = new Mbe_Shipping_Helper_Rates();
        $dataHelper = new Mbe_Shipping_Helper_Data();
        if ($ids_group && (!is_array($ids_group) || !count($ids_group))) {
            return array();
        }
        $sql = '
		SELECT c.*, cl.delay
		FROM `' . _DB_PREFIX_ . 'carrier` c';
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            global $cookie, $cart;
            $sql .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_lang` cl ON (c.`id_carrier` = cl.`id_carrier` AND cl.`id_lang` = ' . (int)$id_lang . ')';
            $sql .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)' .
                ($id_zone ? 'LEFT JOIN `' . _DB_PREFIX_ . 'zone` z ON (z.`id_zone` = ' . (int)$id_zone . ')' : '') . '
                WHERE c.`deleted` = ' . ($delete ? '1' : '0');
            $sql .= ' AND (c.external_module_name <> "mbeshipping" OR c.external_module_name IS NULL ) ';
        }
        else {
            $sql .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_lang` cl ON (c.`id_carrier` = cl.`id_carrier` AND cl.`id_lang` = ' . (int)$id_lang . Shop::addSqlRestrictionOnLang('cl') . ')';
            $sql .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)' .
                ($id_zone ? ' LEFT JOIN `' . _DB_PREFIX_ . 'zone` z ON (z.`id_zone` = ' . (int)$id_zone . ')' : '') . '
		' . Shop::addSqlAssociation('carrier', 'c') . '
		WHERE c.`deleted` = ' . ($delete ? '1' : '0');
        }
        if ($active) {
            $sql .= ' AND c.`active` = 1 ';
        }
        if ($id_zone) {
            $sql .= ' AND cz.`id_zone` = ' . (int)$id_zone . ' AND z.`active` = 1 ';
        }
        if ($ids_group) {
            $sql .= ' AND EXISTS (SELECT 1 FROM ' . _DB_PREFIX_ . 'carrier_group
									WHERE ' . _DB_PREFIX_ . 'carrier_group.id_carrier = c.id_carrier
									AND id_group IN (' . implode(',', array_map('intval', $ids_group)) . ')) ';
        }
        switch ($modules_filters) {
            case 1:
                $sql .= ' AND c.is_module = 0 ';
                break;
            case 2:
                $sql .= ' AND c.is_module = 1 ';
                break;
            case 3:
                $sql .= ' AND c.is_module = 1 AND c.need_range = 1 ';
                break;
            case 4:
                $sql .= ' AND (c.is_module = 0 OR c.need_range = 1) ';
                break;
        }
        if (class_exists('Context')) {
            $context = Context::getContext();
            if (!($context->controller instanceof AdminController)) {
                $sql .= ' AND c.external_module_name <> "mbeshipping" ';
            }
        }
        $sql2 = '';
        if (Configuration::get('mbe_active') == '1') {
            if (!isset($cart)) {
                $cart = $context->cart;
            }
            if (!isset($cart)) {
                $cart = $cart_par;
            }
            if (is_a($cart, 'Cart')) {
                $id_address_delivery = $cart->id_address_delivery;
                $weight = $cart->getTotalWeight();
                $weight = $dataHelper->convertWeight($weight);
                $boxes = $ratesHelper->getTotalNumOfBoxes($weight);
                if ($ratesHelper->enabledCountry($id_address_delivery) && $weight && $boxes) {
                    $myCarriers = $ratesHelper->collectRates($cart, $weight, $boxes);
                    if (is_array($myCarriers) && !empty($myCarriers)) {
                        foreach ($myCarriers as $obj) {
                            $names[] = '"' . $obj['carrier']->name . '"';
                        }
                        $sql2 .= ' UNION ';
                        $sql2 .= '
                    SELECT c.*, cl.delay
                    FROM `' . _DB_PREFIX_ . 'carrier` c';
                        if (version_compare(_PS_VERSION_, '1.5', '<')) {
                            $sql2 .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_lang` cl ON (c.`id_carrier` = cl.`id_carrier` AND cl.`id_lang` = ' . (int)$id_lang . ')';
                            $sql2 .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)' .
                                ($id_zone ? ' LEFT JOIN `' . _DB_PREFIX_ . 'zone` z ON (z.`id_zone` = ' . (int)$id_zone . ')' : '') . '
                            WHERE c.`deleted` = ' . ($delete ? '1' : '0');
                        }
                        else {
                            $sql2 .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_lang` cl ON (c.`id_carrier` = cl.`id_carrier` AND cl.`id_lang` = ' . (int)$id_lang . Shop::addSqlRestrictionOnLang('cl') . ')';
                            $sql2 .= ' LEFT JOIN `' . _DB_PREFIX_ . 'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)' .
                                ($id_zone ? 'LEFT JOIN `' . _DB_PREFIX_ . 'zone` z ON (z.`id_zone` = ' . (int)$id_zone . ')' : '') . '
                    ' . Shop::addSqlAssociation('carrier', 'c') . '
                    WHERE c.`deleted` = ' . ($delete ? '1' : '0');
                        }
                        if ($active) {
                            $sql2 .= ' AND c.`active` = 1 ';
                        }
                        if ($id_zone) {
                            $sql2 .= ' AND cz.`id_zone` = ' . (int)$id_zone . ' AND z.`active` = 1 ';
                        }
                        if ($ids_group) {
                            $sql2 .= ' AND EXISTS (SELECT 1 FROM ' . _DB_PREFIX_ . 'carrier_group
                                    WHERE ' . _DB_PREFIX_ . 'carrier_group.id_carrier = c.id_carrier
                                    AND id_group IN (' . implode(',', array_map('intval', $ids_group)) . ')) ';
                        }
                        $sql2 .= '  AND c.external_module_name = "mbeshipping" AND c.name IN (' . join(',', array_unique($names)) . ') ';
                    }
                }
            }
        }
        else {
            $sql .= ' AND c.external_module_name <> "mbeshipping" ';
        }
        if ($sql != '') {
            $sql .= $sql2;
        }
        $sql .= ' GROUP BY c.`id_carrier`';
        $cache_id = 'Carrier::getCarriers_' . md5($sql);
        if (version_compare(_PS_VERSION_, '1.5', '<')) {
            $carriers = Db::getInstance()->executeS($sql);
        }
        else {
            if (!Cache::isStored($cache_id)) {
                $carriers = Db::getInstance()->executeS($sql);
                Cache::store($cache_id, $carriers);
            }
            else {
                $carriers = Cache::retrieve($cache_id);
            }
        }
        foreach ($carriers as $key => $carrier) {
            if (isset($myCarriers)) {
                foreach ($myCarriers as $t => $m) {
                    if (($m['carrier']->id == $carriers[$key]['id_carrier'])) {
                        $carriers[$key]['price'] = $myCarriers[$t]['price'];
                    }
                }
            }
        }
        return $carriers;
    }
}