<?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\ORM\Typecast;

use BookiFlex\Core\Model\PaymentType\PaymentTypeInterface;
use Cycle\ORM\Parser\CastableInterface;
use Cycle\ORM\Parser\UncastableInterface;

defined( 'ABSPATH' ) || exit;

/**
 * Typecast for PaymentType model.
 *
 * Handles fallback for legacy/missing data from CPT.
 * Most defaults are now defined in the model constructor.
 * The `payable` property is computed in the model based on `type`.
 */
class PaymentTypeTypecast implements CastableInterface, UncastableInterface
{
    public function setRules(array $rules): array
    {
        return $rules;
    }

    /**
     * Provides fallback values for fields that might be null/missing in legacy data.
     * Model constructor handles defaults, but CPT data may have explicit nulls.
     */
    public function cast(array $data): array
    {
        // Fallback for ABA fields (Free version doesn't have these in UI)
        if (!array_key_exists('ABAPeriod', $data) || $data['ABAPeriod'] === null) {
            $data['ABAPeriod'] = PaymentTypeInterface::DEFAULT_ABA_PERIOD;
        }

        if (!isset($data['ABACondition'])) {
            $data['ABACondition'] = PaymentTypeInterface::DEFAULT_ABA_CONDITION;
        }

        if (!array_key_exists('ABAValue', $data) || $data['ABAValue'] === null) {
            $data['ABAValue'] = PaymentTypeInterface::DEFAULT_ABA_VALUE;
        }

        // Fallback for Pro-only fields
        if (!isset($data['paymentAuthorization'])) {
            $data['paymentAuthorization'] = false;
        }

        // Fallback for prepayment fields
        if (!isset($data['prepaymentType'])) {
            $data['prepaymentType'] = PaymentTypeInterface::DEFAULT_PREPAYMENT_TYPE;
        }

        if (!isset($data['prepaymentValue'])) {
            $data['prepaymentValue'] = PaymentTypeInterface::DEFAULT_PREPAYMENT_VALUE;
        }

        // Note: `payable` is now a computed property in the model (based on `type`),
        // so we don't need to set it here.

        return $data;
    }

    public function uncast(array $data): array
    {
        return $data;
    }
}
