<?php

declare(strict_types=1);

namespace External\HannahBundle\Maileon\Export;

use KupShop\OrderingBundle\OrderList\OrderList;
use KupShop\OrderingBundle\Util\Order\OrderInfo;
use Query\Operator;
use Query\QueryBuilder;

class OrderContactExport extends AbstractExport
{
    protected static $type = 'order_contact';
    protected static $uploadDirectory = '/';
    protected static $uploadFilename = 'order_contact.csv';

    /** @required */
    public OrderList $orderList;

    protected function getHeader(): array
    {
        return [
            'cislo_objednavky',
            'email',
            'name',
            'surname',
            'firm',
            'ico',
            'phone',
            'street',
            'city',
            'zip',
        ];
    }

    protected function getData(string $language, ?\DateTime $lastSync): iterable
    {
        $orderList = clone $this->orderList;

        $orders = $orderList
            ->andSpec(function (QueryBuilder $qb) use ($language) {
                return Operator::andX(
                    // filtruju podle jazyka, protoze delam export objednavek pro kazdy jazyk zvlast
                    Operator::equals(['o.id_language' => $language]),
                    // beru objednavky za poslednich 48 hodin
                    'o.date_created > (NOW() - INTERVAL 48 HOUR)'
                );
            })
            ->andSpec(function (QueryBuilder $qb) {
                return Operator::not(Operator::equals(['o.source' => OrderInfo::ORDER_SOURCE_DROPSHIP]));
            })
            ->limit(1000)
            ->orderBy('o.id', 'DESC')
            ->fetchItems()
            ->getOrders();

        /** @var \Order $order */
        foreach ($orders as $order) {
            yield [
                'cislo_objednavky' => $order->order_no,
                'email' => $order->invoice_email,
                'name' => $order->invoice_name,
                'surname' => $order->invoice_surname,
                'firm' => $order->invoice_firm,
                'ico' => $order->invoice_ico,
                'phone' => $order->invoice_phone,
                'street' => $order->invoice_street,
                'city' => $order->invoice_city,
                'zip' => $order->invoice_zip,
            ];
        }
    }
}
