<?php

namespace backend\controllers;

use yii\filters\AccessControl;

class ProducerInvoiceController extends BackendController
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return
                                $this->getParameterBag()->get('dolibarrApiKey')
                                && $this->getUserModule()
                                ->getAuthorizationChecker()
                                ->isGrantedAsProducer($this->getUserCurrent());
                        }
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index', [
            'producer' => $this->getProducerCurrent(),
            'invoicesArray' => $this->getProducerModule()
                ->getDolibarrUtils()
                ->getDolibarrProducerInvoices($this->getProducerCurrent())
        ]);
    }

    public function actionDownload(int $idDolibarrInvoice)
    {
        $documentDownload = \Yii::$app->dolibarrApi->downloadInvoice($idDolibarrInvoice);
        if($documentDownload) {
            return \Yii::$app->response->sendContentAsFile(base64_decode($documentDownload['content']), $documentDownload['filename'], [
                'mimeType' => $documentDownload['content-type']
            ]);
        }
        else {
            $this->addFlash('error', 'Facture introuvable');
            return $this->redirectReferer();
        }
    }
}