<?php
/**
 * Visitor Identification System
 * Generates and manages unique visitor IDs for targeted communication
 */

/**
 * Generate a unique visitor ID
 * @return string Unique visitor identifier
 */
function generateVisitorId() {
    // Create a unique ID based on timestamp, random string, and IP
    $timestamp = time();
    $random = bin2hex(random_bytes(8));
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    
    // Create a hash that's unique but consistent for the same visitor
    $visitorData = $ip . $userAgent . $timestamp;
    $visitorId = 'visitor_' . substr(md5($visitorData), 0, 16) . '_' . $timestamp;
    
    return $visitorId;
}

/**
 * Get or create visitor ID for current session
 * @return string Visitor ID
 */
function getVisitorId() {
    // Check if visitor ID already exists in session
    if (!isset($_SESSION['visitor_id'])) {
        $_SESSION['visitor_id'] = generateVisitorId();
    }
    
    return $_SESSION['visitor_id'];
}

/**
 * Store visitor information with their ID
 * @param string $visitorId Visitor ID
 * @param array $visitorData Visitor information
 * @return bool Success status
 */
function storeVisitorInfo($visitorId, $visitorData = []) {
    $visitorsFile = 'database/active_visitors.json';
    $visitors = [];
    
    if (file_exists($visitorsFile)) {
        $visitors = json_decode(file_get_contents($visitorsFile), true) ?? [];
    }
    
    // Add or update visitor info
    $visitors[$visitorId] = array_merge([
        'id' => $visitorId,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'created_at' => date('Y-m-d H:i:s'),
        'last_seen' => date('Y-m-d H:i:s'),
        'current_page' => $_SERVER['REQUEST_URI'] ?? '/',
        'status' => 'active'
    ], $visitorData);
    
    return file_put_contents($visitorsFile, json_encode($visitors, JSON_PRETTY_PRINT)) !== false;
}

/**
 * Get visitor information by ID
 * @param string $visitorId Visitor ID
 * @return array|null Visitor information or null if not found
 */
function getVisitorInfo($visitorId) {
    $visitorsFile = 'database/active_visitors.json';
    
    if (!file_exists($visitorsFile)) {
        return null;
    }
    
    $visitors = json_decode(file_get_contents($visitorsFile), true) ?? [];
    return $visitors[$visitorId] ?? null;
}

/**
 * Update visitor's current page and last seen
 * @param string $visitorId Visitor ID
 * @param string $currentPage Current page URL
 * @return bool Success status
 */
function updateVisitorActivity($visitorId, $currentPage = null) {
    $visitorsFile = 'database/active_visitors.json';
    $visitors = [];
    
    if (file_exists($visitorsFile)) {
        $visitors = json_decode(file_get_contents($visitorsFile), true) ?? [];
    }
    
    if (isset($visitors[$visitorId])) {
        $visitors[$visitorId]['last_seen'] = date('Y-m-d H:i:s');
        if ($currentPage) {
            $visitors[$visitorId]['current_page'] = $currentPage;
        }
        
        return file_put_contents($visitorsFile, json_encode($visitors, JSON_PRETTY_PRINT)) !== false;
    }
    
    return false;
}

/**
 * Get all active visitors
 * @return array Active visitors
 */
function getActiveVisitors() {
    $visitorsFile = 'database/active_visitors.json';
    
    if (!file_exists($visitorsFile)) {
        return [];
    }
    
    $visitors = json_decode(file_get_contents($visitorsFile), true) ?? [];
    
    // Clean up old visitors (inactive for more than 30 minutes)
    $currentTime = time();
    $cleanedVisitors = [];
    
    foreach ($visitors as $id => $visitor) {
        $lastSeen = strtotime($visitor['last_seen']);
        if (($currentTime - $lastSeen) < 1800) { // 30 minutes
            $cleanedVisitors[$id] = $visitor;
        }
    }
    
    // Save cleaned visitors if any were removed
    if (count($cleanedVisitors) !== count($visitors)) {
        file_put_contents($visitorsFile, json_encode($cleanedVisitors, JSON_PRETTY_PRINT));
    }
    
    return $cleanedVisitors;
}

/**
 * Remove visitor from active list
 * @param string $visitorId Visitor ID
 * @return bool Success status
 */
function removeVisitor($visitorId) {
    $visitorsFile = 'database/active_visitors.json';
    $visitors = [];
    
    if (file_exists($visitorsFile)) {
        $visitors = json_decode(file_get_contents($visitorsFile), true) ?? [];
    }
    
    if (isset($visitors[$visitorId])) {
        unset($visitors[$visitorId]);
        return file_put_contents($visitorsFile, json_encode($visitors, JSON_PRETTY_PRINT)) !== false;
    }
    
    return false;
}

/**
 * Get visitor ID from session or create new one
 * @return string Visitor ID
 */
function getCurrentVisitorId() {
    // Start session if not already started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    $visitorId = getVisitorId();
    
    // Store visitor info
    storeVisitorInfo($visitorId);
    
    // Update activity
    updateVisitorActivity($visitorId, $_SERVER['REQUEST_URI'] ?? '/');
    
    return $visitorId;
}
?>
