<?php

require_once __DIR__ . '/partials/header.php';

if (is_logged_in()) {
    header('Location: index.php');
    exit();
}

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__ . '/auth.php';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';

    $user = login($email, $password);

    if ($user) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_role'] = $user['role'];
        header('Location: index.php');
        exit();
    } else {
        $error = 'Invalid email or password.';
    }
}
?>

<div class="container-fluid vh-100 d-flex justify-content-center align-items-center bg-light-gradient">
    <div class="col-11 col-sm-8 col-md-6 col-lg-5 col-xl-4">
        <div class="card shadow-lg border-0 rounded-4">
            <div class="card-body p-4 p-sm-5">
                <div class="text-center mb-4">
                    <h1 class="h2 fw-bold">Welcome Back</h1>
                    <p class="text-muted">Login to access your Drillex account.</p>
                </div>

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

                <form action="login.php" method="POST">
                    <div class="form-floating mb-3">
                        <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com" required>
                        <label for="email">Email address</label>
                    </div>

                    <div class="form-floating mb-4">
                        <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
                        <label for="password">Password</label>
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg rounded-pill">Login</button>
                    </div>
                </form>

                <div class="text-center mt-4">
                    <p class="text-muted mb-2">or</p>
                    <a href="hybridauth_login.php?provider=Google" class="btn btn-outline-dark btn-lg rounded-pill w-100">
                        <i class="bi bi-google me-2"></i> Sign in with Google
                    </a>
                </div>
                <div class="text-center mt-4">
                    <p class="mb-0">Don't have an account? <a href="register.php" class="fw-bold text-decoration-none">Sign up</a></p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/partials/footer.php'; ?>