<?php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Psr\Log\LoggerInterface;
class ContactController extends AbstractController
{
    #[Route('/api/contact', name: 'api_contact', methods: ['POST'])]
    public function contact(
        Request $request,
        MailerInterface $mailer,
        LoggerInterface $logger
    ): JsonResponse {
        $data = json_decode($request->getContent(), true);

        $firstName = $data['firstName'] ?? null;
        $lastName  = $data['lastName'] ?? null;
        $email     = $data['email'] ?? null;
        $subject   = $data['subject'] ?? null;
        $message   = $data['message'] ?? null;
        $rights    = $data['rights'] ?? false;

        $name = trim($firstName . ' ' . $lastName);
        
        if (!$email || !$message) {
            return new JsonResponse(['error' => 'Invalid input'], 400);
        }
        
        try {
            if ($rights === true) {
                // Send email using POST subject and message
                $emailMessage = (new Email())
                    ->from($_ENV['SULU_ADMIN_EMAIL'])
                    ->to($_ENV['MAILER_TO_EMAIL'])
                    ->subject($subject ?? 'Rights Request')
                    ->text($message);
            } else {
                // Existing behavior
                if (!$name) {
                    return new JsonResponse(['error' => 'Invalid input'], 400);
                }

                $emailMessage = (new Email())
                    ->from($_ENV['SULU_ADMIN_EMAIL'])
                    ->to($_ENV['MAILER_TO_EMAIL'])
                    ->subject('New Contact Form Submission')
                    ->text("Name: $name\nEmail: $email\nMessage: $message");
            }

            $mailer->send($emailMessage);

            return new JsonResponse(['success' => true, 'message' => 'Message sent']);
        } catch (\Exception $e) {
            $logger->error($e->getTraceAsString());

            return new JsonResponse([
                'error' => 'Failed to send message'
            ], 500);
        }
    }

}
