<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SessionController extends Controller
{
    /**
     * Check if session is still valid
     */
    public function check(Request $request)
    {
        if (!Auth::check()) {
            return response()->json([
                'expired' => true,
                'message' => 'Session expired'
            ], 401);
        }
        
        // Get session expiration time
        $lifetime = config('session.lifetime', 120); // in minutes
        $lastActivity = $request->session()->get('_last_activity', now()->timestamp);
        $expiresAt = $lastActivity + ($lifetime * 60);
        $timeRemaining = max(0, $expiresAt - now()->timestamp);
        
        return response()->json([
            'expired' => false,
            'expires_at' => now()->addMinutes($lifetime)->toIso8601String(),
            'time_remaining' => $timeRemaining,
            'minutes_remaining' => round($timeRemaining / 60, 1)
        ]);
    }
    
    /**
     * Extend the session
     */
    public function extend(Request $request)
    {
        if (!Auth::check()) {
            return response()->json([
                'error' => 'Session expired',
                'message' => 'Your session has expired. Please log in again.'
            ], 401);
        }
        
        // Touch the session to extend it
        $request->session()->put('_last_activity', now()->timestamp);
        
        return response()->json([
            'success' => true,
            'message' => 'Session extended',
            'expires_at' => now()->addMinutes(config('session.lifetime', 120))->toIso8601String()
        ]);
    }
}

