<?php
// 1. Incluir el archivo de configuración centralizado
require_once __DIR__ . '/../config.php';
// 2. Lógica específica de la página
$pageTitle = $translations["contactpage"];
$currentPage = 'contact';
$alerts_html = '';

require_once __DIR__ . '/../vendor/autoload.php';

//Se comento por error en la carga de SwiftMailer
// use Swift_SmtpTransport;
//use Swift_Mailer;
//use Swift_Message;


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $recaptcha_response = $_POST['g-recaptcha-response'];
    $recaptcha_secret = $recaptcha_secret_key;
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_data = [
        'secret' => $recaptcha_secret,
        'response' => $recaptcha_response
    ];

    $options = [
        'http' => [
            'header' => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'content' => http_build_query($recaptcha_data)
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($recaptcha_url, false, $context);
    $result_json = json_decode($result, true);

    if ($result_json['success']) {
        $name = $_POST['name'];
        $userEmail = $_POST['email'];
        $userMessage = $_POST['message'];

        $transport = (new Swift_SmtpTransport($smtp_host, $smtp_port, $smtp_encryption))
            ->setUsername($smtp_username)
            ->setPassword($smtp_password);

        $mailer = new Swift_Mailer($transport);

        $adminMessage = (new Swift_Message($translations["newmessagefromwebsite"]))
            ->setFrom([$userEmail => $name])
            ->setTo([$smtp_username])
            ->setBody(
                $translations["fullname"] . ": " . $name . "\n" .
                $translations["email"] . ": " . $userEmail . "\n" .
                $translations["message"] . ": " . $userMessage . "\n"
            );

        $result = $mailer->send($adminMessage);

        // Obtener la plantilla de correo electrónico
        $emailTemplate = file_get_contents(__DIR__ . '/../assets/templates/email/contact_user_confirmation.html');

        // Reemplazar los marcadores de posición con datos reales
        $emailContent = str_replace(
            ['{{domain_url}}', '{{business_name}}', '{{dear}}', '{{name}}', '{{smtpcontactcontent}}', '{{userMessage}}'],
            [$domain_url, $business_name, $translations['dear'], $name, $translations['smtpcontactcontent'], $userMessage],
            $emailTemplate
        );

        $userConfirmationMessage = (new Swift_Message($translations["thankyouforyouremail"]))
            ->setFrom([$smtp_username => $business_name])
            ->setTo([$userEmail])
            ->setBody($emailContent, 'text/html');

        $resultUser = $mailer->send($userConfirmationMessage);

        if ($result && $resultUser) {
            $alerts_html .= '<div class="alert alert-success" role="alert">
                                    ' . $translations["successsndedemail"] . '
                                </div>';
            header("Refresh:2");
        } else {
            $alerts_html .= '<div class="alert alert-danger" role="alert">
                                    ' . $translations["unexpected-error"] . '
                                </div>';
            header("Refresh:2");
        }
    } else {
        $alerts_html .= '<div class="alert alert-danger" role="alert">
                                ' . $translations["recaptcha-error"] . '
                            </div>';
    }
}
?>

<?php
// 3. Incluir la cabecera
require_once __DIR__ . '/../assets/templates/header.php';

// 4. Incluir el contenido de la página
require_once __DIR__ . '/../templates/pages/contact.php';

// 5. Incluir la plantilla del pie de página reutilizable
require_once __DIR__ . '/../assets/templates/footer.php';
?>