here's a list of things your login code needs to do differently -
do NOT store the user_id in a cookie to identify who is logged in. anyone or a bot script can supply any value for a cookie when they request your page and appear to be anyone, such as you or an administrator on your site, just by going through all possible user id's until they find one that works. you would instead generate a random unique value, similar to what a session id cookie is, and store it in a database table that relates it to the actual user_id and store it in the cookie.
you must have an exit/die statement after every header() redirect to STOP code execution. your current code is executing all the rest of the code on the page at each header() redirect.
don't use fetchAll() and a loop for a query that will at most match one row of data. just directly call the fetch() method and test if a row of data was found.
as to your current problem, the code you are dealing with is the login form processing code and the login form. however, you have put the login form processing code at what appears to be the top of the main index.php page. this doesn't make any sense, logically, because you would be redirecting to the main page, that you are already on, if the cookie is set. you are also testing a different cookie name then the one you are setting (id vs user_id), and there's no code setting the $user_id variable you are testing on the page to determine if there is a logged in user.