<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        // For API requests, return null to avoid redirection
        if ($request->expectsJson() || $request->is('api/*')) {
            return null;
        }

        return route('student.login');
    }

    /**
     * Handle unauthenticated requests for API routes.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $guards
     * @return void
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function unauthenticated($request, array $guards)
    {
        // For API requests, return JSON response
        if ($request->expectsJson() || $request->is('api/*')) {
            throw new \Illuminate\Auth\AuthenticationException(
                'Authentication required. Please provide a valid token.'
            );
        }

        // For web requests, redirect to login
        parent::unauthenticated($request, $guards);
    }
}
