<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */


declare(strict_types=1);
namespace BookiFlex\Core\Model\AccommodationType\Placement;

use BookiFlex\Core\Model\AccommodationType\Guest\GuestType;
use BookiFlex\Core\ValueObject\PlacementLocation;

defined( 'ABSPATH' ) || exit;

/**
 * Collection of placement options
 */
final class PlacementRules
{
    /** @var PlacementOption[] */
    private array $options = [];

    public function addOption(PlacementOption $option): void
    {
        $key = $option->getKey() . '_' . $option->getGuestType()->getVariantKey();
        $this->options[$key] = $option;
    }

    public function findOption(GuestType $guestType, PlacementLocation $location): ?PlacementOption
    {
        foreach ($this->options as $option) {
            if ($option->getGuestType()->matches($guestType) &&
                $option->getLocation()->equals($location) &&
                $option->isAllowed()) {
                return $option;
            }
        }
        return null;
    }

    /**
     * @return PlacementOption[]
     */
    public function getAllowedOptions(): array
    {
        return array_filter($this->options, fn($opt) => $opt->isAllowed());
    }

    public function canAccommodate(GuestType $guest, PlacementLocation $location): bool
    {
        $option = $this->findOption($guest, $location);
        return $option !== null && $option->isAllowed();
    }

    public function toArray(): array
    {
        $result = [];
        foreach ($this->options as $option) {
            $typeKey = $option->getGuestType()->getTypeKey();
            $locationKey = $option->getLocation()->toString();
            $variantKey = $option->getGuestType()->getVariantKey();

            $key = "{$typeKey}On" . ucfirst($locationKey) . "Place";
            if (!isset($result[$key])) {
                $result[$key] = [];
            }

            $result[$key][$variantKey] = $option->isAllowed();
        }
        return $result;
    }
}
