<?php

namespace FiloBlu\Storelocator\Model\ResourceModel\Stores;

use FiloBlu\Storelocator\Model\ResourceModel\Stores;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

/**
 *
 */
class Collection extends AbstractCollection
{
	/**
	 * @var string
	 * ID for Mass Actions
	 */
	protected $_idFieldName = 'store_id';

	/**
	 * @param $storeIds
	 * @param $withDefaultStore
	 * @return $this
	 */
	public function addStoreFilter($storeIds = [], $withDefaultStore = true)
	{
		if (!is_array($storeIds)) {
			$storeIds = [$storeIds];
		}
		if ($withDefaultStore && !in_array('0', $storeIds)) {
			array_unshift($storeIds, 0);
		}
		$where = [];
		foreach ($storeIds as $storeId) {
			$where[] = $this->_getConditionSql('store_ids', ['finset' => $storeId]);
		}

		$this->_select->where(implode(' OR ', $where));

		return $this;
	}

	/**
	 * @param $field
	 * @param $condition
	 * @return Collection
	 */
	public function addFieldToFilter($field, $condition = null)
	{
		if ($field === 'store_ids') {
			$conditionSec = ['finset' => $condition['eq']];
			return parent::addFieldToFilter($field, $conditionSec);
		}
		return parent::addFieldToFilter($field, $condition);
	}

	/**
	 * Define resource model
	 *
	 * @return void
	 */
	protected function _construct()
	{

		$this->_init(\FiloBlu\Storelocator\Model\Stores::class, Stores::class);
	}
}