<?php

namespace YSquare\Shipcloud\Application\Model;

use OxidEsales\Eshop\Application\Model\OrderArticle;
use OxidEsales\Eshop\Core\Model\BaseModel;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;

class Shipcloud2Orderarticle extends BaseModel
{
    /**
     * @var QueryBuilderFactory
     */
    protected $queryBuilderFactory;

    /**
     * Class constructor, initiates parent constructor (parent::oxBase()).
     */
    public function __construct()
    {
        parent::__construct();
        $this->init('ysshipcloud2orderarticles');

        $container = ContainerFactory::getInstance()->getContainer();
        $this->queryBuilderFactory = $container->get(QueryBuilderFactoryInterface::class);
    }

    public function getOrderArticle()
    {
        $oxorderarticle = oxNew(OrderArticle::class);
        $oxorderarticle->load($this->ysshipcloud2orderarticles__oxoartid->value);

        return $oxorderarticle;
    }

    public function loadEnhanced($order_article_id, $shipcloud_id)
    {
        $queryBuilder = $this->queryBuilderFactory->create();

        $oxid = $queryBuilder
            ->select('s2oa.oxid')
            ->from('ysshipcloud', 's')
            ->leftJoin('s', 'ysshipcloud2orderarticles', 's2oa', 's.OXID = s2oa.YSSHCLID')
            ->leftJoin('s2oa', 'oxorderarticles', 'oa', 's2oa.OXOARTID = oa.OXID')
            ->where('oa.OXID = :oa_oxid')
            ->andWhere('s.OXID = :s_oxid')
            ->setParameter('oa_oxid', $order_article_id)
            ->setParameter('s_oxid', $shipcloud_id)
            ->execute()->fetch()['oxid'];

        $this->load($oxid);
    }

    public function getAmount()
    {
        return $this->ysshipcloud2orderarticles__oxamount->value;
    }
}
