In this work, we introduce a machine-learning (ML) based detection attack, where an eavesdropper (Eve) is able to learn the symbol detection function based on precoded pilots. With this ability, an Eve can correctly detect symbols with a high probability. To counteract this attack, we propose a novel symbol-level precoding (SLP) scheme that enhances physical-layer security (PLS) while guaranteeing a constructive interference effect at the intended users. Contrary to conventional SLP schemes, the proposed scheme is robust to the ML-based attack. In particular, the proposed scheme enhances security by designing Eve's received signal to lie at the boundaries of the detection regions. This distinct design causes Eve's detection decisions to be based almost purely on noise. The proposed countermeasure is then extended to account for multi-antennas at the Eve and also for multi-level modulation schemes. In the numerical results, we validate both the detection attack and the countermeasures and show that this gain in security can be achieved at the expense of only a small additional power consumption at the transmitter, and more importantly, these benefits are obtained without affecting the performance at the intended user.