<?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\Room\Closure\Filters;

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

use E4J\VikRestaurants\Collection\CollectionFilter;
use E4J\VikRestaurants\Collection\Item;
use E4J\VikRestaurants\Room\Closure\RoomClosure;

/**
 * Filters the room closures to obtain only the ones that match the specified check-in.
 * 
 * @since 1.10
 */
class DateFilter implements CollectionFilter
{
    /** @var \DateTime */
    protected $checkin;

    /**
     * Class constructor.
     * 
     * @param  mixed  $checkin  The check-in date to compare against.
     */
    public function __construct($checkin)
    {
        if (is_int($checkin))
        {
            // convert timestamp into a date object
            $this->checkin = \JFactory::getDate(date('Y-m-d H:i:s', $checkin));
        }
        else if (!$checkin instanceof \DateTime)
        {
            // convert date string into a date object
            $this->checkin = \E4J\VikRestaurants\Helpers\DateHelper::getDate($checkin);
        }
        else
        {
            // date object directly provided
            $this->checkin = $checkin;
        }
    }

    /**
     * @inheritDoc
     */
    public function match(Item $item)
    {
        if (!$item instanceof RoomClosure)
        {
            // can handle only objects that inherit the RoomClosure class
            throw new \InvalidArgumentException('RoomClosure item expected, ' . get_class($item) . ' given');
        }

        // compare the date against recurring dates
        return $item->getRecurrence()->match($this->checkin);
    }
}
