<?php
session_start();

// 1. Incluir el archivo de configuración centralizado
require_once '../config.php';
require_once '../vendor/autoload.php'; // COMPOSER!
// 2. Lógica específica de la página
$pageTitle = $translations["register"];
$currentPage = 'register';
$alerts_html = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $gender = $_POST['gender'];
    $birthdate = $_POST['birthdate'];
    $city = $_POST['city'];
    $street = $_POST['street'];
    $house_number = $_POST['house_number'];
    if ($password !== $confirm_password) {
        $alerts_html .= '<div class="alert alert-danger">' . $translations["twopasswordnot"] . '</div>';
        header("Refresh: 5");
    } else {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        $userid = rand(pow(10, 9), pow(10, 10) - 1);

        $confirmed = 'No';

        $registration_date = date('Y-m-d H:i:s');

        $stmt = $conn->prepare("INSERT INTO users (userid, firstname, lastname, email, password, gender, birthdate, city, street, house_number, registration_date, confirmed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        if ($stmt === false) {
            $alerts_html .= '<div class="alert alert-danger">' . $translations["error-prepared-statement"] . $conn->error . '</div>';
        } else {
            $stmt->bind_param("isssssssssss", $userid, $firstname, $lastname, $email, $hashed_password, $gender, $birthdate, $city, $street, $house_number, $registration_date, $confirmed);

            if ($stmt->execute()) {
                $alerts_html .= '<div class="alert alert-success">' . $translations["successful-registration"] . '</div>';
                header("Refresh: 5");
                $transport = (new Swift_SmtpTransport($smtp_host, $smtp_port, $smtp_encryption))
                    ->setUsername($smtp_username)
                    ->setPassword($smtp_password);

                $mailer = new Swift_Mailer($transport);

                $emailTemplate = file_get_contents(__DIR__ . '/../assets/templates/email/registration_confirmation.html');

                $emailContent = str_replace(
                    ['{{domain_url}}', '{{business_name}}', '{{confiremailbody}}', '{{userid}}', '{{regconfirmbtn}}'],
                    [$domain_url, $business_name, $translations['confiremailbody'], $userid, $translations['regconfirmbtn']],
                    $emailTemplate
                );

                $recipientEmail = $email;
                $subject = $translations["confirmemailmailsub"];

                $isRegistrationSuccessful = true;

                if ($isRegistrationSuccessful) {
                    $message = (new Swift_Message($subject))
                        ->setFrom(["{$smtp_username}" => "{$business_name} - {$translations['confirmemailpage']}"])
                        ->setTo([$recipientEmail])
                        ->setBody($emailContent, 'text/html');
                }
                $result = $mailer->send($message);
                header("Refresh: 5");
            }

            $stmt->close();
        }
        $conn->close();
    }
}

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

?>