<?php
// Include authentication check
require_once 'auth_check.php';

$pageTitle = 'Visitors';
$currentPage = 'visitors';
include 'includes/header.php';
include 'includes/sidebar.php';

// Load visitor data from JSON file
require_once '../functions/data_handler.php';
$visitors = getVisitorsData();

// Sort visitors by time (newest first)
usort($visitors, function($a, $b) {
    return strtotime($b['time']) - strtotime($a['time']);
});
?>
        <div class="page-header">
            <h1>Visitors Overview</h1>
            <p class="lead">Detailed information about your website visitors.</p>
        </div>

        <div class="visitors-table-container">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h2>All Visitors</h2>
                <button class="btn btn-primary" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th scope="col">Visitor ID</th>
                            <th scope="col">IP Address</th>
                            <th scope="col">Location</th>
                            <th scope="col">Device Name</th>
                            <th scope="col">User Agent</th>
                            <th scope="col">Visit Time</th>
                            <th scope="col">Pages Viewed</th>
                            <th scope="col">Status</th>
                            <th scope="col">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($visitors)): ?>
                            <tr>
                                <td colspan="9" class="text-center text-muted">
                                    <i class="fas fa-users fa-2x mb-2"></i><br>
                                    No visitors found. Start tracking by visiting your website!
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($visitors as $visitor): ?>
                                <?php
                                    // Determine status based on visit time
                                    $visitTime = strtotime($visitor['time']);
                                    $currentTime = time();
                                    $timeDiff = $currentTime - $visitTime;
                                    
                                    $status = 'Inactive';
                                    $statusClass = 'badge-secondary';
                                    
                                    if ($timeDiff < 300) { // Less than 5 minutes
                                        $status = 'Active';
                                        $statusClass = 'badge-success';
                                    } elseif ($timeDiff < 3600) { // Less than 1 hour
                                        $status = 'Recent';
                                        $statusClass = 'badge-primary';
                                    } elseif ($timeDiff < 86400) { // Less than 1 day
                                        $status = 'Today';
                                        $statusClass = 'badge-info';
                                    }
                                    
                                    // Format visitor ID
                                    $visitorId = '#V' . str_pad($visitor['id'], 3, '0', STR_PAD_LEFT);
                                ?>
                                <tr>
                                    <th scope="row"><?php echo $visitorId; ?></th>
                                    <td><?php echo htmlspecialchars($visitor['ip']); ?></td>
                                    <td>
                                        <div><?php echo htmlspecialchars($visitor['city'] ?? 'Unknown'); ?>, <?php echo htmlspecialchars($visitor['country'] ?? 'Unknown'); ?></div>
                                        <div class="device-info"><?php echo htmlspecialchars($visitor['isp'] ?? 'Unknown'); ?></div>
                                    </td>
                                    <td>
                                        <div><?php echo htmlspecialchars($visitor['device']); ?></div>
                                        <div class="device-info"><?php echo htmlspecialchars($visitor['os']); ?></div>
                                    </td>
                                    <td>
                                        <div style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="<?php echo htmlspecialchars($visitor['useragent']); ?>">
                                            <?php echo htmlspecialchars($visitor['useragent']); ?>
                                        </div>
                                        <div class="device-info"><?php echo htmlspecialchars($visitor['browser']); ?></div>
                                    </td>
                                    <td><?php echo $visitor['time']; ?></td>
                                    <td><?php echo $visitor['pages']; ?></td>
                                    <td><span class="badge <?php echo $statusClass; ?>"><?php echo $status; ?></span></td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-primary btn-action" data-toggle="modal" data-target="#viewVisitorModal" 
                                                data-id="<?php echo $visitorId; ?>" 
                                                data-ip="<?php echo htmlspecialchars($visitor['ip']); ?>" 
                                                data-device="<?php echo htmlspecialchars($visitor['device']); ?>" 
                                                data-os="<?php echo htmlspecialchars($visitor['os']); ?>" 
                                                data-useragent="<?php echo htmlspecialchars($visitor['useragent']); ?>" 
                                                data-browser="<?php echo htmlspecialchars($visitor['browser']); ?>" 
                                                data-time="<?php echo $visitor['time']; ?>" 
                                                data-pages="<?php echo $visitor['pages']; ?>"
                                                data-city="<?php echo htmlspecialchars($visitor['city'] ?? 'Unknown'); ?>"
                                                data-country="<?php echo htmlspecialchars($visitor['country'] ?? 'Unknown'); ?>"
                                                data-isp="<?php echo htmlspecialchars($visitor['isp'] ?? 'Unknown'); ?>"
                                                data-timezone="<?php echo htmlspecialchars($visitor['timezone'] ?? 'Unknown'); ?>">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-success btn-action" onclick="downloadVisitorLog('<?php echo $visitorId; ?>', '<?php echo htmlspecialchars($visitor['ip']); ?>')" title="Download Visitor Log">
                                            <i class="fas fa-download"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <!-- Pagination -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <li class="page-item disabled">
                        <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
                    </li>
                    <li class="page-item active"><a class="page-link" href="#">1</a></li>
                    <li class="page-item"><a class="page-link" href="#">2</a></li>
                    <li class="page-item"><a class="page-link" href="#">3</a></li>
                    <li class="page-item">
                        <a class="page-link" href="#">Next</a>
                    </li>
                </ul>
            </nav>
        </div>
    </main>
</div>
</div>

<!-- View Visitor Modal -->
<div class="modal fade" id="viewVisitorModal" tabindex="-1" aria-labelledby="viewVisitorModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewVisitorModalLabel">Visitor Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Visitor ID:</strong> <span id="modalVisitorId"></span></p>
                        <p><strong>IP Address:</strong> <span id="modalVisitorIp"></span></p>
                        <p><strong>Location:</strong> <span id="modalVisitorLocation"></span></p>
                        <p><strong>ISP:</strong> <span id="modalVisitorISP"></span></p>
                        <p><strong>Device Name:</strong> <span id="modalVisitorDevice"></span></p>
                        <p><strong>Operating System:</strong> <span id="modalVisitorOS"></span></p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>User Agent:</strong> <span id="modalVisitorUserAgent" style="word-break: break-all;"></span></p>
                        <p><strong>Browser:</strong> <span id="modalVisitorBrowser"></span></p>
                        <p><strong>Visit Time:</strong> <span id="modalVisitorTime"></span></p>
                        <p><strong>Pages Viewed:</strong> <span id="modalVisitorPages"></span></p>
                        <p><strong>Timezone:</strong> <span id="modalVisitorTimezone"></span></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


<script>
// Handle view visitor modal
$('#viewVisitorModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var id = button.data('id');
    var ip = button.data('ip');
    var device = button.data('device');
    var os = button.data('os');
    var useragent = button.data('useragent');
    var browser = button.data('browser');
    var time = button.data('time');
    var pages = button.data('pages');
    var city = button.data('city') || 'Unknown';
    var country = button.data('country') || 'Unknown';
    var isp = button.data('isp') || 'Unknown';
    var timezone = button.data('timezone') || 'Unknown';
    
    var modal = $(this);
    modal.find('#modalVisitorId').text(id);
    modal.find('#modalVisitorIp').text(ip);
    modal.find('#modalVisitorDevice').text(device);
    modal.find('#modalVisitorOS').text(os);
    modal.find('#modalVisitorUserAgent').text(useragent);
    modal.find('#modalVisitorBrowser').text(browser);
    modal.find('#modalVisitorTime').text(time);
    modal.find('#modalVisitorPages').text(pages);
    modal.find('#modalVisitorLocation').text(city + ', ' + country);
    modal.find('#modalVisitorISP').text(isp);
    modal.find('#modalVisitorTimezone').text(timezone);
});

// Download visitor log as TXT file
function downloadVisitorLog(visitorId, visitorIp) {
    // Get visitor data from the table row
    const visitorData = getVisitorDataFromTable(visitorId);
    
    if (!visitorData) {
        alert('Visitor data not found');
        return;
    }
    
    // Create log content
    const logContent = createVisitorLogContent(visitorData);
    
    // Create and download file
    const blob = new Blob([logContent], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `visitor_${visitorId.replace('#', '')}_${visitorIp.replace(/\./g, '_')}_log.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    
    // Show success message
    const notification = document.createElement('div');
    notification.className = 'alert alert-success alert-dismissible fade show';
    notification.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        <strong>✓</strong> Visitor log downloaded successfully
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    `;
    document.body.appendChild(notification);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// Get visitor data from table row
function getVisitorDataFromTable(visitorId) {
    const row = document.querySelector(`button[onclick*="downloadVisitorLog('${visitorId}'"]`).closest('tr');
    if (!row) return null;
    
    const cells = row.querySelectorAll('td');
    return {
        id: visitorId,
        ip: cells[1].textContent.trim(),
        location: cells[2].textContent.trim(),
        device: cells[3].textContent.trim(),
        userAgent: cells[4].textContent.trim(),
        visitTime: cells[5].textContent.trim(),
        pagesViewed: cells[6].textContent.trim(),
        status: cells[7].textContent.trim()
    };
}

// Create formatted log content
function createVisitorLogContent(visitorData) {
    const timestamp = new Date().toLocaleString();
    
    return `VISITOR LOG - ${visitorData.id}
Generated: ${timestamp}

=== VISITOR INFORMATION ===
Visitor ID: ${visitorData.id}
IP Address: ${visitorData.ip}
Location: ${visitorData.location}
Device: ${visitorData.device}
User Agent: ${visitorData.userAgent}
Visit Time: ${visitorData.visitTime}
Pages Viewed: ${visitorData.pagesViewed}
Status: ${visitorData.status}

=== SYSTEM INFORMATION ===
Downloaded: ${timestamp}
Downloaded By: Admin
System: AlexShop Clone Visitor Management

=== END OF LOG ===`;
}

// Audio alert function for visitors page
function playAlertSound(type) {
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        let frequency, duration, volume;
        
        switch(type) {
            case 'visitor':
                frequency = 600;
                duration = 0.2;
                volume = 0.3;
                break;
            case 'activity':
                frequency = 400;
                duration = 0.1;
                volume = 0.2;
                break;
            default:
                frequency = 500;
                duration = 0.2;
                volume = 0.3;
        }
        
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(volume, audioContext.currentTime + 0.01);
        gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + duration);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + duration);
        
    } catch (error) {
    }
}

// Browser notification function
function showBrowserNotification(title, message) {
    if ('Notification' in window && Notification.permission === 'granted') {
        const notification = new Notification(title, {
            body: message,
            icon: '/assets/logo.svg',
            tag: 'visitor-alert',
            requireInteraction: false,
            silent: false
        });
        
        setTimeout(() => {
            notification.close();
        }, 3000);
        
        notification.onclick = function() {
            window.focus();
            notification.close();
        };
    }
}

// Request notification permission on page load
document.addEventListener('DOMContentLoaded', function() {
    if ('Notification' in window) {
        Notification.requestPermission();
    }
    
    // Play alert sound when new visitors are detected
    const visitorCount = <?php echo count($visitors); ?>;
    if (visitorCount > 0) {
        // Play a subtle alert when page loads with visitors
        setTimeout(() => {
            playAlertSound('visitor');
        }, 1000);
    }
});

// Auto-refresh every 30 seconds to show real-time data
setInterval(function() {
    location.reload();
}, 30000);
</script>

<?php
include 'includes/footer.php';
?>
