<?php
header("Content-Type: application/json");

// Configuración de la base de datos
$servername = "localhost";
$username = "toshko";
$password = "19750705t";
$dbname = "toshko_db";

// Conexión a la base de datos
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    sendResponse(false, "Conexión fallida: " . $conn->connect_error);
}

// Leer los datos enviados por el cliente
$data = json_decode(file_get_contents("php://input"), true);
$email = $data['email'] ?? null;
$name = $data['name'] ?? null;
$lastName = $data['lastName'] ?? null;
$age = $data['age'] ?? null;
$password = $data['password'] ?? null;

// Validar los campos
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(false, "Invalid email.");
}
if (empty($name) || empty($lastName) || !is_numeric($age) || empty($password)) {
    sendResponse(false, "All fields are required and valid.");
}

// Validar si el correo ya está registrado
$sql = "SELECT id FROM Users WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
    sendResponse(false, "The email is already registered.");
}

// Generar un token de confirmación
$confirmationToken = bin2hex(random_bytes(16));

// Encriptar la contraseña
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

// Inicializar moonCoint con 0.0000000 y formatear con 7 decimales
$initialMoonCoint = number_format(0, 7, '.', '');

// Insertar el nuevo usuario en la base de datos
$sql = "INSERT INTO Users (email, name, lastName, age, password, moonCoint, confirmationToken, isActive) 
        VALUES (?, ?, ?, ?, ?, ?, ?, 0)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssisss", $email, $name, $lastName, $age, $hashedPassword, $initialMoonCoint, $confirmationToken);

if ($stmt->execute()) {
    // Enviar el correo de confirmación
    if (sendConfirmationEmail($email, $name, $confirmationToken)) {
        sendResponse(true, "User registered successfully. Check your email to confirm your account.");
    } else {
        sendResponse(false, "Registered user, but an error occurred while sending the confirmation email.");
    }
} else {
    sendResponse(false, "Error registering user: " . $stmt->error);
}

$conn->close();

// Funciones auxiliares
function sendResponse($success, $message, $data = null) {
    echo json_encode(["success" => $success, "message" => $message, "data" => $data]);
    exit;
}

function sendConfirmationEmail($email, $name, $token) {
    $subject = "Confirm Your Moon Miner Account";

    $message = "
    <html>
    <head>
        <style>
            body {
                font-family: Arial, sans-serif;
                background-color: #f4f4f9;
                margin: 0;
                padding: 0;
            }
            .email-container {
                max-width: 600px;
                margin: 20px auto;
                background-color: #ffffff;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                overflow: hidden;
            }
            .header {
                background-color: #FE59C2;
                color: #ffffff;
                padding: 20px;
                text-align: center;
            }
            .header h1 {
                margin: 0;
                font-size: 24px;
            }
            .content {
                padding: 20px;
                color: #333333;
            }
            .content p {
                margin: 15px 0;
                line-height: 1.6;
            }
            .content a {
                display: inline-block;
                margin-top: 20px;
                padding: 10px 20px;
                color: #ffffff;
                background-color: #FE59C2;
                text-decoration: none;
                font-weight: bold;
                border-radius: 4px;
            }
            .content a:hover {
                background-color: #d14fa5;
            }
            .footer {
                text-align: center;
                padding: 15px;
                background-color: #f4f4f9;
                font-size: 12px;
                color: #777777;
            }
            .footer a {
                color: #FE59C2;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
        <div class='email-container'>
            <div class='header'>
                <h1>Welcome to Moon Miner</h1>
            </div>
            <div class='content'>
                <p>Hello <strong>$name</strong>,</p>
                <p>Thank you for registering with <strong>Moon Miner</strong>. We're thrilled to have you on board!</p>
                <p>Please confirm your account by clicking the button below:</p>
                <a href='https://neyktosoft.com/moonminer369/confirm.php?token=$token'>Confirm My Account</a>
                <p>If you did not request this registration, you can safely ignore this email.</p>
            </div>
            <div class='footer'>
                <p>&copy; " . date('Y') . " Moon Miner. All rights reserved.</p>
                <p><a href='https://neyktosoft.com'>Visit our website</a></p>
            </div>
        </div>
    </body>
    </html>";

    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "From: no-reply@neyktosoft.com\r\n";

    return mail($email, $subject, $message, $headers);
}
?>
