<?php
/**
 * API - Sessiooni kehtivuse kontroll
 * Tagastab JSON vastuse sessiooni oleku kohta
 * 🔒 TURVALISUS: Automaatse väljalogimise tugi
 */

require_once '../config/config.php';
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Määra content type
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Kontrolli meetodit
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $response = [
        'valid' => false,
        'user_id' => null,
        'user_name' => null,
        'user_role' => null,
        'session_start' => null,
        'last_activity' => null,
        'server_time' => date('c'),
        'session_id' => session_id()
    ];
    
    // Kontrolli kas kasutaja on sisse logitud
    if (isLoggedIn()) {
        $user_id = $_SESSION['user_id'];
        
        // Kontrolli kas kasutaja eksisteerib ja on aktiivne
        $stmt = $pdo->prepare("SELECT id, firstName, lastName, role, isActive FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user && $user['isActive']) {
            // Sessioon on kehtiv
            $response['valid'] = true;
            $response['user_id'] = $user['id'];
            $response['user_name'] = $user['firstName'] . ' ' . $user['lastName'];
            $response['user_role'] = $user['role'];
            
            // Lisa sessiooni info kui saadaval
            if (isset($_SESSION['login_time'])) {
                $response['session_start'] = $_SESSION['login_time'];
            }
            
            // Uuenda viimase aktiivsuse aeg
            $_SESSION['last_activity'] = time();
            $response['last_activity'] = $_SESSION['last_activity'];
            
            // Logi sessiooni kontroll (ainult development režiimis)
            if (APP_ENVIRONMENT === 'development') {
                logActivity($user_id, 'session_check', 'Session validity checked via API');
            }
            
        } else {
            // Kasutaja pole aktiivne või ei eksisteeri
            if ($user && !$user['isActive']) {
                $response['error'] = 'User account is deactivated';
                logActivity($user['id'], 'session_invalid', 'Session check failed - user deactivated');
            } else {
                $response['error'] = 'User not found';
            }
            
            // Hävita vigane sessioon
            session_destroy();
        }
    } else {
        $response['error'] = 'Not logged in';
    }
    
    // Lisa täiendav turvalisuse info
    $response['security'] = [
        'ip_address' => getRealIpAddress(),
        'user_agent_hash' => hash('sha256', $_SERVER['HTTP_USER_AGENT'] ?? ''),
        'session_timeout' => ini_get('session.gc_maxlifetime'),
        'auto_logout_enabled' => getSystemSetting('auto_logout_enabled', '1') === '1'
    ];
    
    // Development režiimis lisa debug info
    if (APP_ENVIRONMENT === 'development' && isset($_GET['debug'])) {
        $response['debug'] = [
            'session_data' => $_SESSION,
            'session_name' => session_name(),
            'session_id' => session_id(),
            'session_status' => session_status(),
            'cookie_params' => session_get_cookie_params(),
            'php_session_settings' => [
                'gc_maxlifetime' => ini_get('session.gc_maxlifetime'),
                'cookie_lifetime' => ini_get('session.cookie_lifetime'),
                'use_strict_mode' => ini_get('session.use_strict_mode')
            ]
        ];
    }
    
    echo json_encode($response, JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    error_log('Session check API error: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'valid' => false,
        'error' => 'Internal server error',
        'server_time' => date('c')
    ]);
}
?>