This paper presents a cost-optimized, reliable, resilient, real-time, rule-based energy management scheme (EMS) for a solar photovoltaic (SPV) array and battery energy storage (BES) interfaced, grid-integrated microgrid (MG) for smart building applications. To solve several economic issues, the EMS is designed to provide power leveling, emergency backup and optimized power consumption from the grid. The introduced EMS controls the power utilized from the BES to regulate the power consumption from the grid to maximize the net profit earned and minimize the energy cost incurred based on the real-time system states. Moreover, this paper presents a variable gain enhanced second-order generalized integrator frequency locked loop (VGESOGI-FLL) based control algorithm for MG. It solves the power quality (PQ) problems in smart building-based MG due to the distorted grid conditions. Moreover, the control also improves the grid side PQ with the local loads at the demand side by eliminating dominant harmonics, providing reactive power support, and operating the grid at the unity power factor, further improving the system efficiency. The system performance is analyzed using simulation results from a designed Simulink model along with hardware results during extreme conditions.