<?php
// config/auth_check.php - Authentication Check for Protected Pages

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['user_id']) || !isset($_SESSION['access_token'])) {
    // User is not authenticated, redirect to login
    header('Location: /admob-manager/index.php');
    exit;
}

// Optional: Check if access token is still valid
// You can add token expiration check here if needed
if (isset($_SESSION['token_expires_at'])) {
    if (time() >= $_SESSION['token_expires_at']) {
        // Token has expired, try to refresh or redirect to login
        
        // Clear session
        session_unset();
        session_destroy();
        
        // Redirect to login
        header('Location: /admob-manager/index.php?error=session_expired');
        exit;
    }
}

// Optional: Refresh token if it's about to expire (within 5 minutes)
if (isset($_SESSION['token_expires_at'])) {
    $time_until_expiry = $_SESSION['token_expires_at'] - time();
    
    // If token expires in less than 5 minutes, try to refresh
    if ($time_until_expiry < 300 && isset($_SESSION['refresh_token'])) {
        require_once __DIR__ . '/config.php';
        require_once __DIR__ . '/../src/OAuth.php';
        
        try {
            $oauth = new OAuth(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI);
            $new_token = $oauth->refreshAccessToken($_SESSION['refresh_token']);
            
            if ($new_token) {
                $_SESSION['access_token'] = $new_token['access_token'];
                $_SESSION['token_expires_at'] = time() + ($new_token['expires_in'] ?? 3600);
                
                if (isset($new_token['refresh_token'])) {
                    $_SESSION['refresh_token'] = $new_token['refresh_token'];
                }
            }
        } catch (Exception $e) {
            // Log error but don't interrupt user
            error_log('Token refresh failed: ' . $e->getMessage());
        }
    }
}

// User is authenticated, continue to page
?>