<?php

use Query\Operator;

$main_class = 'ProductsOfSuppliers';

class ProductsOfSuppliers extends Window
{
    protected $tableName = 'products_of_suppliers';
    protected $nameField = 'id';

    protected $defaults = [
        'import_multiplier' => 1,
    ];

    public function get_vars()
    {
        $vars = parent::get_vars();
        $pageVars = getVal('body', $vars);

        $sql = sqlQuery('SELECT id, name FROM '.getTableName('suppliers'));
        $suppliers = ['' => 'Vyber dodavatele'];
        while (($dbRow = sqlFetchAssoc($sql)) !== false) {
            $suppliers[$dbRow['id']] = $dbRow['name'];
        }
        $pageVars['suppliers'] = $suppliers;

        $data = &$pageVars['data'];
        if (!empty($data['id_product'])) {
            $item = sqlFetchAssoc(sqlQuery('SELECT p.title product_title, pv.title variation_title
                FROM '.getTableName('products').' p
                LEFT JOIN '.getTableName('products_variations').' pv ON p.id = pv.id_product
                WHERE p.id = :id_product AND (pv.id IS NULL OR pv.id = :id_variation)', ['id_product' => $data['id_product'], 'id_variation' => $data['id_variation']]));

            $data['product_title'] = $item['product_title'];
            $data['variation_title'] = $item['variation_title'];
        }

        global $dbcfg;
        if ($dbcfg['prod_prefer_price_vat'] != 'N') {
            $product = new Product();
            if ($product->createFromDB($data['id_product'] ?? null)) {
                if (isset($data['price_buy'])) {
                    $data['price_buy'] *= 1 + ($product->vat / 100);
                }

                if (isset($data['price_sell'])) {
                    $data['price_sell'] *= 1 + ($product->vat / 100);
                }
            }
        }

        $vars['body'] = $pageVars;

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        if (!empty($data['last_sync'])) {
            $data['last_sync'] = $this->prepareDateTime($data['last_sync']);
        }

        if (!empty($data['forecasted_delivery_date'])) {
            $data['forecasted_delivery_date'] = $this->prepareDateTime($data['forecasted_delivery_date']);
        }

        if (getVal('Submit')) {
            if (!empty($data['ean'])) {
                $exists = Variations::eanExists(0, $data['ean']);

                if ($exists) {
                    $message = Variations::eanExistsMessage($exists);
                    $this->addHTMLError($message); // EAN {ean} není unikátní. {odkaz na duplicitní produkt}
                    $data['ean'] = '';
                } else {
                    $exists = sqlQueryBuilder()->select('id')->from('products_of_suppliers')->where(\Query\Operator::like(['ean' => $data['ean']]))->execute()->fetchColumn();

                    if ($exists) {
                        $this->addHTMLError("EAN <strong>{$data['ean']}</strong> není unikátní. <a href=\"javascript:nw('productsOfSuppliers', {$exists})\">Zobrazit produkt dodavatele.</a>");
                        $data['ean'] = '';
                    }
                }
            }
        }

        return $data;
    }

    public function handleUpdate()
    {
        $data = $this->getData();
        $this->checkHasVariations($data);
        $this->checkProductSupplierDuplicity($data);
        $this->checkCodeDuplicity($data);

        return parent::handleUpdate();
    }

    public function checkProductSupplierDuplicity($data)
    {
        $qb = $this->getQueryBuilder()
            ->select('id')
            ->from('products_of_suppliers')
            ->where(Operator::equals(['id_supplier' => $data['id_supplier'], 'id_product' => $data['id_product']]));
        if ($data['id_variation']) {
            $qb = $qb->andWhere(Operator::equals(['id_variation' => $data['id_variation']]));
        }
        if ($this->getID()) {
            $qb = $qb->andWhere(Operator::not(Operator::equals(['id' => $this->getID()])));
        }

        if ($qb->execute()->rowCount() > 0) {
            $ErrStr = 'Tento produkt máte již k tomuto dodavateli přiřazený.';
            $this->returnError($ErrStr);
        }
    }

    public function checkCodeDuplicity($data)
    {
        if (findModule('suppliers', 'allow_duplicate_code')) {
            return false;
        }

        $qb = $this->getQueryBuilder()
            ->select('id')
            ->from('products_of_suppliers')
            ->where(Operator::equals(['id_supplier' => $data['id_supplier'], 'code' => $data['code']]));
        if ($this->getID()) {
            $qb = $qb->andWhere(Operator::not(Operator::equals(['id' => $this->getID()])));
        }

        if ($qb->execute()->rowCount() > 0) {
            $ErrStr = 'Kód produktu u tohoto dodavatele je již obsazený.';
            $this->returnError($ErrStr);
        }
    }

    public function checkHasVariations($data): void
    {
        if (!empty($data['id_product'])) {
            $product = new Product($data['id_product']);
            if (empty($data['id_variation']) && $product->hasVariations()) {
                $ErrStr = 'Produkt má varianty ale žádná nebyla vybrána.';
                $this->returnError($ErrStr);
            }
        }
    }
}
