<?php
/**
 * 2016 Eengine Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

class InpostDispatchPoints extends Module
{
    public $name = 'inpost';
    const FILE = 'inpostdispatchpoints';
    public function generateTableDispatchPoint()
    {

        $this->fields_list = array(
            'name' => array(
                'title' => $this->l('Name', self::FILE),
                'type' => 'text',
            ),
            'country_name' => array(
                'title' => $this->l('Country', self::FILE)
            ),
            'postcode' => array(
                'title' => $this->l('Postal code', self::FILE),
                'type' => 'text',
                'class' => 'postcode_dispatch',
            ),
            'city' => array(
                'title' => $this->l('City', self::FILE),
                'type' => 'text',
            ),
            'street' => array(
                'title' => $this->l('Street', self::FILE),
                'type' => 'text',
            ),

            'phone' => array(
                'title' => $this->l('Phone', self::FILE),
                'type' => 'text',

            ),
            'email' => array(
                'title' => $this->l('Email', self::FILE),
                'type' => 'text',
            ),
            // 'comments' => array(
            //     'title' => $this->l('Comments', self::FILE),
            //     'type' => 'text',
            // ),
            'office_hours' => array(
                'title' => $this->l('Open hours', self::FILE),
                'type' => 'text',
            ),
            'dispatch_status' => array(
                'title' => $this->l('Is active?', self::FILE),
                'type' => 'bool',
                'active' => 'dispatch_status',
            ),
        );

        $helper = new HelperList();

        $helper->actions = array('edit', 'delete');
        $helper->orderBy = Tools::getValue('inpostDispatchOrderby');
        $helper->orderWay = Tools::strtoupper(Tools::getValue('inpostDispatchOrderway'));

        $helper->identifier = 'id';
        $helper->show_toolbar = false;
        $helper->title = 'Lista punktów';
        $helper->table = $this->name.'Dispatch';
        $helper->shopLinkType = '';
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name.'&dispatch_points';

        $helper->bulk_actions = array(
            '' => array('text' => ''),
        );

        $this->resetFilters();
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            $page = (int)Tools::getValue('submitFilterDispatch');
        } else {
            $page = (int)Tools::getValue('submitFilterinpostDispatch');
        }

        if (!$page) {
            $page = 1;
        }

        $pagination = (int)Tools::getValue('inpostDispatch_pagination', 50);

        $start = ($pagination * $page) - $pagination;

        $content = $this->getListContent(
            $helper->orderBy,
            $helper->orderWay,
            $_POST,
            $pagination,
            $start
        );

        $helper->listTotal= 1;

        return $helper->generateList($content, $this->fields_list);
    }

    public function resetFilters()
    {

        if (Tools::isSubmit('submitResetinpostDispatch')) {
            $_POST['inpostDispatchFilter_name'] = '';
            $_POST['inpostDispatchFilter_country_name'] = '';
            $_POST['inpostDispatchFilter_postcode'] = '';
            $_POST['inpostDispatchFilter_city'] = '';
            $_POST['inpostDispatchFilter_street'] = '';
            $_POST['inpostDispatchFilter_building_no'] = '';
            $_POST['inpostDispatchFilter_flat_no'] = '';
            $_POST['inpostDispatchFilter_phone'] = '';
            $_POST['inpostDispatchFilter_email'] = '';
            $_POST['inpostDispatchFilter_comments'] = '';
            $_POST['inpostDispatchFilter_office_hours'] = '';
            $_POST['inpostDispatchFilter_service'] = '';
        }
    }
    public function getListContent($orderBy, $orderWay, $data, $limit, $start = 0)
    {

        $sql = "SELECT idp.*, icl.name as country_name FROM "._DB_PREFIX_."inpost_dispatch_points idp
                    LEFT JOIN "._DB_PREFIX_."country_lang icl on idp.country=icl.id_country
                    WHERE id_lang=".Context::getContext()->language->id;
        $filtersDispatchPoints = $this->filterDispatchPoint($data);
        if ($filtersDispatchPoints) {
            $sql .= ' AND '.$filtersDispatchPoints;
        }

        if ($orderBy) {
            $sql.= ' order by '.$orderBy;
        }
        if ($orderWay) {
            $sql.= ' '.$orderWay;
        }
        if ($limit) {
            $sql .= ' LIMIT '.$limit;
        }
        if ($start) {
            $sql .= ' OFFSET '.$start;
        }

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

        foreach ($dispatchPoints as &$singleDispatch) {
            $singleDispatch['dispatch_status'] = 0;
            $singleDispatch['phone'] = $singleDispatch['phone_no'];
            if ($singleDispatch['inpost_service'] == 'CROSSBORDER') {
                $singleDispatch['inpost_service'] = 'Crossborder';
            }
            if ($singleDispatch['inpost_service'] == 'PARCEL_LOCKER') {
                $singleDispatch['inpost_service'] = 'Parcel locker';
            }
            if (strtoupper($singleDispatch['status']) === 'ACTIVE') {
                $singleDispatch['dispatch_status'] = 1;
            }

            $singleDispatch['street'] = (string)$singleDispatch['street'].' '.(string)$singleDispatch['building_no'] . ' ' . (string)$singleDispatch['flat_no'];
        }

        return $dispatchPoints;


    }

    public function filterDispatchPoint()
    {

        $filter = [];
        if (Tools::isSubmit('submitFilterinpostDispatch')) {
            if (Tools::getValue('inpostDispatchFilter_name')) {
                $filter[] = "idp.name like '%".Tools::getValue('inpostDispatchFilter_name')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_country_name')) {
                $filter[] = " icl.name like '%".Tools::getValue('inpostDispatchFilter_country_name')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_postcode')) {
                $filter[] = "postcode like '%".Tools::getValue('inpostDispatchFilter_postcode')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_city')) {
                $filter[] = "city like '%".Tools::getValue('inpostDispatchFilter_city')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_street')) {
                $filter[] = "street like '%".Tools::getValue('inpostDispatchFilter_street')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_building_no')) {
                $filter[] = "building_no like '".Tools::getValue('inpostDispatchFilter_building_no')."'";
            }
            if (Tools::getValue('inpostDispatchFilter_flat_no')) {
                $filter[] = "flat_no like '".Tools::getValue('inpostDispatchFilter_flat_no')."'";
            }
            if (Tools::getValue('inpostDispatchFilter_phone')) {
                $filter[] = "phone_no like '".Tools::getValue('inpostDispatchFilter_phone')."'";
            }
            if (Tools::getValue('inpostDispatchFilter_email')) {
                $filter[] = "email like '".Tools::getValue('inpostDispatchFilter_email')."'";
            }
            if (Tools::getValue('inpostDispatchFilter_comments')) {
                $filter[] = "comments like '%".Tools::getValue('inpostDispatchFilter_comments')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_office_hours')) {
                $filter[] = "office_hours like '%".Tools::getValue('inpostDispatchFilter_office_hours')."%'";
            }
            if (Tools::getValue('inpostDispatchFilter_service')) {
                $filter[] = 'inpost_service = "'.Tools::getValue('inpostDispatchFilter_service').'"';
            }
            if (Tools::getValue('inpostDispatchFilter_dispatch_status') == '') {
            }
            if (Tools::getValue('inpostDispatchFilter_dispatch_status') === "0") {
                $filter[] = 'status != "ACTIVE"';
            }

            if (Tools::getValue('inpostDispatchFilter_dispatch_status') === "1") {
                $filter[] = 'status = "ACTIVE"';
            }


        }

        if ($filter) {
            return implode(' AND ', $filter);
        }
        return false;

    }

    public function renderDispatchPointActions()
    {
        if (version_compare(_PS_VERSION_, '1.6', '<')) {
            return $this->context->smarty->fetch(INPOST_TPL_DIR.'admin/1.5/dispatch_points_actions.tpl');
        }

        return $this->context->smarty->fetch(INPOST_TPL_DIR.'admin/dispatch_points_actions.tpl');
    }

    public static function deleteDispatchPoints()
    {
        $api = new InpostConnector();
        $toRemove = Tools::getValue('inpostDispatchBox');
        if (!$toRemove) {
            $toRemove = [Tools::getValue('id')];
        }

        if ($toRemove) {
            foreach ($toRemove as $singleToRemove) {
                $dispatchToRemove = self::getDispatchPointById($singleToRemove);

                $response = $api->deleteDispatchPoint($dispatchToRemove['href']);

                if (!is_array($response)) {
                    self::deleteDispatchPointFromDatabase($singleToRemove);
                } else {
                    return $response;
                }
            }
        }

    }

    public static function getDispatchPointById($id)
    {
        if ($id) {
            return Db::getInstance()->getRow("SELECT * FROM "._DB_PREFIX_."inpost_dispatch_points WHERE id = {$id}");
        }
        return false;
    }


    public static function deleteDispatchPointFromDatabase($id)
    {
        return Db::getInstance()->delete('inpost_dispatch_points', 'id='.$id);
    }

    public static function getDispatchPointForCourierOrder()
    {
        return Db::getInstance()->executeS('SELECT id, href, `name`, `status`, x_border_id
                                            FROM '._DB_PREFIX_.'inpost_dispatch_points');
    }

    public static function getDispatchPoints($activeOnly = true)
	{
		$where = '';

		if($activeOnly) {
			$where = "WHERE status = 'ACTIVE'";
		}

		$sql = '
			SELECT 
				id, href, `name`, `status`, x_border_id
			FROM 
				'._DB_PREFIX_.'inpost_dispatch_points
			'. $where .' ORDER BY name ASC';

		return Db::getInstance()->executeS($sql);
	}

	public static function isActive()
	{
		return (((int)Configuration::get('INPOST_AVAILABLE_SERVICES_CROSSBORDER')
			|| ((int)Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS') === 1
				|| (int)Configuration::get('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD') === 1)
			|| ((int)Tools::getValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS') === 1
				|| (int)Tools::getValue('INPOST_AVAILABLE_SERVICES_PARCELS_LOCKERS_COD') === 1)
			||  Tools::isSubmit('INPOST_AVAILABLE_SERVICES_CROSSBORDER')
		) && (int)Configuration::get('INPOST_COUNTRY') === 1);
	}
}
