<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonShippingCommon\Classes\Mail;

use Doctrine\ORM\Query;
use Enlight_Components_Db_Adapter_Pdo_Mysql;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Order\Order;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;

/**
 * Class ReturnLabelMailContextHelper
 */
class ReturnLabelMailContextHelper
{
    /**
     * @param string $emailTemplateName
     * @param Enlight_Components_Db_Adapter_Pdo_Mysql $pdo
     */
    public static function updateTemplateToDefaultContextValue(
        $emailTemplateName,
        Enlight_Components_Db_Adapter_Pdo_Mysql $pdo
    ) {
        $pdo->query(
            'UPDATE s_core_config_mails 
                            SET context = :context
                            WHERE name = :emailTemplateName',
            array(
                'context' => self::getDefaultReturnLabelMailContextValue(),
                'emailTemplateName' => $emailTemplateName
            )
        );
    }

    /**
     * @param Order $order
     * @param ModelManager $entityManager
     * @return array
     */
    public static function getOrderAsArray(Order $order, ModelManager $entityManager)
    {
        $queryBuilder = $entityManager->createQueryBuilder();
        // We need to retrieve the customer this way because then it is not cached and will return null if
        // it is not found.
        $customer = $entityManager->getRepository(
            'Shopware\Models\Customer\Customer'
        )->findOneBy(array('id' => $order->getCustomer()->getId()));

        $fields = array(
            'o.number as orderNumber',
            'o.transactionId as transactionId',
            'o.orderTime as orderTime',
            'o.dispatchId as dispatchId',
            'o.trackingCode as trackingCode',
            'billing.street as userStreet',
            'billing.city as userCity',
            'billing.company as userCompany',
            'billing.department as userDepartment',
            'billing.countryId as userCountryId',
            'shipping.salutation as shippingSalutation',
            'shipping.firstName as shippingFirstName',
            'shipping.lastName as shippingLastName',
            'shipping.street as shippingStreet',
            'shipping.zipCode as shippingZipCode',
            'shipping.city as shippingCity',
            'shipping.company as shippingCompany',
            'shipping.department as shippingDepartment',
            'shippingCountry.iso as shippingCountryIso',
            'payment.name as paymentName',
            'payment.description as paymentDescription',
        );
        if ($customer !== null) {
            $fields[] = 'customer.email as customerEmail';
            if (ViisonCommonUtil::assertMinimumShopwareVersion('5.2')) {
                $fields[] = 'billing.zipcode as userZipCode';
            } else {
                $fields[] = 'billing.zipCode as userZipCode';
            }
        }

        $queryBuilder
            ->select($fields)
            ->from('Shopware\Models\Order\Order', 'o')
            ->leftJoin('o.payment', 'payment')
            ->join('o.shipping', 'shipping')
            ->join('shipping.country', 'shippingCountry')
            ->where('o.id = :orderid')
            ->setParameter('orderid', $order->getId());

        if ($customer !== null) {
            $queryBuilder->join('o.customer', 'customer');
            if (ViisonCommonUtil::assertMinimumShopwareVersion('5.2')) {
                $queryBuilder->join('customer.defaultBillingAddress', 'billing');
            } else {
                $queryBuilder->join('customer.billing', 'billing');
            }
        } else {
            $queryBuilder->join('o.billing', 'billing');
        }

        return $queryBuilder->getQuery()->getSingleResult(Query::HYDRATE_ARRAY);
    }

    /**
     * @param Order $order
     * @param ModelManager $entityManager
     * @return array
     */
    public static function getOrderDetailsWithAttributesAsArray(Order $order, ModelManager $entityManager)
    {
        $queryBuilder = $entityManager->createQueryBuilder();
        $context = $queryBuilder
            ->select(
                'orderDetail',
                'orderDetailAttribute'
            )
            ->from('Shopware\Models\Order\Detail', 'orderDetail')
            ->join('orderDetail.attribute', 'orderDetailAttribute')
            ->where('orderDetail.orderId = :orderId')
            ->setParameter('orderId', $order->getId())
            ->getQuery()
            ->getResult(Query::HYDRATE_ARRAY);

        return $context;
    }

    /**
     * @return string
     */
    protected static function getDefaultReturnLabelMailContextValue()
    {
        return 'a:27:{s:11:"orderNumber";s:5:"20005";s:13:"transactionId";s:0:"";s:9:"orderTime";s:10:"10.10.2017";s:10:"dispatchId";i:9;' .
            's:12:"trackingCode";s:0:"";s:13:"customerEmail";s:17:"mustermann@b2b.de";s:10:"userStreet";s:11:"Musterweg 1";s:11:"userZipCode";' .
            's:5:"55555";s:8:"userCity";s:11:"Musterstadt";s:11:"userCompany";s:3:"B2B";s:14:"userDepartment";s:7:"Einkauf";s:18:"shippingSalutation";' .
            's:2:"mr";s:17:"shippingFirstName";s:8:"Händler";s:16:"shippingLastName";s:18:"Kundengruppe-Netto";s:14:"shippingStreet";s:11:"Musterweg 1";s:15:"shippingZipCode";' .
            's:5:"00000";s:12:"shippingCity";s:11:"Musterstadt";s:15:"shippingCompany";s:3:"B2B";s:18:"shippingDepartment";' .
            's:7:"Einkauf";s:18:"shippingCountryIso";s:2:"DE";s:11:"paymentName";s:7:"invoice";s:18:"paymentDescription";s:8:"Rechnung";s:14:"userSalutation";s:2:"mr";' .
            's:13:"userFirstName";s:8:"Händler";s:12:"userLastName";s:18:"Kundengruppe-Netto";s:14:"userCountryIso";s:2:"DE";s:12:"orderDetails";a:3:{i:0;a:21:{s:2:"id";i:213;' .
            's:7:"orderId";i:64;s:9:"articleId";i:2;s:5:"taxId";i:1;s:7:"taxRate";i:19;s:8:"statusId";i:0;s:6:"number";s:5:"20005";s:13:"articleNumber";s:9:"SW10002.3";s:5:"price";d:16.797999999999998;' .
            's:8:"quantity";i:1;s:11:"articleName";s:39:"Münsterländer Lagerkorn 32% 0,5 Liter";s:7:"shipped";i:0;s:12:"shippedGroup";i:0;s:11:"releaseDate";N;s:4:"mode";i:0;s:10:"esdArticle";i:0;s:6:"config";' .
            's:0:"";s:3:"ean";s:0:"";s:4:"unit";s:5:"Liter";s:8:"packUnit";s:10:"Flasche(n)";s:9:"attribute";a:12:{s:2:"id";i:26;s:13:"orderDetailId";i:213;s:10:"attribute1";s:0:"";s:10:"attribute2";N;s:10:"attribute3";N;' .
            's:10:"attribute4";N;s:10:"attribute5";N;s:10:"attribute6";N;s:22:"viisonCanceledQuantity";i:0;s:20:"viisonPickedQuantity";i:1;s:35:"viisonAdditionalRequiredInformation";N;s:33:"viisonBinLocationPickedQuantities";' .
            's:40:"[{"binLocationId":1,"pickedQuantity":1}]";}}i:1;a:21:{s:2:"id";i:214;s:7:"orderId";i:64;s:9:"articleId";i:0;s:5:"taxId";i:0;s:7:"taxRate";i:19;s:8:"statusId";i:0;s:6:"number";s:5:"20005";s:13:"articleNumber";' .
            's:16:"SHIPPINGDISCOUNT";s:5:"price";i:-2;s:8:"quantity";i:1;s:11:"articleName";s:15:"Warenkorbrabatt";s:7:"shipped";i:0;s:12:"shippedGroup";i:0;s:11:"releaseDate";N;s:4:"mode";i:4;s:10:"esdArticle";i:0;s:6:"config";s:0:"";' .
            's:3:"ean";s:0:"";s:4:"unit";s:0:"";s:8:"packUnit";s:0:"";s:9:"attribute";a:12:{s:2:"id";i:27;s:13:"orderDetailId";i:214;s:10:"attribute1";N;s:10:"attribute2";N;s:10:"attribute3";N;s:10:"attribute4";N;s:10:"attribute5";N;' .
            's:10:"attribute6";N;s:22:"viisonCanceledQuantity";i:0;s:20:"viisonPickedQuantity";i:0;s:35:"viisonAdditionalRequiredInformation";N;s:33:"viisonBinLocationPickedQuantities";N;}}i:2;a:21:{s:2:"id";i:215;s:7:"orderId";i:64;' .
            's:9:"articleId";i:0;s:5:"taxId";i:0;s:7:"taxRate";i:19;s:8:"statusId";i:0;s:6:"number";s:5:"20005";s:13:"articleNumber";s:19:"sw-payment-absolute";s:5:"price";i:5;s:8:"quantity";i:1;s:11:"articleName";' .
            's:25:"Zuschlag für Zahlungsart";s:7:"shipped";i:0;s:12:"shippedGroup";i:0;s:11:"releaseDate";N;s:4:"mode";i:4;s:10:"esdArticle";i:0;s:6:"config";s:0:"";s:3:"ean";s:0:"";s:4:"unit";s:0:"";s:8:"packUnit";s:0:"";' .
            's:9:"attribute";a:12:{s:2:"id";i:28;s:13:"orderDetailId";i:215;s:10:"attribute1";N;s:10:"attribute2";N;s:10:"attribute3";N;s:10:"attribute4";N;s:10:"attribute5";N;s:10:"attribute6";N;s:22:"viisonCanceledQuantity";i:0;' .
            's:20:"viisonPickedQuantity";i:0;s:35:"viisonAdditionalRequiredInformation";N;s:33:"viisonBinLocationPickedQuantities";N;}}}}';
    }
}
