<?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\Service\SuitableRatePlan;

use BookiFlex\Core\Model\RatePlan\RatePlan;
use BookiFlex\Core\Repository\RatePlanRepository;
use BookiFlex\Core\Service\SuitableRatePlan\Event\SuitableRatePlansAreFound;
use BookiFlex\Core\Util\Iter;
use Psr\EventDispatcher\EventDispatcherInterface;

defined( 'ABSPATH' ) || exit;

/**
 * Search active Rate plans by accommodation type.
 * And returns Rate plans which can support the accommodation type.
 */
class SuitableRatePlan
{
    public function __construct(
        private readonly RatePlanRepository $ratePlanRepository,
        private readonly ?EventDispatcherInterface $dispatcher = null
    ) {
    }

    /**
     * @param array $ratePlanIDs List of rate plan IDs to search for
     * @param array $accommodationTypeIDs List of accommodation type IDs to search for
     * @param mixed $context
     * @return RatePlan[]
     */
    public function search(
        array $ratePlanIDs = [],
        array $accommodationTypeIDs = [],
        mixed $context = null
    ): array {
        $ratePlans = $this->ratePlanRepository->findAll(['ids' => $ratePlanIDs, 'onlyActive' => true]);
        $ratePlans = $this->filterActiveRatePlans($ratePlans);

        if (!empty($accommodationTypeIDs)) {
            $ratePlans = $this->filterRatePlansByAccommodationTypes($ratePlans, $accommodationTypeIDs);
        }

        // TODO: filter Rate plans by Promo codes
        if ($this->dispatcher) {
            $event     = $this->dispatcher->dispatch(new SuitableRatePlansAreFound($ratePlans, $context));
            $ratePlans = $event->getRatePlans();
        }

        return Iter::toArray($ratePlans);
    }

    private function filterActiveRatePlans(iterable $ratePlans): array
    {
        $filteredRatePlans = [];
        foreach ($ratePlans as $ratePlan) {
            if ($ratePlan->isActive()) {
                $filteredRatePlans[] = $ratePlan;
            }
        }

        return $filteredRatePlans;
    }

    /**
     * @param RatePlan[] $ratePlans
     * @param int[] $accommodationTypeIDs
     * @return array
     */
    private function filterRatePlansByAccommodationTypes(iterable $ratePlans, array $accommodationTypeIDs): array
    {
        $result = [];
        foreach ($ratePlans as $ratePlan) {
            if (empty($ratePlan->getAccommodationTypes())) {
                continue;
            }
            foreach ($ratePlan->getAccommodationTypes() as $accommodationType) {
                if (in_array($accommodationType->getId(), $accommodationTypeIDs)) {
                    $result[] = $ratePlan;
                    break;
                }
            }
        }

        return $result;
    }
}
