<?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\Invoice;
use traits\stripe_endpoint_t;

class stripe_endpoint_invoice
{
    use stripe_endpoint_t;

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

    /**
     * @throws ApiErrorException
     * @throws Exception
     */
    public function generate(int $order_id, string $stripe_customer_id): Invoice
    {
        $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('invoice');
        // 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,
            $stripe_customer_id,
            [
                'order_id' => $order_id,
                'customer_id' => $stripe_customer_id
            ]
        );
    }

    /**
     * Create a new payment link
     * @param stripe_line_items $line_items
     * @param string $stripe_customer_id
     * @param array $metadata Additional metadata
     * @return Invoice
     * @throws ApiErrorException
     * @throws Exception
     */
    public function create(stripe_line_items $line_items, string $stripe_customer_id, array $metadata = []): Invoice
    {
        $invoice = self::getClient()->invoices->create([
            'customer' => $stripe_customer_id,
            'collection_method' => 'send_invoice',
            'days_until_due' => 30,
            'metadata' => $metadata,
            'auto_advance' => true,
            //'payment_settings' => [
            //    'payment_method_types' => [
            //        'card',
            //        'paypal'
            //    ],
            //],
        ]);
        // Add the line items to the invoice
        foreach ( $line_items->get() as $line_item ) {
            self::getClient()->invoiceItems->create([
                'customer' => $stripe_customer_id,
                'invoice' => $invoice->id,
                'price' => $line_item['price'],
            ]);
        }
        // Finalize the invoice
        return $invoice->finalizeInvoice();
    }

}