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

$error = '';
$redirect = clean($_GET['redirect'] ?? '/account/dashboard.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = strtolower(trim($_POST['email'] ?? ''));
    $password = $_POST['password'] ?? '';
    if ($email && $password) {
        $db   = getDB();
        $stmt = $db->prepare("SELECT * FROM clients WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $client = $stmt->fetch();
        if ($client && password_verify($password, $client['password_hash'])) {
            loginClient((int)$client['id']);
            header('Location: ' . $redirect);
            exit;
        }
        $error = 'Incorrect email or password.';
    } else {
        $error = 'Please enter your email and password.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign In — Royal Luxe Grooming</title>
<link href="https://fonts.googleapis.com/css2?family=Cinzel+Decorative:wght@400;700&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="register">Create Account</a></li>
    </ul>
  </div>
</nav>
<div class="login-page">
  <div class="login-glow"></div>
  <div class="login-card">
    <img src="/assets/img/logo.png" alt="Royal Luxe" onerror="this.style.display='none'">
    <h1>Welcome Back</h1>
    <p>Sign in to your Royal Luxe account</p>
    <?php if ($error): ?><div class="login-error"><?= $error ?></div><?php endif; ?>
    <form method="POST">
      <input type="hidden" name="redirect" value="<?= clean($redirect) ?>">
      <div class="form-group">
        <label>Email Address</label>
        <input type="email" name="email" value="<?= clean($_POST['email'] ?? '') ?>" autocomplete="email" required>
      </div>
      <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" autocomplete="current-password" required>
      </div>
      <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;margin-top:.5rem">Sign In</button>
    </form>
    <p style="margin-top:1.25rem;font-size:.82rem;color:var(--white-muted)">
      No account? <a href="register" style="color:var(--purple-light);text-decoration:none">Create one free</a>
    </p>
  </div>
</div>
<script src="/assets/js/main.js"></script>
</body>
</html>
