<?php

declare(strict_types=1);

namespace External\PompoBundle\View;

use Query\Operator;

class BonusProgramExchangeView extends \KupShop\BonusProgramBundle\View\Exchange\BonusProgramExchangeView
{
    protected function getExchangeList(): array
    {
        $data = parent::getExchangeList();

        // Odfiltruju partnerske slevy, ktere uz nemaji dostupne zadne kupony
        foreach ($data as $key => $item) {
            if (($item['partner'] ?? 'N') === 'Y') {
                if (!$this->hasAvailablePartnerCoupons((int) $item['id_discount'])) {
                    unset($data[$key]);
                }
            }
        }

        return $data;
    }

    private function hasAvailablePartnerCoupons(int $discountId): bool
    {
        $count = sqlQueryBuilder()
            ->select('COUNT(*)')
            ->from('discounts_coupons')
            ->andWhere(Operator::equals(['id_discount' => $discountId]))
            ->andWhere('id_user IS NULL AND id_order_purchased IS NULL AND id_order_used IS NULL')
            ->andWhere(Operator::equals(['used' => 'N']))
            ->andWhere('date_from <= NOW() OR date_from IS NULL')
            ->andWhere('date_to >= NOW() OR date_to IS NULL')
            ->execute()->fetchOne();

        if ($count > 0) {
            return true;
        }

        return false;
    }
}
