<?php

namespace stripe\helpers;

class stripe_line_items
{
    /**
     * @var array $line_items
     */
    protected array $line_items = [];
    protected array $types = [
        'invoice',
        'payment_link'
    ];
    protected string $type;

    /**
     * @throws \Exception
     */
    public function __construct($type = 'payment_link')
    {
        if (!in_array($type, $this->types)) {
            throw new \Exception('Invalid type');
        }
        $this->type = $type;
    }

    public function __toString(): string
    {
        // Return the line items as a JSON string
        return json_encode(self::get());
    }

    public function get(): array
    {
        $line_items = [];
        /** @var stripe_line_item|array $line_item */
        foreach ( $this->line_items as $line_item ) {
            $line_items[] = is_array($line_item)
                ? $line_item
                : $line_item->get($this->type);
        }
        return $line_items;
    }

    public function add(stripe_line_item|array $line_item): void
    {
        $this->line_items[] = $line_item;
    }
}