<?php

namespace common\components;

class DolibarrApi extends AbstractApi
{
    const RESOURCE_INVOICES = 'invoices';
    const RESOURCE_PRODUCTS = 'products';
    const RESOURCE_DOCUMENTS = 'documents';

    public function getInvoicesByThirParty(int $idThirdParty)
    {
        return $this->get(self::RESOURCE_INVOICES, [
            'sortfield' => 't.rowid',
            'sortorder' => 'DESC',
            'thirdparty_ids' => $idThirdParty,
            'limit' => 24
        ]);
    }

    public function getInvoice(int $idInvoice)
    {
        return $this->get(self::RESOURCE_INVOICES.'/'.$idInvoice, [
            'contact_list' => 1
        ]);
    }

    public function downloadInvoice(string $idInvoice)
    {
        $invoice = $this->getInvoice($idInvoice);
        if($invoice && isset($invoice['last_main_doc'])) {
            $originalFilename = str_replace('facture/', '', $invoice['last_main_doc']);

            return $this->get(self::RESOURCE_DOCUMENTS.'/download', [
                'modulepart' => 'facture',
                'original_file' => $originalFilename
            ]);
        }

        return null;
    }

    public function createInvoice(int $idUser)
    {
        return $this->post(self::RESOURCE_INVOICES, [
            'socid' => $idUser,
            'cond_reglement_id' => 2
        ]);
    }

    public function addInvoiceLine(int $idInvoice, int $idProduct)
    {
        $productArray = $this->getProduct($idProduct);

        return $this->post(self::RESOURCE_INVOICES . '/' . $idInvoice . '/lines', [
            'fk_product' => $idProduct,
            'subprice' => $productArray['price'],
            'qty' => 1,
            'desc' => $productArray['description']
        ]);
    }

    public function validateInvoice(int $idInvoice)
    {
        return $this->post(self::RESOURCE_INVOICES . '/' . $idInvoice . '/validate', [], false);
    }

    public function generateInvoicePdf(string $reference)
    {
        return $this->put(self::RESOURCE_DOCUMENTS . '/builddoc', [
            'modulepart' => 'invoice',
            'doctemplate' => 'crabe',
            'langcode' => 'fr_FR',
            'original_file' => $reference.'/'.$reference.'.pdf'
        ]);
    }

    public function getProduct(int $idProduct)
    {
        return $this->get(self::RESOURCE_PRODUCTS . '/' . $idProduct);
    }
}