<?php
// admin/register.php
session_start();
require_once __DIR__ . '/../inc/db.php';

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST['name'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';

    if (!$name || !$email || !$password || !$confirm) {
        $msg = "All fields are required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msg = "Invalid email format";
    } elseif ($password !== $confirm) {
        $msg = "Password and Confirm Password do not match";
    } else {
        // check if email already exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE email=?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $msg = "Email already exists!";
        } else {
            $hash  = password_hash($password, PASSWORD_BCRYPT);
            $token = bin2hex(random_bytes(32));
            $insert = $conn->prepare("INSERT INTO users (name,email,password,api_token) VALUES (?,?,?,?)");
            $insert->bind_param("ssss", $name, $email, $hash, $token);
            if ($insert->execute()) {
                $msg = "✅ Registration successful. <a href='login.php'>Login here</a>";
            } else {
                $msg = "Database error: ".$conn->error;
            }
            $insert->close();
        }
        $stmt->close();
    }
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Register</title>
</head>
<body>
<h2>Admin Panel - New User Registration</h2>
<?php if($msg) echo "<p style='color:blue;'>".htmlspecialchars($msg)."</p>"; ?>
<form method="post">
  <label>Name</label><br>
  <input type="text" name="name" required><br><br>
  
  <label>Email</label><br>
  <input type="email" name="email" required><br><br>
  
  <label>Password</label><br>
  <input type="password" name="password" required><br><br>
  
  <label>Confirm Password</label><br>
  <input type="password" name="confirm_password" required><br><br>
  
  <button type="submit">Register</button>
</form>
<p><a href="login.php">Back to Login</a></p>
</body>
</html>
