<?php

declare(strict_types=1);


namespace BrandCrockAquaTheme\Storefront\Controller;

use Exception;
use Shopware\Core\Content\Mail\Service\AbstractMailService;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Controller\StorefrontController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Response;
use Shopware\Core\Framework\Log\Package;

/**
 * @internal
 */
#[Package('checkout')]
#[Route(defaults: ['_routeScope' => ['storefront']])]

class ContactUsController extends StorefrontController
{
    public $mailService;
    public $systemConfigService;

    public function __construct(AbstractMailService $mail, SystemConfigService $systemConfigService)
    {
        $this->mailService = $mail;
        $this->systemConfigService = $systemConfigService;
    }

    #[Route(
        path: '/bc_contact_us/index',
        name: 'frontend.action.bc_contact_us',
        methods: [Request::METHOD_POST],
        defaults: [
            'XmlHttpRequest' => true,
        ]
    )]
    public function index(Request $request, SalesChannelContext $salesChannelContext)
    {
        $formData = json_decode($request->getContent(), true) ?? [];

        if (!empty($formData['company'])) {
            // Bot detected
            return new Response('', 204); // silent fail (best practice)
        }

        $senderName = $formData['name'] ?? '';
        $senderEmail = $formData['email'] ?? '';
        $senderContact = $formData['phone'] ?? 'not provided';
        $senderMessage = $formData['message'] ?? '';

        if (empty($senderEmail) || empty($senderMessage)) {
            $errorMessage = $this->trans(\sprintf('BrandCrockAquaTheme.contactform.error.requiredFields'));
            return new Response($errorMessage, 400);
        }

        if (!preg_match("/^[\p{L} '-]+$/u", $senderName)) {
            $errorMessage = $this->trans(\sprintf('BrandCrockAquaTheme.contactform.error.invalidName'));
            return new Response($errorMessage, 406);
        }

        if (!filter_var($senderEmail, FILTER_VALIDATE_EMAIL)) {
            $errorMessage = $this->trans(\sprintf('BrandCrockAquaTheme.contactform.error.invalidEmail'));
            return new Response($errorMessage, 406);
        }

        if ($senderContact !== 'not provided') {            
            if (!preg_match("/^[0-9+\-\s()]+$/", $senderContact)) {
                $errorMessage = $this->trans(\sprintf('BrandCrockAquaTheme.contactform.error.invalidPhone'));
                return new Response($errorMessage, 406);
            }
        }

        $senderName = htmlspecialchars($senderName);
        $senderEmail = htmlspecialchars($senderEmail);
        $senderContact = htmlspecialchars($senderContact);
        $senderMessage = nl2br(htmlspecialchars($senderMessage));

        $contentHtml = '<b>Name:</b> '. $senderName.'<br/><b>Email:</b> '.$senderEmail.'<br/><b>Phone: </b>'.$senderContact.'<br/><b>Message: </b>'.$senderMessage;
        $shopName = $salesChannelContext->getSalesChannel()->getName();
        $shopEmail = $this->systemConfigService->get('core.basicInformation.email', $salesChannelContext->getSalesChannel()->getId());
        $subject =  $this->trans(\sprintf('BrandCrockAquaTheme.contactform.mail.subject', ['%name%' => $senderName]));

        try {
            $data = new ParameterBag();
            $data->set(
                'recipients',
                [
                    $shopEmail => $shopName
                ]
            );

            $data->set('senderName', $senderName ?: $senderEmail);
            $data->set('contentHtml', $contentHtml);
            $data->set('contentPlain', strip_tags($contentHtml));
            $data->set('subject', $subject);
            $data->set('salesChannelId', $salesChannelContext->getSalesChannel()->getId());

            $this->mailService->send(
                $data->all(),
                $salesChannelContext->getContext(),
                []
            );

            $successMessage = $this->trans(\sprintf('BrandCrockAquaTheme.contactform.success'));

            return new Response($successMessage, Response::HTTP_OK);
        } catch (Exception $e) {
            $errorMessage = $this->trans(\sprintf('BrandCrockAquaTheme.contactform.error.generalError'));
            return new Response($errorMessage, 406);
        }
    }
}
