<?php

namespace KupShop\ProductGiftsBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;

class ProductGiftsTab extends WindowTab
{
    protected $title = 'flapGifts';

    protected $template = 'ProductGiftsTab.tpl';

    public static function getTypes()
    {
        return [
            'products' => 1,
        ];
    }

    public function getLabel()
    {
        return 'Dárky';
    }

    public function getVars($smarty_tpl_vars)
    {
        $product = $smarty_tpl_vars['body']->value['product'] ?? false;
        if ($product) {
            $product->fetchGifts(true);
            foreach ($product->gifts ?: [] as &$gift) {
                $gift->fetchImages('admin');
                $gift->fetchVariations();
                $variations = [];
                if (!empty($gift['variations']['variations'])) {
                    foreach ($gift['variations']['variations'] as $variation) {
                        $selected = false;
                        if ($variation['id'] == $gift['selected_variation']) {
                            $selected = true;
                        }
                        $variations[] = ['label' => $variation['title'], 'value' => $variation['id'], 'selected' => $selected];
                    }
                }
                $gift['variations'] = $variations;
            }
        }

        return $smarty_tpl_vars;
    }

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

        $data = $this->getData();
        $gifts = getVal('gifts', $data, []);

        foreach ($gifts as $id => $gift) {
            $gift['id_product_gift'] = intval($gift['id_product_gift']);
            $gift['id_product'] = $this->getID();
            if (empty($gift['id_variation_gift'])) {
                $gift['id_variation_gift'] = null;
            }
            $this->prepareNull($gift['price']);

            if (!ctype_digit($gift['pieces']) || $gift['pieces'] < 1) {
                $gift['pieces'] = 1;
            }

            if ($this->isDuplicate() && $id > 0) {
                $id = -99;
            }

            if (!empty($gift['delete']) || !$id || $gift['id_product_gift'] <= 0) {
                if ($id > 0) {
                    $this->deleteSQL('products_gifts', $this->filterFields($gift, ['id_product', 'id_product_gift']));
                }

                continue;
            }

            if ($id < 0) {
                try {
                    $this->insertSQL('products_gifts', $gift);
                } catch (\Doctrine\DBAL\DBALException $e) {
                }
            } else {
                $this->updateSQL('products_gifts', $gift, $this->filterFields($gift, ['id_product', 'id_product_gift']));
            }
        }
    }

    public function isVisible()
    {
        if ($this->getAction() != 'add') {
            return parent::isVisible(); // TODO: Change the autogenerated stub
        }
    }
}
