<?php
session_start();
$conn = mysqli_connect("localhost","root","","ecommerce");
if(!$conn){ die("DB Error"); }

if(isset($_POST['username'], $_POST['password'])){
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = $_POST['password'];

    $res = mysqli_query($conn,"SELECT * FROM admin_users WHERE username='$username' AND status=1 LIMIT 1");
    if($res && mysqli_num_rows($res) > 0){
        $user = mysqli_fetch_assoc($res);
        // Password is MD5 hashed in your example
        if(md5($password) === $user['password']){
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_username'] = $user['username'];
            $_SESSION['admin_role'] = $user['role'];
            header("Location: dashboard.php");
            exit;
        } else {
            header("Location: login.php?error=Invalid password");
            exit;
        }
    } else {
        header("Location: login.php?error=User not found or inactive");
        exit;
    }
} else {
    header("Location: login.php");
    exit;
}
