<?php

namespace KupShop\OrderingBundle\Controller;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Routing\TranslatedRoute;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\OrderingBundle\Attachment\InvoicePDFAttachment;
use KupShop\OrderingBundle\Util\Invoice\PdfGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class PDFInvoiceController extends AbstractController
{
    /**
     * @TranslatedRoute(path="/#orderView#/{id_order}/pdf/", requirements={"id_order": "\d+"}, name="kupshop_orderingbundle_pdfinvoice")
     *
     * @return RedirectResponse|Response
     */
    public function getOrderInvoice(Request $request, PdfGenerator $pdf, $id_order)
    {
        // Check invoice download is enabled
        if (findModule(\Modules::ORDERS, 'show_invoice', 'Y') == 'N') {
            throw new NotFoundHttpException('Invoice download is disabled');
        }

        $userContext = Contexts::get(UserContext::class);

        $allow_access = false;

        $order = new \Order($id_order);
        $order->createFromDB($id_order);

        if (getAdminUser()) {
            $allow_access = true;
        } elseif ($request->query->get('cf')) {
            if ($request->query->get('cf') == $order->getSecurityCode()) {
                $allow_access = true;
            }
        } elseif ($userId = $userContext->getActiveId()) {
            if ($id_order && ($order->getUser()->id ?? null) == $userId) {
                $allow_access = true;
            }
        }

        if (!$allow_access) {
            return new RedirectResponse(createScriptURL([
                'URL' => 'launch.php',
                's' => 'orders',
                'ESCAPE' => 'NO',
            ]));
        }

        if ($externalInvoiceUrl = ($order->getData('externalDocuments')[InvoicePDFAttachment::getType()] ?? null)) {
            $externalPDFResponse = new Response(file_get_contents($externalInvoiceUrl));
            $externalPDFResponse->headers->set('Content-Type', 'application/pdf; charset=utf8');

            return $externalPDFResponse;
        }

        return $pdf->getResponse($order);
    }
}
