Character moves out of character controller collider when rotating

Hey guys, I am trying to learn unity by making a simple 3rd person game following some tutorials. My character moves fine but if I try to rotate my character towards his back (like pressing s and w again and again) he start to move out of his character controller collider (using the built-in character controller). Following is the script I am using for the movement, besides this I am using cinemachine to handle camera:

public class ThirdPersonMovement : MonoBehaviour
{
    public CharacterController controller;
    public Transform cam;

    public float speed = 6.0f;
    public float turnSmoothTime = 0.1f; // factor used to smooth player rotation
    float turnSmoothVelocity;

    // Update is called once per frame
    void Update()
    {
        //Get raw input (Movement keys): -1 to 1
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        Vector3 direction = new Vector3(horizontal, 0.0f, vertical).normalized;

        //If direction vector has greater value than 0.1f then start moving
        if(direction.magnitude >= 0.1f)
        {
            //figure out the angle from mouse input for player's Z
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;

            //smoothly change the angle
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y,targetAngle, ref turnSmoothVelocity, turnSmoothTime);

            //rotate player along Y axis
            transform.rotation = Quaternion.Euler(0.0f,angle,0.0f);

            //Rotation to direction: to forward
            Vector3 moveDir = Quaternion.Euler(0.0f, targetAngle, 0.0f) * Vector3.forward;

            controller.Move(moveDir.normalized * speed * Time.deltaTime);
        }

    }
}

I would apricate any help, thanks!

I’ve watched a lot of videos and I’ve noticed that a lot of people tend to use Local Rotation to normal Rotation so try

Try Reading this