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

use BookiFlex\Core\Service\OfferFinder\DTO\OfferResult;
use BookiFlex\Core\Service\StayCostCalculator\ValueObject\StayCostByDate;
use Brick\Math\RoundingMode;

defined( 'ABSPATH' ) || exit;

class StayCostResultTransformer
{
    public static function transform(OfferResult $result): array
    {
        $summary = $result->getStayCost()->getCompleteSummary();
        if ($discountPercentage = $result->getStayCost()->getInheritanceDiscountPercentage()) {
            $discountPercentage = (int) round($discountPercentage);
        }

        return [
            'ratePlan'          => $result->getRatePlan()->getId(),
            'accommodationType' => $result->getAccommodationType()->getId(),
            'details'           => array_map(
                function (StayCostByDate $priceDetails) {
                    $summary = $priceDetails->getCashier();
                    return [
                        'date'       => $priceDetails->getDate()->format('Y-m-d'),
                        'subtotal'   => $summary->subtotal()->net()->getMinorAmount()->toInt(),
                        'total'      => $summary->total()->getMinorAmount()->toInt(),
                        'placements' => $priceDetails->getPriceDetails(),
                    ];
                },
                $result->getStayCost()->getDailyCosts()
            ),
            'price' => [
                'currency'             => $summary->total()->getCurrency(),
                'sellingPrice'         => $summary->total()->getMinorAmount()->toInt(),
                'originalSellingPrice' => $discountPercentage > 0
                    ? $summary->total()->dividedBy(1 - ($discountPercentage / 100), RoundingMode::HALF_UP)->getMinorAmount()->toInt()
                    : null,
                'discount'             => $discountPercentage,
                'details'              => [
                    'subtotal'  => $summary->subtotal()->getMinorAmount()->toInt(),
                    'taxes'     => $summary->totalTaxes()->getMinorAmount()->toInt(),
                    'charges'   => $summary->totalCharges()->getMinorAmount()->toInt(),
                    'discounts' => $summary->totalDiscounts()->getMinorAmount()->toInt(),
                    'total'     => $summary->total()->getMinorAmount()->toInt(),
                ]
            ],
            'scenario'     => $result->getScenario(),
            'restrictions' => $result->getRestrictions()
        ];
    }
}
