<?php
namespace App\Controller\Content;

use App\Service\Content\ContentFileExporter;
use App\Service\ContentService;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Swift_Attachment;
use Swift_Mailer;
use Swift_Message;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;


class SendEmailToClientContactsController extends AbstractFOSRestController
{
    /**
     * @var ContentService
     */
    private $service;

    /**
     * @var ContentFileExporter
     */
    private $contentFileExporter;

    public function __construct(ContentService $service, ContentFileExporter $contentFileExporter)
    {
        $this->service = $service;
        $this->contentFileExporter = $contentFileExporter;
    }

    /**
     * Retrieves an File resource.
     *
     * @Rest\Post("/content/{id}/sendmessage", requirements={"id"="\d+"}))
     *
     * @param int $id
     * @param Swift_Mailer $mailer
     * @return JsonResponse
     */
    public function getAction(int $id, Swift_Mailer $mailer, Request $request)
    {
        $payload = json_decode($request->getContent());
        $message = $payload->message ?? '';
        $content = $this->service->getContent($id);
        $type = $payload->format ?? 'pdf';
        $file = $this->contentFileExporter->export($content, strtoupper($type));

        $path = realpath(__DIR__ . '/../../../public/uploads/' . $file->getPath() . $file->getFilename());
        $contact = $content->getCampaign()->getClient()->getMainContact();
        if (!$contact) {
            throw new \Exception('No main contact for content id '.$id.'!');
        }

        $this->sendEmail($message, $contact, $content, $mailer, $path);

        return $this->json(
            [
                'id' => $id,
                'status' => true,
            ]
        );
    }

    private function sendEmail($message, $contact, $content, $mailer, $filePath)
    {
        $emailMessage = (new Swift_Message($content->getTitle()))
            ->setFrom('system@akita.crm.i3x.co.uk')
            ->setTo($contact->getEmail())
            ->setBody(
                $this->renderView(
                    'Email/send-message.html.twig',
                    [
                        'message' => $message,
                    ]
                ),
                'text/html'
            )
            ->attach(Swift_Attachment::fromPath($filePath))
        ;

        $mailer->send($emailMessage);
    }
}