<?php


namespace Magetop\Advancepreview\Block\Adminhtml\Product\Edit;

use Magento\Backend\Block\Template;

/**
 * Class PreviewDiscount
 * @package Magetop\Advancepreview\Block\Adminhtml\Product\Edit
 */
class PreviewAdditionalTab extends Template
{
    /**
     * @var \Magetop\Advancepreview\Helper\Data
     */
    protected $previewHelper;
    protected $collectionFactory;
    public function __construct(
        Template\Context $context,
        \Magetop\Advancepreview\Helper\Data $previewHelper,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $collectionFactory,
        array $data = []
    )
    {
        parent::__construct($context, $data);
        $this->previewHelper = $previewHelper;
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * @param $id
     * @param $productId
     * @return array
     */
    public function getAdditionalById($id, $productId) {
        $collection = $this->collectionFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('addition_id',$id);
//        echo (string)$collection->getSelect();
        $additionalData = [
            'addition_id'=>0,
            'product_id'=>0,
            'status'=>1,
            'title'=>'',
            'description'=>'',
            'price'=>0,
            'created_at'=>date('Y-m-d H:i:s')
        ];
        if($collection && $collection->getSize() > 0) {
            $additionalData = $collection->getFirstItem()->getData();
        }
        return $additionalData;
    }

    /**
     * @param int $productId
     * @return mixed
     */
    public function getAdditionalProductId($productId = 0) {
        $collection = $this->collectionFactory->create()
            ->addFieldToSelect('*')
            ->addFieldToFilter('product_id',$productId)
            ->setOrder('addition_id','ASC');
        // echo (string)$collection->getSelect();
        return $collection;
    }

    /**
     * @return array
     */
    public function getAjaxUrl() {
        $saveUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/previewAdditionalTab/save');
        $itemsUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/previewAdditionalTab/items');
        $editUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/previewAdditionalTab/edit');
        $dellUrl = $this->previewHelper->getOpdAdminUrl('advancepreview/previewAdditionalTab/dellItem');
        return [
            'save_url'=>$saveUrl,
            'item_url'=>$itemsUrl,
            'edit_url'=>$editUrl,
            'dell_url'=>$dellUrl,
        ];
    }
}
