<?php
session_start();
require 'db_connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT user_id, username, password, role 
            FROM users 
            WHERE username = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {

        $stmt->bind_result($user_id, $db_username, $db_password, $role);
        $stmt->fetch();

        if (password_verify($password, $db_password)) {

            /* 🔒 CHECK ROLE */
            if ($role !== 'admin') {

                $_SESSION['login_error'] = "⚠ Access Denied: Only Admin Can Login";

                header("Location: login.php");
                exit();
            }

            /* ✅ ADMIN LOGIN SUCCESS */
            $_SESSION['user_id'] = $user_id;
            $_SESSION['username'] = $db_username;
            $_SESSION['role'] = $role;

            header("Location: admin_dashboard.php");
            exit();

        } else {
            $_SESSION['login_error'] = "Incorrect password";
        }

    } else {
        $_SESSION['login_error'] = "User not found";
    }

    header("Location: login.php");
    exit();
}

$conn->close();
?>