<?php
require_once '../../includes/config.php';
// Redirect if already logged in
if (getClientFromSession()) { header('Location: /account/dashboard'); exit; }

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email     = strtolower(trim($_POST['email'] ?? ''));
    $password  = $_POST['password'] ?? '';
    $confirm   = $_POST['confirm_password'] ?? '';
    $first     = clean($_POST['first_name'] ?? '');
    $last      = clean($_POST['last_name'] ?? '');
    $phone     = clean($_POST['phone'] ?? '');
    $referral  = strtoupper(trim($_POST['referral_code'] ?? ''));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL))   $error = 'Invalid email address.';
    elseif (strlen($password) < 8)                    $error = 'Password must be at least 8 characters.';
    elseif ($password !== $confirm)                   $error = 'Passwords do not match.';
    elseif (!$first || !$last)                        $error = 'First and last name required.';
    elseif (!$phone)                                  $error = 'Phone number required.';
    else {
        $db = getDB();
        $exists = $db->prepare("SELECT id FROM clients WHERE email = ?");
        $exists->execute([$email]);
        if ($exists->fetch()) {
            $error = 'An account with that email already exists.';
        } else {
            $refClient = null;
            if ($referral) {
                $refStmt = $db->prepare("SELECT id FROM clients WHERE referral_code = ?");
                $refStmt->execute([$referral]);
                $refClient = $refStmt->fetchColumn();
            }
            $hash    = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
            $myCode  = strtoupper(substr(md5($email . time()), 0, 8));
            $stmt = $db->prepare("
                INSERT INTO clients (email, password_hash, first_name, last_name, phone, referral_code, referred_by, verified, points)
                VALUES (?, ?, ?, ?, ?, ?, ?, 1, 50)
            ");
            $stmt->execute([$email, $hash, $first, $last, $phone, $myCode, $refClient ?: null]);
            $newId = $db->lastInsertId();

            // Welcome points
            awardPoints($newId, 50, 'manual', 'Welcome bonus — thanks for joining Royal Luxe!');

            // Referral bonus
            if ($refClient) {
                awardPoints((int)$refClient, 100, 'earn_referral', "Referral bonus — $first $last joined!");
            }

            loginClient($newId);
            header('Location: /account/dashboard?welcome=1');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Account — Royal Luxe Grooming</title>
<link href="https://fonts.googleapis.com/css2?family=Cinzel+Decorative:wght@400;700&family=Cormorant+Garamond:wght@300;400&family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/main.css">
</head>
<body>
<canvas id="particles"></canvas>
<nav class="nav scrolled">
  <div class="nav-inner">
    <a href="/index.php" class="nav-logo">
      <img src="/assets/img/logo.png" alt="Royal Luxe" width="44" onerror="this.style.display='none'">
      <span class="nav-logo-text">Royal Luxe</span>
    </a>
    <ul class="nav-links">
      <li><a href="/index.php">Home</a></li>
      <li><a href="login">Sign In</a></li>
    </ul>
  </div>
</nav>

<div style="min-height:100vh;display:flex;align-items:center;justify-content:center;padding:120px 2rem 4rem;position:relative;z-index:1">
  <div style="background:var(--black-card);border:1px solid var(--black-border);border-radius:var(--radius-lg);padding:2.5rem;width:100%;max-width:480px">
    <div style="text-align:center;margin-bottom:2rem">
      <img src="/assets/img/logo.png" width="60" alt="Royal Luxe" onerror="this.style.display='none'">
      <h1 style="font-size:1.3rem;margin-top:.75rem">Create Your Account</h1>
      <p style="color:var(--white-muted);font-size:.85rem">Earn points on every visit. Save your pets. Book faster.</p>
    </div>

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

    <form method="POST">
      <div class="form-row">
        <div class="form-group">
          <label>First Name *</label>
          <input type="text" name="first_name" value="<?= clean($_POST['first_name'] ?? '') ?>" required>
        </div>
        <div class="form-group">
          <label>Last Name *</label>
          <input type="text" name="last_name" value="<?= clean($_POST['last_name'] ?? '') ?>" required>
        </div>
      </div>
      <div class="form-group">
        <label>Email Address *</label>
        <input type="email" name="email" value="<?= clean($_POST['email'] ?? '') ?>" required>
      </div>
      <div class="form-group">
        <label>Phone Number *</label>
        <input type="tel" name="phone" value="<?= clean($_POST['phone'] ?? '') ?>" required>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Password *</label>
          <input type="password" name="password" minlength="8" required>
        </div>
        <div class="form-group">
          <label>Confirm Password *</label>
          <input type="password" name="confirm_password" required>
        </div>
      </div>
      <div class="form-group">
        <label>Referral Code <span style="color:var(--white-muted)">(optional)</span></label>
        <input type="text" name="referral_code" value="<?= clean($_POST['referral_code'] ?? '') ?>" placeholder="Friend's code" style="text-transform:uppercase">
      </div>
      <div style="background:var(--black-soft);border:1px solid var(--black-border);border-radius:var(--radius);padding:.85rem 1rem;margin-bottom:1.5rem;font-size:.8rem;color:var(--white-muted)">
        🎁 Get <strong style="color:var(--gold)">50 points free</strong> just for joining — worth $0.50 off your next visit!
      </div>
      <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center">
        Create Account
      </button>
    </form>
    <p style="text-align:center;margin-top:1.25rem;font-size:.82rem;color:var(--white-muted)">
      Already have an account? <a href="login" style="color:var(--purple-light);text-decoration:none">Sign in</a>
    </p>
  </div>
</div>
<script src="/assets/js/main.js"></script>
</body>
</html>
