<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../services/AuthService.php';

$pdo = db();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $email = trim($_POST['email']);
    $password = $_POST['password'];

    if (AuthService::login($pdo, $email, $password)) {
        header("Location: ../user/dashboard.php");
        exit;
    } else {
        $message = "Invalid email or password.";
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>

<div class="header">
    <h1>Trading Assistant</h1>
</div>

<div class="container">

    <div class="card" style="max-width:400px; margin:auto;">

        <h2>Login</h2>

        <?php if ($message): ?>
            <p style="color:red;"><?= htmlspecialchars($message) ?></p>
        <?php endif; ?>

        <form method="post">

            <label>Email</label><br>
            <input type="email" name="email" required><br><br>

            <label>Password</label><br>
            <input type="password" name="password" required><br><br>

            <button class="button">Login</button>

        </form>

        <hr style="margin:20px 0;">

        <p>
            Don't have an account?
            <a href="register.php">Register here</a>
        </p>

    </div>

</div>

</body>
</html>