<?php

declare(strict_types=1);

session_start();

if (isset($_SESSION['client_user'])) {
    header('Location: account.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require __DIR__ . '/../api/db.php';

    try {
        $database = new MattressDatabase();
        $user = $database->loginUser((string)$_POST['email'], (string)$_POST['password']);
        $_SESSION['client_user'] = $user;
        header('Location: account.php');
        exit;
    } catch (Throwable $exception) {
        $error = $exception->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client Login | Dr. Mattress</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; background: #f7f5f0; display: grid; place-items: center; min-height: 100vh; }
        .card { width: min(90vw, 420px); background: #fff; padding: 30px; border-radius: 14px; box-shadow: 0 10px 30px rgba(0,0,0,0.08); }
        h1 { margin-bottom: 12px; color: #202d2b; }
        p { color: #71807a; margin-bottom: 20px; }
        label { display: block; font-weight: 600; margin-bottom: 8px; }
        input { width: 100%; padding: 12px 14px; margin-bottom: 16px; border-radius: 8px; border: 1px solid #ddd; }
        button { width: 100%; padding: 12px; background: #31594c; color: #fff; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; }
        .error { background: #fee2e2; color: #991b1b; padding: 10px 12px; border-radius: 8px; margin-bottom: 16px; }
        .link { margin-top: 16px; display: block; text-align: center; color: #31594c; }
    </style>
</head>
<body>
    <div class="card">
        <h1>Client login</h1>
        <p>Sign in to track your orders and manage your account.</p>

        <?php if ($error !== ''): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <label for="email">Email</label>
            <input id="email" name="email" type="email" placeholder="you@example.com" required>

            <label for="password">Password</label>
            <input id="password" name="password" type="password" placeholder="Enter your password" required>

            <button type="submit">Login</button>
        </form>

        <a class="link" href="register.php">Create a new account</a>
    </div>
</body>
</html>
