<?php
session_start();

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

    // Database connection
    $link = mysqli_connect("localhost", "gurukul_tsli", "t8bF8MZ6tbTNSBEn", "gurukul_tsli");

    if (!$link) {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Step 1: Check if username exists
    $sql = "SELECT password, post_name FROM branchlogin WHERE username = ?";
    $stmt = mysqli_prepare($link, $sql);
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) === 0) {
        echo "❌ Error: Username not found.";
    } else {
        // Step 2: Bind result
        mysqli_stmt_bind_result($stmt, $hashed_password, $post_name);
        mysqli_stmt_fetch($stmt);

        // Step 3: Check post_name
        if (strtoupper($post_name) !== 'BRANCH') {
            echo "❌ Error: You are not an admin (post_name is '$post_name').";
        } else {
            // Step 4: Verify password
            if (password_verify($password, $hashed_password)) {
                $_SESSION['username'] = $username;
                $_SESSION['loggedIn'] = true;
                header("Location: index.php");
                exit();
            } else {
                echo "❌ Error: Incorrect password.";
            }
        }
    }

    // Close connections
    mysqli_stmt_close($stmt);
    mysqli_close($link);
}
?>


	
	