<?php
require_once __DIR__ . "/../includes/config.php";
require_once __DIR__ . "/../includes/functions.php";

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name  = trim($_POST['name'] ?? '');
  $email = strtolower(trim($_POST['email'] ?? ''));
  $pass  = $_POST['password'] ?? '';

  // Name validation (alphabets only)
  if (!preg_match("/^[A-Za-z ]+$/", $name)) {
    $error = "Name must contain only alphabets.";
  }
  elseif (strlen($pass) < 6) {
    $error = "Password must be at least 6 characters.";
  }
  else {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email=?");
    $stmt->execute([$email]);

    if ($stmt->fetch()) {
      $error = "Email already registered. Please login.";
    } else {
      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare(
        "INSERT INTO users (name,email,password_hash) VALUES (?,?,?)"
      );
      $stmt->execute([$name,$email,$hash]);

      $success = "Account created successfully. Please login.";
      header("refresh:2;url=/myukstore/auth/login.php");
    }
  }
}

include __DIR__ . "/../includes/header.php";
?>

<h3 class="mb-3">Create Account</h3>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<?php if ($success): ?>
  <div class="alert alert-success"><?= e($success) ?></div>
<?php endif; ?>

<form method="post">
  <input class="form-control mb-2" name="name" placeholder="Full Name" required>
  <input class="form-control mb-2" name="email" type="email" placeholder="Email" required>
  <input class="form-control mb-2" name="password" type="password" placeholder="Password (min 6 chars)" required>
  <button class="btn btn-warning w-100">Signup</button>
</form>

<p class="mt-3">
  Already have an account?
  <a href="/myukstore/auth/login.php">Login</a>
</p>

<?php include __DIR__ . "/../includes/footer.php"; ?>
