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


declare(strict_types=1);
namespace BookiFlex\Extensions\Payment\Api\Transformer;

use BookiFlex\Extensions\Payment\Model\Payment;
use BookiFlex\Extensions\Payment\Model\PaymentAllocation;
use BookiFlex\Extensions\Payment\Util\Util;

defined( 'ABSPATH' ) || exit;

class PaymentTransformer
{
    public static function transform(Payment $payment): array
    {
        $client = $payment->getClient();
        return [
            'id'          => $payment->getId(),
            'amount'      => $payment->getAmount()->getMinorAmount()->toInt(),
            'currency'    => $payment->getAmount()->getCurrency(),
            'status'      => (string) $payment->getStatus(),
            'description' => $payment->getDescription(),
            'details'     => $payment->getDetails(),
            'number'      => $payment->getNumber(),
            'gatewayName' => $payment->getGatewayName(),
            'allocations' => self::transformAllocations($payment->getPaymentAllocations()),
            'createdAt'   => $payment->getCreatedAt()->format('Y-m-d H:i:s'),
            'updatedAt'   => $payment->getUpdatedAt()?->format('Y-m-d H:i:s'),
            'client'      => [
                'id'        => $client->getId(),
                'email'     => $client->getEmail(),
                'firstName' => $client->getFirstName(),
                'lastName'  => $client->getLastName(),
                'phone'     => $client->getPhone(),
            ]
        ];
    }

    private static function transformAllocations(array $paymentAllocations): array
    {
        return array_map(function (PaymentAllocation $paymentAllocation) {
            $reservation = $paymentAllocation->getReservation();
            return [
                'id'          => $paymentAllocation->getId(),
                'amount'      => $paymentAllocation->getAmount()->getMinorAmount()->toInt(),
                'reservation' => [
                    'id'          => $reservation->getId(),
                    'sid'         => $reservation->getSid(),
                    'number'      => $reservation->getNumber(),
                    'status'      => (string) $reservation->getStatus(),
                    'paymentType' => [
                        'name'         => $reservation->getPaymentType()->getName(),
                        'waitingUntil' => $reservation->getWaitingPaymentUntil()?->format('Y-m-d H:i:s'),
                        'gatewayName'  => $reservation->getPaymentType()->getGatewayName(),
                    ],
                ],
            ];
        }, $paymentAllocations);
    }
}
