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


declare(strict_types=1);
namespace BookiFlex\Extensions\Cart\ORM\Typecast;

use BookiFlex\Extensions\Cart\Contract\CartItemInterface;
use BookiFlex\Extensions\Cart\Model\AccommodationCartItem;
use Cycle\ORM\Parser\CastableInterface;
use Cycle\ORM\Parser\UncastableInterface;

defined( 'ABSPATH' ) || exit;

class CartTypecast implements CastableInterface, UncastableInterface
{
    public function setRules(array $rules): array
    {
        return $rules;
    }

    public function cast(array $data): array
    {
        // Cart casting
        if (isset($data['data']) && is_string($data['data'])) {
            $itemArray = json_decode($data['data'], true);
            if ($itemArray) {
                if ($itemArray['type'] === AccommodationCartItem::TYPE) {
                    $data['data'] = AccommodationCartItem::fromArray($itemArray);
                }
            }
        }

        return $data;
    }

    public function uncast(array $data): array
    {
        // Cart uncasting
        if (isset($data['data']) && $data['data'] instanceof CartItemInterface) {
            $data['data'] = json_encode($data['data']->toArray());
        }

        return $data;
    }
}
