<?php

declare(strict_types=1);

namespace KupShop\PohodaBundle\Utils\Tools;

use Query\Operator;

trait CouponHelper
{
    protected array $discounts;

    protected function processCoupon($product): bool
    {
        $productCode = (string) $product->PRODUCT_CODE ?? '';

        if ($productCode == '') {
            return false;
        }

        $couponRow = sqlQueryBuilder()
            ->select('*')
            ->from('discounts_coupons')
            ->andWhere(Operator::like(['code' => $productCode]))
            ->execute()->fetchAssociative();

        if ($couponRow) {
            $inStore = (int) $product->STORE;
            $odbyt = (string) $product->ODBYT == 'true';
            $fields = null;

            // pomocné načtení objednávky
            if ($inStore == 1 && $couponRow['id_order_purchased']) {
                $order = new \Order();
                $order->createFromDB($couponRow['id_order_purchased']);
            }

            if ($inStore > 0 && $odbyt && !$couponRow['id_order_purchased']) {
                // Nemelo by byt potreba, protoze vsechny kupony vzniknou na e-shopu, tak aktivni by mely bejt hned
            } elseif (($inStore == 0 && $odbyt && !$couponRow['id_order_purchased'])
                || ($inStore == 1 && ($order ?? false) && $order->isPaid())
            ) {
                // pokud není skladem, zároveň je odbyt, tak má jit kupon k uplatnění, protože byl koupenej
                $nowDateTime = new \DateTime();

                $fields = [
                    'date_from' => $this->prepareDateTime($nowDateTime),
                ];
            } elseif ($inStore == 1 && !$odbyt) {
                // pokud není skladem a zároveň nemá odbyt, tak už je uplatněný
                $fields = [
                    'used' => 'Y',
                ];
            }

            if ($fields) {
                sqlQueryBuilder()
                    ->update('discounts_coupons')
                    ->directValues($fields)
                    ->andWhere(Operator::like(['code' => $productCode]))
                    ->execute();
            }

            return true;
        }

        return false;
    }

    public function loadCaches()
    {
        parent::loadCaches();

        if (findModule(\Modules::POHODA, \Modules::SUB_SYNC_COUPONS)) {
            $this->discounts = sqlFetchAll(sqlQueryBuilder()
                ->select('id, condition_value')
                ->from('discounts')
                ->where(Operator::like(['condition_type' => 'generate_coupon']))
                ->execute(), ['condition_value' => 'id']);
        }
    }

    public function tryFindCoupon($product, $item): ?bool
    {
        // Projdou se všechny existující kupony
        foreach ($this->discounts as $prefix => $id) {
            if ($prefix != '' && strpos($product['product_code'] ?? '', $prefix) !== false) {
                // Pokud se najde, zprocesuje se
                return $this->processCoupon($item);
            }
        }

        return null;
    }
}
