<?php
/**
 * API Endpoint - Session Update
 * Handles session updates and behavioral tracking
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Include required files
require_once '../config.php';
require_once '../antibot.php';
require_once '../data-handler.php';

// Load configuration
$config = include '../config.php';

// Initialize AntiBot protection
$antibot = new AntiBot($config);

// Check if antibot protection is enabled
if (!$antibot->protect()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
    exit;
}

// Validate required fields
if (!isset($input['sessionId'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing sessionId']);
    exit;
}

$sessionId = $input['sessionId'];
$timeSpent = $input['timeSpent'] ?? 0;
$currentSection = $input['currentSection'] ?? 0;

try {
    // Initialize data handler
    $dataHandler = new SimpleDataHandler($config);
    
    // Get client information
    $clientIP = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Log session activity
    $dataHandler->logSecurityEvent($clientIP, $userAgent, 'session_update', 
        "Time spent: {$timeSpent}s, Section: {$currentSection}");
    
    echo json_encode([
        'success' => true,
        'message' => 'Session updated successfully',
        'timeSpent' => $timeSpent,
        'currentSection' => $currentSection
    ]);
    
} catch (Exception $e) {
    error_log("Session Update Error: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update session'
    ]);
}
?>
