<?php

namespace endpoints\orders;

use Exception;
use traits\economic_endpoint_t;

class economic_invoices_booked_endpoint
{
    use economic_endpoint_t;

    /**
     * List sent invoices
     * @param string $filter Set the filter using the self::filter method
     * @return object {collection: [order], pagination: {maxPageSize: number, skipPages: number, results: number}}
     */
    public function get(array $filters = [], array $pagination = []): object
    {
        $response = $this->send_request(
            '/invoices/booked/?filter=' . self::filters($filters) . self::pagination($pagination),
            'GET'
        );
        // Return the response as an object
        return json_decode($response);
    }

    /**
     * Get invoice lines
     * @param array $invoice_ids List of invoice ids to get lines for (e.g. [1, 2, 3])
     * @param array $filters Set the filter using the self::filter method
     * @return array {invoice_id: {collection: [invoice_line], pagination: {maxPageSize: number, skipPages: number, results: number}}}
     */
    public function get_invoice_lines(array $invoice_ids, array $filters = []): array
    {
        $tmp_invoices = [];
        foreach ( $invoice_ids as $invoice ) {
            $response = $this->send_request(
                '/invoices/booked/' . $invoice . '/?filter=' . self::filters($filters),
                'GET'
            );
            $tmp_invoices[$invoice] = json_decode($response)->lines;
        }
        return $tmp_invoices;
    }

    /**
     * Get booked invoice from external id
     * @param string $external_id External id to get
     * @return int Invoice id
     * @throws Exception If the request fails
     * @throws Exception If the invoice is not found
     */
    public function get_from_external_id(string $external_id): int
    {
        $response = $this->send_request(
            '/invoices/booked?filter=references.other$eq:' . $external_id,
            'GET'
        );
        // Return the response as an object
        $response = json_decode($response);
        //var_dump($response);
        if (isset($response->collection[0])) {
            return $response->collection[0]->bookedInvoiceNumber;
        } else {
            throw new Exception('Invoice booked with external id (' . $external_id . ') not found');
        }
    }

    public function getFromId(int $invoice_id): object
    {
        $response = $this->send_request(
            '/invoices/booked/' . $invoice_id,
            'GET'
        );
        // Return the response as an object
        return json_decode($response);
    }

}