<?php
/**
 * Log user interactions for tracking purposes
 */

header('Content-Type: application/json');

require_once 'Database.php';
require_once 'Logger.php';
require_once 'InputSanitizer.php';

try {
    // Start session if not already started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Initialize services
    $db = Database::getInstance();
    
    // Get JSON input
    $jsonInput = file_get_contents('php://input');
    $data = json_decode($jsonInput, true);
    
    if (!$data || !isset($data['interaction_type'])) {
        throw new Exception('Invalid input data');
    }
    
    // Sanitize inputs
    $interactionType = InputSanitizer::sanitizeString($data['interaction_type']);
    $sessionId = session_id();
    
    // Validate interaction type
    $validTypes = ['consent_view', 'consent_submit', 'page_load', 'form_interaction', 'consent_decline'];
    if (!in_array($interactionType, $validTypes)) {
        throw new Exception('Invalid interaction type');
    }
    
    // Collect metadata
    $interactionData = [
        'session_id' => $sessionId,
        'interaction_type' => $interactionType,
        'page_url' => $_SERVER['HTTP_REFERER'] ?? '',
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'referer' => $_SERVER['HTTP_REFERER'] ?? '',
        'screen_resolution' => $data['screen_resolution'] ?? '',
        'timezone' => $data['timezone'] ?? '',
        'language' => $data['language'] ?? '',
        'platform' => $data['platform'] ?? '',
        'browser' => $data['browser'] ?? '',
        'device_type' => $data['device_type'] ?? 'desktop',
        'interaction_data' => json_encode($data['interaction_data'] ?? [])
    ];
    
    // Insert interaction record
    $db->insert('user_interactions', $interactionData);
    
    echo json_encode([
        'success' => true,
        'message' => 'Interaction logged successfully'
    ]);
    
} catch (Exception $e) {
    Logger::error('Failed to log interaction', [
        'error' => $e->getMessage(),
        'input_data' => $data ?? []
    ]);
    
    echo json_encode([
        'success' => false,
        'message' => 'Failed to log interaction'
    ]);
}
?>
