<?php
include 'config/config.php';

// Clear any previous errors on fresh load
$error = "";

if (isset($_POST['login'])) {
    // Trim both username and password to remove accidental spaces
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    // Debugging: If this still fails, we can check the strings
    if ($user && password_verify($password, $user['password'])) {
        session_regenerate_id(true);
        $_SESSION['user_id']   = $user['id'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['role']      = $user['role'];

        $update = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
        $update->execute([$user['id']]);

        header("Location: " . ($_SESSION['role'] == 'admin' ? "admin/dashboard.php" : "member/dashboard.php"));
        exit();
    } else {
        $error = "Invalid credentials.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login | Internal teledrama Ratings</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="d-flex align-items-center justify-content-center" style="min-height: 100vh; background: #141414;">

<div class="card bg-dark border-secondary p-4" style="width: 350px;">
    <h2 class="text-danger text-center fw-bold">SIGN IN</h2>
    <?php if($error) echo "<div class='alert alert-danger py-1 small'>$error</div>"; ?>
    
    <form method="POST" autocomplete="off">
        <div class="mb-3">
            <label class="text-white-50 small">Username</label>
            <input type="text" name="username" class="form-control bg-dark text-white border-secondary" required>
        </div>
        <div class="mb-3">
            <label class="text-white-50 small">Password</label>
            <input type="password" name="password" class="form-control bg-dark text-white border-secondary" required>
        </div>
        <button type="submit" name="login" class="btn btn-danger w-100 fw-bold">LOG IN</button>
    </form>
</div>

</body>
</html>