<?php

declare(strict_types=1);

namespace KupShop\ProductReservationBundle\Admin;

use KupShop\ProductReservationBundle\Util\ProductReservationUtil;
use Query\Operator;

class ProductReservation extends \Window
{
    protected $tableName = 'product_reservations';
    protected $nameField = 'id';

    public function get_vars()
    {
        $vars = parent::get_vars();

        $vars['body']['types'] = ProductReservationUtil::getReservationTypes();

        return $vars;
    }

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

        if (empty($data['id_variation']) && $this->hasProductVariations((int) $data['id_product'])) {
            $this->returnError(translate('errorVariationNotSelected'));
        }

        return $data;
    }

    private function hasProductVariations(int $productId): bool
    {
        return (bool) sqlQueryBuilder()
            ->select('id')
            ->from('products_variations')
            ->where(Operator::equals(['id_product' => $productId]))
            ->execute()->fetchOne();
    }
}

return ProductReservation::class;
