<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

namespace E4J\VikRestaurants\Payment\Filters;

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

use E4J\VikRestaurants\Collection\CollectionFilter;
use E4J\VikRestaurants\Collection\Item;

/**
 * Filters the payment gateways to obtain only the ones compliant with the current take-away service (pickup or delivery).
 * 
 * @since 1.11
 */
class TakeAwayServiceFilter implements CollectionFilter
{
    /** @var string */
    protected $service;

    /**
     * Class constructor.
     * 
     * @param  mixed  $service  The current service.
     */
    public function __construct($service = null)
    {
        if (is_null($service))
        {
            // recover service from cart
            $this->service = \E4J\VikRestaurants\TakeAway\Cart::getInstance()->getService();
        }
        else if ($service instanceof \E4J\VikRestaurants\TakeAway\Cart)
        {
            // extract service cost from cart
            $this->service = $service->getService();
        }
        else
        {
            $this->service = (string) $service;
        }
    }

    /**
     * @inheritDoc
     */
    public function match(Item $item)
    {
        // get the configured service
        $service = $item->get('service', '');

        // accept only if the service accepts anything or the selected one
        return !$service || $service == $this->service;
    }
}
