<?php

namespace Shop\Infrastructure\Models\Customer;

use Propel\Runtime\ActiveQuery\BaseModelCriteria;
use Propel\Runtime\ActiveQuery\ModelJoin;
use Propel\Runtime\Propel;
use Shop\Domain\Customer\Contracts\CustomerEntityInterface;
use Shop\Infrastructure\Models\Customer\Base\Customer as BaseCustomer;
use Shop\Infrastructure\Models\Customer\Map\CustomerTableMap;
use Shop\Infrastructure\Models\Product\Product;
use Shop\Infrastructure\Models\Provider\Provider;
use Shop\Infrastructure\Models\Shop\Shop;
use Shop\Infrastructure\Models\Shop\ShopQuery;

/**
 * Skeleton subclass for representing a row from the 'shop_customer' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */
class Customer extends BaseCustomer implements #\Shop\Contracts\CustomerComplexInterface,
    #\Shop\Contracts\CustomerAccessPricesInterface,
    CustomerEntityInterface
{

    /**
     * Код созданный при регистрации
     * @var type
     */
    protected $registerCode;

    protected $access = false;

    protected $accessPrices = [];

    /**
     * @return array
     */
    public function getAccessPrices(): array
    {
        return $this->accessPrices;
    }

    /**
     * @param array $ids
     * @return Customer
     *
     */
    public function setAccessPrices(array $ids): Customer
    {
        $this->accessPrices = $ids;
        return $this;
    }

    /**
     * @param int $contractorGroupId
     * @return Shop
     */
    public function getStockIfContractor(int $contractorGroupId): Shop
    {
        if ($this->getGroupId() !== $contractorGroupId) {
            throw new \RuntimeException('not contractor');
        }

        $stock = ShopQuery::create()->filterByContractorId($this->getId())->findOne();

        return $stock;
    }


    protected $isProvider = false;
    protected $isStock = false;

    /**
     * @return bool
     */
    public function isProvider(): bool
    {
        return $this->isProvider;
    }

    /**
     * @return bool
     */
    public function isStock(): bool
    {
        return $this->isStock;
    }

    /**
     * @deprecated
     * @todo является ли поставщик точкой, избавится от группы настройик должны прилететь извне
     * @param int $providerGroupId
     * @return Provider
     */
    public function getStockIfProvider(int $providerGroupId): Provider
    {
        if ($this->getGroupId() !== $providerGroupId) {
            throw new \RuntimeException('not provider');
        }
    }


    /**
     * Доступ к прайс-листам клиента
     * @todo Удалить костыль перевести на настройки
     * @return array
     */
    public function getAccessPriceListScheetIds(): array
    {
        //dump($this->access);
        if ($this->access !== false) {
            return $this->access;
        }

        if ($this->accessPrices) {
            return $this->accessPrices;
        }


        $con = Propel::getConnection(Propel::DEFAULT_NAME);
        $query = "SELECT
  `shop_price_access`.`id`,
  `shop_price_access`.`customer_group_id`,
  `shop_price_access`.`shop_id`,
  `shop_price_access`.`price_scheet_id`,
  `shop_price_access`.`customer_id`,
 sps.id AS scheet_id
FROM `shop_price_access`

    INNER JOIN shop_pricelist_sheets sps
    ON sps.id LIKE shop_price_access.price_scheet_id
  INNER JOIN shop_pricelist_files spf
    ON sps.pricelist_file_id = spf.id
  INNER JOIN shop_providers sp
    ON spf.provider_id = sp.id AND sp.shop_id = '" . $this->getManager()->getShopId() . "'

WHERE (('" . $this->getGroupId() . "' LIKE `customer_group_id`
AND '" . $this->getManager()->getShopId() . "' LIKE `shop_price_access`.`shop_id`)
AND '" . $this->getId() . "' LIKE `customer_id`)
ORDER BY `shop_price_access`.`customer_id` DESC,
  `shop_price_access`.`customer_group_id` DESC,
  `shop_price_access`.`shop_id` DESC 
  ";


        $stmt = $con->prepare($query);
        $prices = [];
        if ($stmt->execute()) {
            $res = $stmt->fetchAll();
            foreach ($res as $r) {
                $prices[] = $r["scheet_id"];
            }
        }

        $this->accessPrices = $prices;


        return $prices;
    }

    /**
     *
     * @return string
     */
    function getRegisterCode(): string
    {
        return $this->registerCode;
    }

    /**
     *
     * @param string $registerCode
     * @return $this
     */
    function setRegisterCode(string $registerCode)
    {
        $this->registerCode = $registerCode;
        return $this;
    }

    /**
     * Разрешена ли отправка на email
     * @return bool
     */
    public function isNotifyEmail(): bool
    {

        if (strpos($this->getNotifyType(), "email") !== false) {
            return true;
        }

        return false;
    }

    /**
     * Разрешена ли отправка на sms
     * @return bool
     */
    public function isNotifySms(): bool
    {

        if (strpos($this->getNotifyType(), "sms") !== false) {
            return true;
        }

        return false;
    }

    /**
     * Полный адресс
     * @return string
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function getFullAddress(): string
    {

        $city = $this->getCustomerCity();
        $region = $city->getCityRegion();

        return sprintf(
            "%s, г.%s",
            $region->getName(),
            $city->getName()
        );
    }

    public function setDiscount($v)
    {
        if ($v !== null) {
            $v = (string)$v;
        }

        if ($v === '') {
            $v = null;
        }

        if ($this->discount !== $v) {
            $this->discount = $v;
            $this->modifiedColumns[CustomerTableMap::COL_DISCOUNT] = true;
        }

        return $this;
    } // setPrice()


    protected $auth = false;

    public function isAuth(): bool
    {
        return $this->auth;
    }


}
