<?php

use App\Http\Middleware\PermissionMiddleware;
use App\Http\Middleware\SetDatabaseTimezone;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Session\TokenMismatchException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'permission' => PermissionMiddleware::class,
        ]);
        $middleware->append(SetDatabaseTimezone::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (TokenMismatchException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Session expired. Please login again.'], 419);
            }

            $scheme = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
            $loginUrl = $scheme.'://'.$host.'/login';

            return response('<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0;url='.$loginUrl.'">
    <title>Session Expired - PosAI</title>
    <style>
        body { font-family: Arial, sans-serif; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        .card { background: white; padding: 40px; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); text-align: center; max-width: 400px; }
        h2 { color: #333; margin-bottom: 10px; }
        p { color: #666; }
        a { color: #007bff; text-decoration: none; display: inline-block; margin-top: 15px; padding: 10px 20px; background: #007bff; color: white; border-radius: 5px; }
        a:hover { background: #0056b3; }
    </style>
</head>
<body>
    <div class="card">
        <h2>Session Expired</h2>
        <p>Your session has expired due to inactivity.</p>
        <p>Redirecting to login...</p>
        <a href="'.$loginUrl.'">Go to Login</a>
    </div>
    <script>setTimeout(function(){ window.location.href = "'.$loginUrl.'"; }, 2000); </script>
</body>
</html>', 419);
        });
    })->create();
