<?php

namespace KupShop\OrderingBundle\Controller;

use KupShop\ContentBundle\View\OrderView;
use KupShop\KupShopBundle\Routing\TranslatedRoute;
use KupShop\OrderingBundle\Attachment\BaseAttachment;
use KupShop\OrderingBundle\Attachment\InvoiceXLSAttachment;
use KupShop\OrderingBundle\Exception\InvoiceException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class XLSInvoiceController extends AbstractController
{
    /**
     * @TranslatedRoute(path="/#orderView#/{id_order}/xls/", requirements={"id_order": "\d+"}, name="kupshop_orderingbundle_xlsinvoice")
     *
     * @return Response
     */
    public function getOrderItems(Request $request, InvoiceXLSAttachment $invoiceXLSAttachment, $id_order)
    {
        OrderView::checkOrderOwnership($id_order, $request->get('cf'));
        $order = $this->getOrder($id_order);
        try {
            $response = new Response();
            $invoiceXLSAttachment->setOrder($order);
            $content = $invoiceXLSAttachment->getContent();

            $response->headers->set('Content-Type', $invoiceXLSAttachment->getMimeType());
            $response->headers->set('Content-Disposition', 'inline; filename="'.$invoiceXLSAttachment->getFilename().'"');

            if (!$content) {
                throw new \UnexpectedValueException('XLS error: server returned false');
            }

            if ($invoiceXLSAttachment->getAttachmentType() == BaseAttachment::TYPE_PATH) {
                $content = file_get_contents($content);
            }

            $response->setContent($content);

            return $response;
        } catch (\UnexpectedValueException $e) {
            getRaven()->captureException($e);

            return new Response('Přílohu se nepodařilo vygenerovat, zkuste to znovu.');
        } catch (InvoiceException $e) {
            return new Response($e->getMessage());
        }
    }

    private function getOrder($id_order)
    {
        $order = new \Order($id_order);
        $order->createFromDB($id_order);

        return $order;
    }
}
