<?php
session_start();
include '../database/db.php';

/* Ziņojums pēc veiksmīgas reģistrācijas */
$success_message = "";

if (isset($_GET['registered'])) {
    $success_message = "Registration successful! Please login.";
}

/* Pieteikšanās formas apstrāde */
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    /* Iegūstam ievadītos datus */
    $email = $_POST['email'];
    $password = $_POST['password'];

    /* Meklējam lietotāju pēc e-pasta */
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    /* Pārbaudām, vai lietotājs eksistē un parole sakrīt */
    if ($user && password_verify($password, $user['password_hash'])) {

        /* Saglabājam lietotāja datus sesijā */
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['name'] = $user['name'];

        /* Novirzām uz dashboard */
        header("Location: ../dashboard.php");
        exit();

    } else {
        /* Kļūda, ja e-pasts vai parole nav pareizi */
        $error_message = "Incorrect email or password!";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Work Planner</title>
    <link rel="stylesheet" href="../css/users.css">
</head>
<body>
<div class="form-container">
    <h2>Login</h2>

    <?php if (!empty($success_message)): ?>
        <p class="success"><?= htmlspecialchars($success_message) ?></p>
    <?php endif; ?>

    <?php if (isset($error_message)): ?>
        <p class="error"><?= htmlspecialchars($error_message) ?></p>
    <?php endif; ?>

    <form action="login.php" method="post">
        <label for="email">Email</label>
        <input type="email" name="email" id="email" required>

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

        <button type="submit">Login</button>
    </form>
    
    <p class="form-footer">Don't have an account? <a href="register.php">Register here</a></p>
</div>
</body>
</html>