Calling PHP function doesn’t work in index.php

I think you’re misunderstanding the function get_page_template_slug

When you call $template = get_page_template_slug( $post_id ); it won’t return index.php if you are using the default theme template. It only works when viewing Pages and will either return the slug of the Custom Page Template assigned to that Page or an empty string otherwise.

So if ( 'index.php' == $template ) will always be false.

Rather than trying to detect which template file is running, use WP’s is_ functions.

true == is_front_page()

on your site’s home page, for example.

There is a whole range of these functions to check the sort of page you are on. Have a read up on them in the documentation available online. If really feel the need to check whether you are using the index.php template then you could set a global flag variable at the start of that template and check it within your function, I suppose.