<?php
session_start();
include 'config.php';

if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $result = $conn->query("SELECT * FROM users WHERE username='$username'");
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if (password_verify($password, $row['password'])) {
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['role'] = $row['role'];
            $_SESSION['username'] = $row['username'];
            
            if($row['role'] == 'admin'){
                header("Location: admin/panel.php");
            } else {
                header("Location: dashboard.php");
            }
            exit();
        }
    }
    $error = "Invalid Credentials";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Sensi Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-900 text-white flex items-center justify-center h-screen">
    <div class="w-full max-w-md p-8 space-y-6 bg-gray-800 rounded-xl shadow-lg border border-gray-700">
        <h2 class="text-3xl font-bold text-center text-cyan-400">LOGIN</h2>
        <?php if(isset($error)) echo "<p class='text-red-500 text-center'>$error</p>"; ?>
        <form method="POST" class="space-y-4">
            <div>
                <label class="block mb-1 text-sm">Username</label>
                <input type="text" name="username" required class="w-full px-4 py-2 bg-gray-900 border border-gray-600 rounded focus:border-cyan-400 focus:outline-none">
            </div>
            <div>
                <label class="block mb-1 text-sm">Password</label>
                <input type="password" name="password" required class="w-full px-4 py-2 bg-gray-900 border border-gray-600 rounded focus:border-cyan-400 focus:outline-none">
            </div>
            <button type="submit" class="w-full py-3 font-bold text-black bg-cyan-400 rounded hover:bg-cyan-300">ENTER PORTAL</button>
        </form>
        <p class="text-center text-sm">Don't have an account? <a href="register.php" class="text-cyan-400">Register</a></p>
    </div>
</body>
</html>