<?php
// Include config file
require_once '../../../4p1c_4cc45t0db._.php';

// Create a database connection
$conn = Database::connect();

// Define variables and initialize with empty values
$mail = $psswd = $confirm_psswd = $entity = "";
$mail_err = $psswd_err = $confirm_psswd_err = "";

// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validate email
    if (empty(trim($_POST["mail"]))) {
        $mail_err = "Por favor ingrese un correo.";
    } elseif (!filter_var(trim($_POST["mail"]), FILTER_VALIDATE_EMAIL)) {
        $mail_err = "Ingrese un correo válido.";
    } else {
        // Check if email is already registered
        $sql = "SELECT id FROM user WHERE mail = ?";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("s", $param_mail);
            $param_mail = trim($_POST["mail"]);
            if ($stmt->execute()) {
                $stmt->store_result();
                if ($stmt->num_rows > 0) {
                    $mail_err = "Este correo ya está registrado.";
                } else {
                    $mail = trim($_POST["mail"]);
                }
            } else {
                echo "Algo salió mal, inténtelo más tarde.";
            }
            $stmt->close();
        }
    }

    // Validate password
    if (empty(trim($_POST["psswd"]))) {
        $psswd_err = "Por favor ingrese una contraseña.";
    } elseif (strlen(trim($_POST["psswd"])) < 6) {
        $psswd_err = "La contraseña debe tener al menos 6 caracteres.";
    } else {
        $psswd = trim($_POST["psswd"]);
    }

    // Validate confirm password
    if (empty(trim($_POST["confirm_psswd"]))) {
        $confirm_psswd_err = "Por favor confirme la contraseña.";
    } else {
        $confirm_psswd = trim($_POST["confirm_psswd"]);
        if (empty($psswd_err) && ($psswd != $confirm_psswd)) {
            $confirm_psswd_err = "Las contraseñas no coinciden.";
        }
    }

    // Check for errors before inserting into database
    if (empty($mail_err) && empty($psswd_err) && empty($confirm_psswd_err)) {
        $sql = "INSERT INTO user (mail, psswd, entity) VALUES (?, ?, ?)";
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("sss", $param_mail, $param_psswd, $param_entity);
            $param_mail = $mail;
            $param_psswd = password_hash($psswd, PASSWORD_DEFAULT); // Hash the password
            $param_entity = '3e6a0eac-ed86-4124-be4e-e546b69c3915'; // Default entity

            if ($stmt->execute()) {
                header("location: login.php");
            } else {
                echo "Algo salió mal, inténtelo más tarde.";
            }
            $stmt->close();
        }
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Registro</title>
    <link rel="stylesheet" href="style/style.css">
</head>

<body>
    <div class="card">
        <div class="tittleLogin">Registrar</div>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="formLogin">
            <div class="formLoginItem <?php echo (!empty($mail_err)) ? 'has-error' : ''; ?>">
                <label>Email</label>
                <input type="text" name="mail" class="form-control" value="<?php echo $mail; ?>">
                <span class="error"><?php echo $mail_err; ?></span>
            </div>
            <div class="formLoginItem <?php echo (!empty($psswd_err)) ? 'has-error' : ''; ?>">
                <label>Contraseña</label>
                <input type="password" name="psswd" class="form-control">
                <span class="error"><?php echo $psswd_err; ?></span>
            </div>
            <div class="formLoginItem <?php echo (!empty($confirm_psswd_err)) ? 'has-error' : ''; ?>">
                <label>Confirmar Contraseña</label>
                <input type="password" name="confirm_psswd" class="form-control">
                <span class="error"><?php echo $confirm_psswd_err; ?></span>
            </div>
            <div class="formLoginItem">
                <input type="submit" class="btn" value="Registrar">
            </div>
        </form>
    </div>
</body>

</html>
