<?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\Repository;

use BookiFlex\Core\ORM\Schema\DateUnitSchema;
use Cycle\Database\Injection\Fragment;
use Cycle\Database\Injection\Parameter;
use Cycle\ORM\Select\Repository;
use DateTimeInterface;

defined( 'ABSPATH' ) || exit;

class DateUnitRepository extends Repository
{
    /**
     * Find DateUnits by date range
     */
    public function findByRange(
        DateTimeInterface $dateFrom,
        DateTimeInterface $dateTo,
        int $ratePlanId,
        int $accommodationTypeId
    ): iterable {
        $query = $this->select()
            ->where('rate_plan_id', $ratePlanId)
            ->andWhere('accommodation_type_id', $accommodationTypeId)
            ->andWhere('date', '>=', $dateFrom->format('Y-m-d'))
            ->andWhere('date', '<=', $dateTo->format('Y-m-d'))
            ->orderBy('date');

        return $query->fetchAll();
    }

    /**
     * Return MIN and MAX date for set DateUnits by ratePlanId and accommodationTypeId
     *
     * @param int $ratePlanId
     * @param int $accommodationTypeId
     * @return array|null
     */
    public function findMinMaxDateBy(int $ratePlanId, int $accommodationTypeId): ?array
    {
        $query = $this->select()
            ->buildQuery()
            ->from(DateUnitSchema::TABLE_NAME)
            ->columns([
                new Fragment('MIN(date) as min'),
                new Fragment('MAX(date) as max')
            ])
            ->where('rate_plan_id', new Parameter($ratePlanId))
            ->andWhere('accommodation_type_id', new Parameter($accommodationTypeId));

        $result = $query->run()->fetch();

        if ($result === false) {
            return null;
        }

        return [
            'min' => $result['min'],
            'max' => $result['max'],
        ];
    }
}
