<?php

namespace Diamond\Controllers;

use Core\BaseController;
use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Helpers\Date;
use Diamond\Application\Notification\Dto\Message;
use Diamond\Application\Notification\NotificationService;
use Diamond\Application\Notification\SendEmail\SendEmailException;
use Diamond\Config\Main;
use Diamond\Infrastructure\Models\MailingRequestRecipient\MailingRequestRecipientQuery;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class MailingController extends BaseController implements RequestAwareInterface
{

    use RequestAwareTrait;


    public function __construct(private Main $mainConfig, private NotificationService $notificationService)
    {
    }

    public function pingImage(array $arg)
    {

        $id = $arg['id'] ?? null;

        $receipt = MailingRequestRecipientQuery::create()->filterById($id)->findOne();

        if ($receipt) {
            $receipt->setViewedAt(new \DateTime());
            $receipt->save();
        }

        return new Response(
            base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII='),
            200, [
                'Content-Type' => 'image/png'
            ]
        );
    }

    public function sendMail()
    {
        if(!$to = $this->mainConfig->getEmail_admin()){
            return new JsonResponse([
                'error' => 'Email адрес администратора не настроен'
            ], JsonResponse::HTTP_OK);
        }

        try {
            $this->notificationService->sendToEmail($to, new Message('Тестовое сообщения для проверки работы почты',
                'Тестовое сообщения для проверки работы почты, дата: ' . (new \DateTime())->format(Date::formatDisplay())));
            return new JsonResponse([
                'success' => true
            ], JsonResponse::HTTP_OK);
        } catch (SendEmailException $ex) {
            return new JsonResponse([
                'error' => 'Не получилось отправить сообщение, проверьте настройки email'
            ], JsonResponse::HTTP_OK);
        }
    }
}