<?php

namespace KupShop\OrderingBundle;

use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\OrderingBundle\Util\Order\OrderInfo;
use Query\Operator;

class OrdersList
{
    protected $divide = 20;

    protected $noItems;
    protected $specs = [];

    protected $orderInfo;

    protected $contextManager;

    protected bool $activeUserSpec = true;

    public function __construct(OrderInfo $orderInfo, ContextManager $contextManager)
    {
        $this->orderInfo = $orderInfo;
        $this->contextManager = $contextManager;
    }

    public function getOrders()
    {
        $dbcfg = \Settings::getDefault();

        $data = [];

        $qb = sqlQueryBuilder()
            ->select('SQL_CALC_FOUND_ROWS o.id', 'o.order_no', 'o.status', 'o.status_storno', 'o.delivery_country',
                'DATE_FORMAT(o.date_created, "'.$dbcfg['date_format'].' '.$dbcfg['time_format'].'") AS datec',
                'o.total_price', 'o.note_admin', 'o.flags', 'o.date_handle', 'o.source');

        if (findModule('currencies')) {
            $qb->addSelect('o.currency, o.id_language');
        }

        $qb->from(getTableName('orders'), 'o')
            ->orderBy('o.date_created', 'DESC');

        if ($this->activeUserSpec) {
            $id_user = Contexts::get(UserContext::class)->getActiveId();
            $qb->andWhere('id_user=:id_user')->setParameter('id_user', $id_user);
        }

        $qb->andWhere(Operator::andX($this->specs));

        $sql = $qb->execute();

        $this->noItems = (int) sqlFetchAssoc(sqlQuery('SELECT FOUND_ROWS() as total_count'))['total_count'];

        foreach ($sql as $row) {
            $IDo = $row['id'];

            if (findModule(\Modules::COMPONENTS)) {
                $order = new \Order();
                $order->createFromDB($IDo);
            } else {
                $order = new \Order($IDo);
                $order->createFromArray($row);
            }

            $this->contextManager->activateOrder($order, function () use (&$order_arr, $row, $order, $IDo) {
                $totalPriceArray = formatPrice($row['total_price'], 0);
                $order_arr = [
                    'id' => $IDo,
                    'number' => $row['order_no'],
                    'status' => $this->orderInfo->getOrderStatus($row['status']),
                    'price' => printPrice($totalPriceArray, ['dealerdiscount' => false]),
                    'price_array' => $totalPriceArray,
                    'date' => $row['datec'],
                    'editable' => $order->isEditable(),
                    'orderObj' => $order,
                ];

                if ($row['status_storno'] == 1) {
                    $order_arr['status'] = $this->orderInfo->getOrderStatus('storno');
                }
            });

            $data[] = $order_arr;
        }

        return $data;
    }

    public function andSpec(?callable $spec = null)
    {
        $this->specs[] = $spec;
    }

    public function createPager()
    {
        $pager = new \Pager();
        $pager->setOnPage($this->divide);
        $pager->setPageNumber((int) getVal('page', null, 1));

        return $pager;
    }

    public function getDivide(): int
    {
        return $this->divide;
    }

    public function setDivide(int $divide)
    {
        $this->divide = $divide;
    }

    public function getActiveUserSpec(): bool
    {
        return $this->activeUserSpec;
    }

    public function setActiveUserSpec(bool $activeUserSpec)
    {
        $this->activeUserSpec = $activeUserSpec;
    }

    /**
     * @return int
     */
    public function getNoItems()
    {
        return $this->noItems;
    }
}
