<?php

namespace KupShop\AdminBundle\Util;

use Doctrine\DBAL\Driver\Exception;
use Query\Operator;

class StockInProductOfSupplierService
{
    use \DatabaseCommunication;

    /**
     * @throws \Doctrine\DBAL\Exception
     * @throws Exception
     */
    public function updateOrInsertProductSupplier($product, $stockInData): void
    {
        if ($this->canUpdateOrInsert($product, $stockInData)) {
            $pos_id = $this->findProductOfSupplierId($product, $stockInData);

            if ($pos_id > 0) {
                $this->updateProductSupplier($pos_id, $product['supplier_code']);
            } else {
                $this->insertProductSupplier($product, $stockInData);
            }
        }
    }

    private function canUpdateOrInsert($product, $stockInData): bool
    {
        return !empty($product['id_product']) && $stockInData['id_supplier'];
    }

    /**
     * @throws \Doctrine\DBAL\Exception
     * @throws \Exception|Exception
     */
    private function findProductOfSupplierId($product, $data)
    {
        return sqlQueryBuilder()->select('id')
            ->from('products_of_suppliers')
            ->where(Operator::equalsNullable([
                'id_product' => $product['id_product'],
                'id_variation' => $product['id_variation'],
                'id_supplier' => $data['id_supplier'],
            ]))
            ->execute()
            ->fetchOne();
    }

    private function updateProductSupplier($pos_id, $supplier_code): void
    {
        if ($supplier_code) {
            $this->updateSQL('products_of_suppliers', ['code' => $supplier_code], ['id' => $pos_id]);
        }
    }

    private function insertProductSupplier($product, $data): void
    {
        $prod_allow_empty_supplier_code = (\Settings::getDefault()['prod_allow_empty_supplier_code'] ?? null);
        if (empty($product['supplier_code']) && ($prod_allow_empty_supplier_code != 'Y')) {
            return;
        }

        $pos = [
            'id_product' => $product['id_product'],
            'id_variation' => $product['id_variation'],
            'id_supplier' => $data['id_supplier'],
            'code' => $product['supplier_code'],
        ];
        $this->insertSQL('products_of_suppliers', $pos);
    }
}
