<?php

namespace stripe\endpoints;

use Exception;
use objects\orders_o;
use Stripe\Exception\ApiErrorException;
use stripe\helpers\stripe_line_item;
use stripe\helpers\stripe_line_items;
use Stripe\PaymentLink;
use traits\stripe_endpoint_t;

class stripe_endpoint_payment_link
{
    use stripe_endpoint_t;

    /**
     * Retrieve a payment link
     * @param string $id
     * @return PaymentLink
     * @throws ApiErrorException
     * @throws Exception
     */
    public function retrieve(string $id): PaymentLink
    {
        return self::getClient()->paymentLinks->retrieve($id);
    }

    /**
     * @throws ApiErrorException
     * @throws Exception
     */
    public function generate(int $order_id, string $email): PaymentLink
    {
        $order = (new orders_o())->select($order_id);
        $order->requireSelected();
        // Get the order items
        $order_items = $order->getOrderItems($order_id);
        // Create a new line items object
        $line_items = new stripe_line_items();
        // Loop through the order items
        foreach ( $order_items as $order_item ) {
            // Add the order item to the line items
            $line_items->add(
                new stripe_line_item(
                    $order_item['product_id'],
                    $order_item['price'],
                    $order_item['quantity']
                )
            );
        }
        // Create the payment link
        return $this->create($line_items, [
            'order_id' => $order_id,
            'email' => $email
        ]);
    }

    /**
     * Create a new payment link
     * @param stripe_line_items $line_items
     * @param array $metadata Additional metadata
     * @return PaymentLink
     * @throws ApiErrorException
     * @throws Exception
     */
    public function create(stripe_line_items $line_items, array $metadata = []): PaymentLink
    {
        return self::getClient()->paymentLinks->create([
            'line_items' => $line_items->get(),
            'metadata' => $metadata
        ]);
    }

}