<?php
require_once 'includes/User.php';

$msg = '';
$msgType = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $nm = $_POST["name"] ?? '';
    $em = $_POST["email"] ?? '';
    $pw = $_POST["password"] ?? '';
    $ph = $_POST["phone"] ?? '';
    $addr = $_POST["adress"] ?? '';
    
    if (empty($nm) || empty($em) || empty($pw)) {
        $msg = 'Please fill in all required fields';
        $msgType = 'error';
    } elseif (!filter_var($em, FILTER_VALIDATE_EMAIL)) {
        $msg = 'Please enter a valid email address';
        $msgType = 'error';
    } elseif (strlen($pw) < 6) {
        $msg = 'Password must be at least 6 characters long';
        $msgType = 'error';
    } else {
        $u = new User();
        $res = $u->register($nm, $em, $pw, $ph, $addr);
        
        if ($res['success']) {
            $msg = $res['message'];
            $msgType = 'success';
            header("Location: /allura/login.php?registered=1");
            exit();
        } else {
            $msg = $res['message'];
            $msgType = 'error';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Account - Allura Dry Clean</title>
    <?php include 'includes/header.php'; ?>
</head>
<body>
    <div class="login-box">
        <h2>Create Account</h2>

        <?php if (!empty($msg)): ?>
            <p class="<?php echo $msgType; ?>-message"><?php echo htmlspecialchars($msg); ?></p>
        <?php endif; ?>

        <form method="POST" action="">
            <input type="text" name="name" placeholder="Full Name" required><br>
            <input type="email" name="email" placeholder="Email Address" required><br>
            <input type="password" name="password" placeholder="Password (min. 6 characters)" required><br>
            <input type="text" name="phone" placeholder="Phone Number"><br>
            <input type="text" name="adress" placeholder="Address"><br>
      
            <button type="submit" class="btn">Register</button>
        </form>

        <p class="register-text">
            If you have an account! 
            <a href="/allura/login.php">Login</a>
        </p>
    </div>
    <?php include 'includes/footer.php'; ?>
</body>
</html>