<?php
session_start();
require_once "config/db.php";

$error = "";

// ================= AUTO LOGIN =================
if(!isset($_SESSION['user_id']) && isset($_COOKIE['remember_token'])){

    $token = $_COOKIE['remember_token'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE remember_token=?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if($result->num_rows === 1){
        $user = $result->fetch_assoc();

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];

        header("Location: pages/dashboard.php");
        exit;
    }
}

// ================= LOGIN =================
if(isset($_POST['login'])){

    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $remember = isset($_POST['remember']);

    if(empty($username) || empty($password)){
        $error = "All fields are required";
    } else {

        $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if($result->num_rows === 1){
            $user = $result->fetch_assoc();

            if(password_verify($password, $user['password'])){

                session_regenerate_id(true);

                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];

                // ================= REMEMBER ME =================
                if($remember){
                    $token = bin2hex(random_bytes(32));

                    setcookie("remember_token", $token, time() + (86400 * 30), "/"); // 30 days

                    $stmt = $conn->prepare("UPDATE users SET remember_token=? WHERE id=?");
                    $stmt->bind_param("si", $token, $user['id']);
                    $stmt->execute();
                }

                header("Location: pages/dashboard.php");
                exit;

            } else {
                $error = "Invalid credentials";
            }
        } else {
            $error = "Invalid credentials";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

<style>
body {
    background: linear-gradient(135deg, #3a7bd5, #00d2ff);
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.login-card {
    width: 100%;
    max-width: 380px;
    border-radius: 15px;
    padding: 25px;
    background: #fff;
}

.logo img {
    max-width: 120px;
}

.input-group-text {
    background: #f1f1f1;
}

.btn-primary {
    background: #3a7bd5;
    border: none;
}
</style>
</head>

<body>

<div class="login-card shadow">

    <!-- LOGO -->
    <div class="text-center logo mb-3">
        <img src="assets/images/logo.png" style="max-width:200px;">
        <h5 class="mt-2">Let's Get Started</h5>
        <small class="text-muted">Sign in to continue</small>
    </div>

    <!-- ERROR -->
    <?php if(!empty($error)){ ?>
        <div class="alert alert-danger text-center">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php } ?>

    <!-- FORM -->
    <form method="POST">

        <!-- Username -->
        <div class="input-group mb-3">
            <span class="input-group-text">
                <i class="fa fa-user"></i>
            </span>
            <input type="text" name="username" class="form-control" placeholder="Username" required>
        </div>

        <!-- Password -->
        <div class="input-group mb-3">
            <span class="input-group-text">
                <i class="fa fa-lock"></i>
            </span>
            <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>

            <span class="input-group-text" onclick="togglePassword()" style="cursor:pointer;">
                <i class="fa fa-eye"></i>
            </span>
        </div>

        <!-- Remember -->
        <div class="form-check mb-3">
            <input type="checkbox" name="remember" class="form-check-input">
            <label class="form-check-label">Remember Me</label>
        </div>

        <!-- Button -->
        <button class="btn btn-primary w-100" name="login">
            SIGN IN
        </button>

    </form>

    <!-- Forgot -->
    <div class="text-center mt-3">
        <a href="forgot_password.php" class="text-decoration-none">Forgot Password?</a>
    </div>

</div>

<script>
function togglePassword(){
    const input = document.getElementById("password");
    input.type = input.type === "password" ? "text" : "password";
}
</script>

</body>
</html>

