<?php
/**
 * Individual Visitor Details
 * LandSales Pro - View complete visitor activity
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';
require_once '../../includes/visitor_tracker.php';

initSecureSession();
requireAuth();
requireAdmin();

$visitorId = intval($_GET['id'] ?? 0);

if (!$visitorId) {
    header('Location: index.php');
    exit;
}

$data = getVisitorDetails($visitorId);

if (!$data) {
    header('Location: index.php');
    exit;
}

$visitor = $data['visitor'];
$sessions = $data['sessions'];
$pageviews = $data['pageviews'];
$events = $data['events'];

$pageTitle = 'Visitor Details';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="<?php echo SITE_URL; ?>/assets/css/dashboard.css" rel="stylesheet">
    <style>
        .visitor-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 1.5rem;
        }
        .visitor-header h2 { margin: 0; }
        .visitor-header .badge { font-size: 0.9rem; }

        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
            height: calc(100% - 1.5rem);
        }
        .info-card h5 {
            margin-bottom: 1rem;
            color: #1e293b;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .info-card h5 i { color: #667eea; }

        .info-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .info-list li {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .info-list li:last-child { border-bottom: none; }
        .info-list .label { color: #64748b; }
        .info-list .value { color: #1e293b; font-weight: 500; text-align: right; }

        .activity-timeline {
            position: relative;
            padding-left: 30px;
        }
        .activity-timeline::before {
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }

        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
        }
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -24px;
            top: 4px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #667eea;
            border: 2px solid white;
            box-shadow: 0 0 0 2px #667eea;
        }
        .timeline-item.session::before { background: #22c55e; box-shadow: 0 0 0 2px #22c55e; }
        .timeline-item.event::before { background: #f59e0b; box-shadow: 0 0 0 2px #f59e0b; }

        .timeline-time {
            font-size: 0.75rem;
            color: #94a3b8;
            margin-bottom: 0.25rem;
        }
        .timeline-content {
            background: #f8fafc;
            padding: 0.75rem 1rem;
            border-radius: 8px;
        }
        .timeline-content .page-url {
            color: #667eea;
            font-size: 0.875rem;
            word-break: break-all;
        }

        .map-container {
            height: 200px;
            border-radius: 8px;
            overflow: hidden;
            background: #f1f5f9;
        }

        .country-flag {
            width: 32px;
            height: 24px;
            border-radius: 4px;
            margin-right: 0.75rem;
        }

        .session-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        .session-card.active {
            border-left: 3px solid #22c55e;
        }

        .user-agent-box {
            background: #f1f5f9;
            padding: 1rem;
            border-radius: 8px;
            font-family: monospace;
            font-size: 0.8rem;
            word-break: break-all;
            color: #475569;
        }

        .badge-bot { background: #94a3b8; }
        .badge-human { background: #22c55e; }

        .stat-mini {
            text-align: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
        }
        .stat-mini .value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        .stat-mini .label {
            font-size: 0.75rem;
            color: #64748b;
        }
    </style>
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title"><?php echo $pageTitle; ?></h1>
            <div>
                <a href="index.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i> Back to Visitors
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Visitor Header -->
            <div class="visitor-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="d-flex align-items-center mb-2">
                            <?php if ($visitor['country_code']): ?>
                            <img src="https://flagcdn.com/w40/<?php echo strtolower($visitor['country_code']); ?>.png"
                                 class="country-flag" alt="">
                            <?php endif; ?>
                            <h2>
                                <?php if ($visitor['is_bot']): ?>
                                    <span class="badge badge-bot me-2"><i class="fas fa-robot me-1"></i><?php echo htmlspecialchars($visitor['bot_name'] ?: 'Bot'); ?></span>
                                <?php else: ?>
                                    <span class="badge badge-human me-2"><i class="fas fa-user me-1"></i>Human Visitor</span>
                                <?php endif; ?>
                                <?php echo htmlspecialchars($visitor['ip_address']); ?>
                            </h2>
                        </div>
                        <p class="mb-0 opacity-75">
                            <?php if ($visitor['city']): ?>
                                <?php echo htmlspecialchars($visitor['city']); ?>,
                            <?php endif; ?>
                            <?php if ($visitor['region']): ?>
                                <?php echo htmlspecialchars($visitor['region']); ?>,
                            <?php endif; ?>
                            <?php echo htmlspecialchars($visitor['country_name'] ?: 'Unknown Location'); ?>
                            <?php if ($visitor['isp']): ?>
                                | <?php echo htmlspecialchars($visitor['isp']); ?>
                            <?php endif; ?>
                        </p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <div class="row g-2">
                            <div class="col-4">
                                <div class="stat-mini" style="background: rgba(255,255,255,0.15);">
                                    <div class="value" style="color: white;"><?php echo number_format($visitor['total_visits']); ?></div>
                                    <div class="label" style="color: rgba(255,255,255,0.7);">Visits</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="stat-mini" style="background: rgba(255,255,255,0.15);">
                                    <div class="value" style="color: white;"><?php echo number_format($visitor['total_pageviews']); ?></div>
                                    <div class="label" style="color: rgba(255,255,255,0.7);">Pages</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="stat-mini" style="background: rgba(255,255,255,0.15);">
                                    <div class="value" style="color: white;"><?php echo count($sessions); ?></div>
                                    <div class="label" style="color: rgba(255,255,255,0.7);">Sessions</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- Left Column -->
                <div class="col-lg-4">
                    <!-- Device Info -->
                    <div class="info-card">
                        <h5><i class="fas fa-laptop"></i> Device Information</h5>
                        <ul class="info-list">
                            <li>
                                <span class="label">Device Type</span>
                                <span class="value">
                                    <?php
                                    $deviceIcon = match($visitor['device_type']) {
                                        'desktop' => 'fa-desktop',
                                        'mobile' => 'fa-mobile-alt',
                                        'tablet' => 'fa-tablet-alt',
                                        'bot' => 'fa-robot',
                                        default => 'fa-question'
                                    };
                                    ?>
                                    <i class="fas <?php echo $deviceIcon; ?> me-1"></i>
                                    <?php echo ucfirst($visitor['device_type']); ?>
                                </span>
                            </li>
                            <li>
                                <span class="label">Browser</span>
                                <span class="value"><?php echo htmlspecialchars($visitor['browser'] ?: 'Unknown'); ?> <?php echo $visitor['browser_version']; ?></span>
                            </li>
                            <li>
                                <span class="label">Operating System</span>
                                <span class="value"><?php echo htmlspecialchars($visitor['os'] ?: 'Unknown'); ?> <?php echo $visitor['os_version']; ?></span>
                            </li>
                            <li>
                                <span class="label">Site</span>
                                <span class="value">
                                    <span class="badge bg-primary"><?php echo htmlspecialchars($visitor['site']); ?></span>
                                </span>
                            </li>
                        </ul>
                    </div>

                    <!-- Location Info -->
                    <div class="info-card">
                        <h5><i class="fas fa-map-marker-alt"></i> Location</h5>
                        <?php if ($visitor['latitude'] && $visitor['longitude']): ?>
                        <div class="map-container mb-3" id="map"></div>
                        <?php endif; ?>
                        <ul class="info-list">
                            <li>
                                <span class="label">Country</span>
                                <span class="value">
                                    <?php if ($visitor['country_code']): ?>
                                    <img src="https://flagcdn.com/w20/<?php echo strtolower($visitor['country_code']); ?>.png"
                                         style="width: 20px; margin-right: 5px;">
                                    <?php endif; ?>
                                    <?php echo htmlspecialchars($visitor['country_name'] ?: 'Unknown'); ?>
                                </span>
                            </li>
                            <li>
                                <span class="label">Region</span>
                                <span class="value"><?php echo htmlspecialchars($visitor['region'] ?: '-'); ?></span>
                            </li>
                            <li>
                                <span class="label">City</span>
                                <span class="value"><?php echo htmlspecialchars($visitor['city'] ?: '-'); ?></span>
                            </li>
                            <li>
                                <span class="label">Timezone</span>
                                <span class="value"><?php echo htmlspecialchars($visitor['timezone'] ?: '-'); ?></span>
                            </li>
                            <li>
                                <span class="label">ISP</span>
                                <span class="value"><?php echo htmlspecialchars($visitor['isp'] ?: '-'); ?></span>
                            </li>
                            <?php if ($visitor['latitude'] && $visitor['longitude']): ?>
                            <li>
                                <span class="label">Coordinates</span>
                                <span class="value" style="font-family: monospace; font-size: 0.8rem;">
                                    <?php echo $visitor['latitude']; ?>, <?php echo $visitor['longitude']; ?>
                                </span>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </div>

                    <!-- Timestamps -->
                    <div class="info-card">
                        <h5><i class="fas fa-clock"></i> Timeline</h5>
                        <ul class="info-list">
                            <li>
                                <span class="label">First Visit</span>
                                <span class="value"><?php echo date('M j, Y H:i', strtotime($visitor['first_visit'])); ?></span>
                            </li>
                            <li>
                                <span class="label">Last Visit</span>
                                <span class="value"><?php echo date('M j, Y H:i', strtotime($visitor['last_visit'])); ?></span>
                            </li>
                        </ul>
                    </div>

                    <!-- User Agent -->
                    <div class="info-card">
                        <h5><i class="fas fa-code"></i> User Agent</h5>
                        <div class="user-agent-box">
                            <?php echo htmlspecialchars($visitor['user_agent'] ?: 'Not available'); ?>
                        </div>
                    </div>
                </div>

                <!-- Right Column - Activity -->
                <div class="col-lg-8">
                    <!-- Sessions -->
                    <div class="info-card">
                        <h5><i class="fas fa-history"></i> Sessions (<?php echo count($sessions); ?>)</h5>
                        <?php foreach ($sessions as $session): ?>
                        <div class="session-card <?php echo !$session['ended_at'] ? 'active' : ''; ?>">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <strong>Session #<?php echo $session['id']; ?></strong>
                                    <?php if (!$session['ended_at']): ?>
                                        <span class="badge bg-success ms-2">Active</span>
                                    <?php endif; ?>
                                </div>
                                <small class="text-muted">
                                    <?php echo date('M j, Y H:i', strtotime($session['started_at'])); ?>
                                </small>
                            </div>
                            <div class="row g-2 mb-2">
                                <div class="col-4">
                                    <small class="text-muted d-block">Pages Viewed</small>
                                    <strong><?php echo $session['pageviews']; ?></strong>
                                </div>
                                <div class="col-4">
                                    <small class="text-muted d-block">Duration</small>
                                    <strong>
                                        <?php
                                        if ($session['duration_seconds'] > 0) {
                                            $mins = floor($session['duration_seconds'] / 60);
                                            $secs = $session['duration_seconds'] % 60;
                                            echo $mins > 0 ? "{$mins}m {$secs}s" : "{$secs}s";
                                        } else {
                                            echo '-';
                                        }
                                        ?>
                                    </strong>
                                </div>
                                <div class="col-4">
                                    <small class="text-muted d-block">Site</small>
                                    <span class="badge bg-primary"><?php echo $session['site']; ?></span>
                                </div>
                            </div>
                            <?php if ($session['entry_page']): ?>
                            <small class="text-muted">Entry: </small>
                            <small class="text-primary"><?php echo htmlspecialchars($session['entry_page']); ?></small>
                            <?php endif; ?>
                            <?php if ($session['referrer']): ?>
                            <br><small class="text-muted">Referrer: </small>
                            <small><?php echo htmlspecialchars($session['referrer_domain'] ?: $session['referrer']); ?></small>
                            <?php endif; ?>
                            <?php if ($session['utm_source']): ?>
                            <br><small class="text-muted">Campaign: </small>
                            <small>
                                <?php echo htmlspecialchars($session['utm_source']); ?>
                                <?php if ($session['utm_medium']): ?> / <?php echo htmlspecialchars($session['utm_medium']); ?><?php endif; ?>
                                <?php if ($session['utm_campaign']): ?> / <?php echo htmlspecialchars($session['utm_campaign']); ?><?php endif; ?>
                            </small>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                        <?php if (empty($sessions)): ?>
                        <p class="text-muted text-center">No sessions recorded</p>
                        <?php endif; ?>
                    </div>

                    <!-- Page Views Activity -->
                    <div class="info-card">
                        <h5><i class="fas fa-eye"></i> Page Activity (<?php echo count($pageviews); ?> recent)</h5>
                        <div class="activity-timeline">
                            <?php foreach ($pageviews as $pv): ?>
                            <div class="timeline-item">
                                <div class="timeline-time"><?php echo date('M j, Y H:i:s', strtotime($pv['viewed_at'])); ?></div>
                                <div class="timeline-content">
                                    <div class="page-url"><?php echo htmlspecialchars($pv['page_path']); ?></div>
                                    <?php if ($pv['page_title']): ?>
                                    <small class="text-muted"><?php echo htmlspecialchars($pv['page_title']); ?></small>
                                    <?php endif; ?>
                                    <?php if ($pv['time_on_page'] > 0): ?>
                                    <span class="badge bg-light text-dark ms-2"><?php echo $pv['time_on_page']; ?>s</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            <?php if (empty($pageviews)): ?>
                            <p class="text-muted text-center">No page views recorded</p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Events -->
                    <?php if (!empty($events)): ?>
                    <div class="info-card">
                        <h5><i class="fas fa-bolt"></i> Events (<?php echo count($events); ?>)</h5>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Time</th>
                                        <th>Type</th>
                                        <th>Category</th>
                                        <th>Action</th>
                                        <th>Label</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($events as $event): ?>
                                    <tr>
                                        <td><small><?php echo date('H:i:s', strtotime($event['created_at'])); ?></small></td>
                                        <td><span class="badge bg-warning"><?php echo htmlspecialchars($event['event_type']); ?></span></td>
                                        <td><?php echo htmlspecialchars($event['event_category'] ?: '-'); ?></td>
                                        <td><?php echo htmlspecialchars($event['event_action'] ?: '-'); ?></td>
                                        <td><?php echo htmlspecialchars($event['event_label'] ?: '-'); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <?php if ($visitor['latitude'] && $visitor['longitude']): ?>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        const map = L.map('map').setView([<?php echo $visitor['latitude']; ?>, <?php echo $visitor['longitude']; ?>], 10);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap'
        }).addTo(map);
        L.marker([<?php echo $visitor['latitude']; ?>, <?php echo $visitor['longitude']; ?>]).addTo(map)
            .bindPopup('<?php echo htmlspecialchars($visitor['city'] ?: $visitor['country_name']); ?>');
    </script>
    <?php endif; ?>
</body>
</html>
