<?php
include 'config.php';
$message = "";

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

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

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

        if (password_verify($pass, $user['password'])) {
            $_SESSION['username'] = $user['username'];
            $_SESSION['name'] = $user['name'];
            $_SESSION['user_category'] = !empty($user['user_category']) ? $user['user_category'] : 'Normal';

            if ($_SESSION['user_category'] === 'Admin') {
                header("Location: dashboard.php");
            } else {
                header("Location: sale.php");
            }
            exit();
        } else {
            $message = "Invalid password.";
        }
    } else {
        $message = "User not found.";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi SewaPiyasa-Login</title>
    <link rel="stylesheet" href="assets/style.css">
    <style>
        .login-logo-wrap{
            text-align:center;
            margin-bottom:12px;
        }
        .login-logo-wrap img{
            width:120px;
            height:120px;
            object-fit:contain;
            display:inline-block;
        }
        .auth-card p{
            text-align:center;
            margin-top:2px;
            font-size:0.92rem;
        }
        .auth-card p a{
            color:#1f7a3f;
            font-weight:750;
            text-decoration:none;
        }
        .auth-card p a:hover{
            text-decoration:underline;
        }
    </style>
</head>
<body class="auth-body">
<div class="auth-card">
    <div class="login-logo-wrap">
        <img src="logo/logo_color1.png" alt="Krushi Sewa Piyasa Logo">
    </div>

    <h2>Krushi Sewa Piyasa - Login</h2>

    <?php if($message) echo "<div class='alert'>$message</div>"; ?>

    <form method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>

    <p>No account? <a href="register.php">Register</a></p>
</div>
</body>
</html>