<?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\Api\Request\DateUnit;

use BookiFlex\Core\Api\Request\AbstractRequest;
use BookiFlex\Core\Provider\LocalTimeZone;
use DateTimeImmutable;
use WP_REST_Request;

defined( 'ABSPATH' ) || exit;

class GetCalendarRequest extends AbstractRequest
{
    private readonly DateTimeImmutable $dateFrom;
    private readonly DateTimeImmutable $dateTo;

    public function __construct(
        DateTimeImmutable|string $dateFrom,
        DateTimeImmutable|string $dateTo,
        private readonly int $ratePlanId
    ) {
        $this->dateFrom = is_string($dateFrom)
            ? DateTimeImmutable::createFromFormat('Y-m-d', $dateFrom, LocalTimeZone::get())
            : $dateFrom;

        $this->dateTo = is_string($dateTo)
            ? DateTimeImmutable::createFromFormat('Y-m-d', $dateTo, LocalTimeZone::get())
            : $dateTo;
    }

    /**
     * Create request from WP REST Request
     */
    public static function fromWpRestRequest(WP_REST_Request $request): self
    {
        $params = $request->get_json_params();

        return new self(
            dateFrom: $params['dateFrom'],
            dateTo: $params['dateTo'],
            ratePlanId: (int) $params['ratePlan']
        );
    }

    /**
     * Get validation rules for WP REST API
     */
    public static function getValidationRules(): array
    {
        return [
            'dateFrom' => self::dateRangeRule(
                fromField: 'dateFrom',
                toField: 'dateTo',
                allowEqual: true,
                required: true
            ),
            'dateTo' => self::dateRule(required: true),
            'ratePlan' => self::positiveIntRule(required: true),
        ];
    }

    public function getDateFrom(): DateTimeImmutable
    {
        return $this->dateFrom;
    }

    public function getDateTo(): DateTimeImmutable
    {
        return $this->dateTo;
    }

    public function getRatePlanId(): int
    {
        return $this->ratePlanId;
    }
}
