<?php
session_start();

$serverName = "10.10.1.8";
$connectionOptions = [
    "Database" => "LIBRARYDB",
    "Uid" => "sa",
    "PWD" => "kolkata@1",
    "CharacterSet" => "UTF-8"
];

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

    try {
        $conn = sqlsrv_connect($serverName, $connectionOptions);
        if ($conn) {
            $sql = "SELECT USERNAME FROM loginmst WHERE USERNAME = ? AND PWS = ?";
            $params = array($user, $pass);
            $stmt = sqlsrv_query($conn, $sql, $params);

            if ($stmt && sqlsrv_has_rows($stmt)) {
                $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
                $_SESSION['member_id'] = $row['USERNAME'];
                
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Invalid ID or Password']);
            }
            sqlsrv_close($conn);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database Connection Failed']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'System Error']);
    }
}
?>