<?php
require 'includes/db.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    //$email = strtolower(trim($_POST['email']));
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $merchant_key = uniqid('mer_');
    $secret_key = bin2hex(random_bytes(16));

    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, merchant_key, secret_key) VALUES (?, ?, ?, ?, ?)");

    try {
        $stmt->execute([$name, $email, $password, $merchant_key, $secret_key]);
        $_SESSION['user_id'] = $pdo->lastInsertId();
        header("Location: dashboard.php");
        exit();
    } catch (PDOException $e) {
        $error = "Email already exists.";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
</head>
<body class="container p-5">
    <h2>User Registration</h2>
    <?php if (isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>
    <form method="POST">
        <input name="name" class="form-control mb-2" placeholder="Name" required>
        <input type="text" name="username" class="form-control" placeholder="Enter Username" required>
        <input name="password" class="form-control mb-2" placeholder="Password" type="password" required>
        <button class="btn btn-primary">Register</button>
        <a href="login.php" class="btn btn-link">Login</a>
    </form>
</body>
</html>
