<?php
session_start();
$servername = "localhost"; 
$username = "s2300379_g5pharmaease";
$password = "12345";
$dbname = "s2300379_g5pharmaease";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = mysqli_connect($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Get form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $inputPassword = trim($_POST['password']); // Trim whitespace
    $number = $_POST['number'];

    // Check if the email already exists in the database
    $checkQuery = "SELECT id FROM admin_records WHERE email = ?";
    $checkStmt = $conn->prepare($checkQuery);
    $checkStmt->bind_param('s', $email);
    $checkStmt->execute();
    $checkStmt->store_result();

    if ($checkStmt->num_rows > 0) {
        echo "<script>alert('Email already exists. Please use a different email.');</script>";
    } else {
        // Insert the new user into the database (with plain text password)
        $insertQuery = "INSERT INTO admin_records (name, email, password, number) VALUES (?, ?, ?, ?)";
        $insertStmt = $conn->prepare($insertQuery);
        $insertStmt->bind_param('ssss', $name, $email, $inputPassword, $number);

        if ($insertStmt->execute()) {
            echo "<script>alert('Registration successful!'); window.location='index.php';</script>";
        } else {
            echo "<script>alert('Error: " . $insertStmt->error . "');</script>";
        }

        $insertStmt->close();
    }

    // Close the statement and connection
    $checkStmt->close();
    $conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="custom.css?<?php echo time();?>">
</head>
<body>
    <br><br><br><br><br><br><br><br><br><br>
    <div id="login-block">
        <h2>Register</h2>
        <form method="POST" action="" name="register">
            <div>
                <input type="text" class="input" required name="name" placeholder="Full Name" required/>
            </div>
            <div>
                <input type="email" class="input" required name="email" placeholder="Valid E-mail" required/>
            </div>
            <div>
                <input type="password" class="input" required name="password" placeholder="Password" required/>
            </div>
            <div>
                <input type="text" class="input" required name="number" placeholder="Phone Number" required/>
            </div>
            <div style="margin-top: 0px;">
                <button type="submit">Register</button>
            </div>
            <p>Already have an account? <a href="index.php">Login here</a></p>
        </form>
    </div>
</body>
</html>