<?php

namespace KupShop\CheckAppBundle\Util;

use KupShop\BalikonosBundle\Exception\BalikonosException;
use KupShop\ReclamationsSuppliersBundle\Exception\InvalidSupplierInfo;
use KupShop\ReclamationsSuppliersBundle\Util\ReclamationsSuppliersUtil;
use Query\Operator;

class ReclamationSupplierCheckoutWorker
{
    private ?ReclamationsSuppliersUtil $reclamationsSuppliersUtil = null;

    /** @var WorkerUtil */
    protected $workerUtil;

    /**
     * @required
     */
    public function setWorkerUtil(WorkerUtil $workerUtil): void
    {
        $this->workerUtil = $workerUtil;
    }

    /**
     * @required
     */
    public function setReturnsUtil(?ReclamationsSuppliersUtil $reclamationsSuppliersUtil = null)
    {
        $this->reclamationsSuppliersUtil = $reclamationsSuppliersUtil;
    }

    public function getReclamationSupplierCheckData($idReclamationSupplier)
    {
        $data = [];
        foreach ($this->reclamationsSuppliersUtil->getItems($idReclamationSupplier) as $item) {
            $product = new \Product();
            $product->createFromDB($item['product_id']);

            $additionalData = $this->getAdditionalData($item['product_id'], $item['variation_id']);

            $productData = sqlQueryBuilder()
                ->select('COALESCE(pv.ean, p.ean) ean, COALESCE(pv.code, p.code) code, p.title, pv.title variation_title')
                ->from('products', 'p')
                ->joinVariationsOnProducts()
                ->where(Operator::equalsNullable([
                    'p.id' => $item['product_id'],
                    'pv.id' => $item['variation_id'] ?: null,
                ]))
                ->addSelect(\Query\Product::withProductPhotoId(true))
                ->execute()->fetch();

            $data[] = [
                'id' => $item['id'],
                'title' => $productData['title'].($productData['variation_title'] ? " ({$productData['variation_title']})" : ''),
                'quantity' => (int) $item['pieces'],
                'code' => ($productData['code'] ?? ''),
                'ean' => formatEAN($productData['ean']),
                'id_product' => $item['product_id'],
                'id_variation' => $item['variation_id'],
                'note' => $product->note_ ?? '',
                'serial_number_require' => $additionalData['serial_number_require'] ?? '',
                'batch_number_require' => $additionalData['batch_number_require'] ?? '',
                'batches_numbers' => $additionalData['batches_numbers'] ?? [],
                'image' => getImage($productData['id_photo'], null, null, 3)['src'] ?? '',
                'positions' => $additionalData['positions'] ?? '',
                'supplier_eans' => explode(';', $additionalData['supplier_eans'] ?? ''),
                'supplier_codes' => explode(';', $additionalData['supplier_codes'] ?? ''),
                'figure' => $product->visible,
            ];
        }

        usort($data, function ($a, $b) {
            return empty($b['ean']) <=> empty($a['ean']);
        });

        $index = 0;
        foreach ($data as &$item) {
            $item['index'] = $index++;
        }

        return $data;
    }

    public function checkoutReclamationSupplier($reclamationSupplierId, $items): array
    {
        if ($error = $this->workerUtil->checkIfAnyItemChecked($items)) {
            return [
                'result' => false,
                'keepState' => true,
                'message' => $error,
            ];
        }

        try {
            $this->reclamationsSuppliersUtil->changeStatus($reclamationSupplierId, 1);
        } catch (InvalidSupplierInfo|BalikonosException $e) {
            return [
                'result' => false,
                'keepState' => true,
                'message' => $e->getMessage(),
            ];
        }

        sqlQueryBuilder()->update('reclamations_suppliers')
            ->set('data', "JSON_SET(IF(JSON_VALID(data), data, JSON_OBJECT()), '$.checkout_control', true)")
            ->where(Operator::equals(['id' => $reclamationSupplierId]))
            ->execute();

        $this->reclamationsSuppliersUtil->logHistory($reclamationSupplierId, 'Proběhla výstupní kontrola reklamace dodavateli.', 1);

        return [
            'result' => true,
            'message' => 'Reklamace dodavateli zkontrolována',
        ];
    }

    protected function getAdditionalData($id_product, $id_variation)
    {
        return $this->workerUtil->getProductAdditionalData($id_product, $id_variation);
    }
}
