<?php
/**
 * Visitor Analytics Dashboard
 * LandSales Pro - Admin visitor tracking reports
 */
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();

$pageTitle = 'Visitor Analytics';

// Get filter parameters
$site = $_GET['site'] ?? '';
$days = intval($_GET['days'] ?? 30);
$showBots = isset($_GET['bots']) ? $_GET['bots'] === '1' : false;

// Get statistics
$stats = getVisitorStats($site ?: null, $days);

// Get recent visitors
$recentVisitors = getRecentVisitors($site ?: null, 50, 0, $showBots);

// Get visitor count for pagination
$totalVisitorsCount = db_fetch_one("
    SELECT COUNT(*) as count FROM visitors
    WHERE 1=1 " .
    ($site ? "AND site = '" . mysqli_real_escape_string($conn, $site) . "'" : "") .
    ($showBots ? "" : " AND is_bot = 0")
)['count'] ?? 0;
?>
<!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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            height: 100%;
        }
        .stat-card.primary { border-left: 4px solid #667eea; }
        .stat-card.success { border-left: 4px solid #22c55e; }
        .stat-card.warning { border-left: 4px solid #f59e0b; }
        .stat-card.danger { border-left: 4px solid #ef4444; }
        .stat-card.info { border-left: 4px solid #3b82f6; }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
        }
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            color: white;
        }
        .stat-icon.primary { background: linear-gradient(135deg, #667eea, #764ba2); }
        .stat-icon.success { background: linear-gradient(135deg, #22c55e, #16a34a); }
        .stat-icon.warning { background: linear-gradient(135deg, #f59e0b, #d97706); }
        .stat-icon.danger { background: linear-gradient(135deg, #ef4444, #dc2626); }
        .stat-icon.info { background: linear-gradient(135deg, #3b82f6, #2563eb); }

        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
        }
        .chart-card h5 {
            margin-bottom: 1rem;
            color: #1e293b;
            font-weight: 600;
        }

        .visitor-table {
            font-size: 0.875rem;
        }
        .visitor-table th {
            background: #f8fafc;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            font-size: 0.75rem;
            padding: 0.75rem;
        }
        .visitor-table td {
            padding: 0.75rem;
            vertical-align: middle;
        }

        .badge-bot { background: #94a3b8; }
        .badge-human { background: #22c55e; }
        .badge-desktop { background: #3b82f6; }
        .badge-mobile { background: #8b5cf6; }
        .badge-tablet { background: #f59e0b; }

        .country-flag {
            width: 20px;
            height: 15px;
            margin-right: 0.5rem;
            border-radius: 2px;
        }

        .device-icon {
            width: 24px;
            text-align: center;
            margin-right: 0.25rem;
        }

        .filter-bar {
            background: white;
            border-radius: 12px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .top-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .top-list li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .top-list li:last-child { border-bottom: none; }
        .top-list .count {
            background: #f1f5f9;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
        }

        .progress-bar-custom {
            height: 6px;
            border-radius: 3px;
            background: #e2e8f0;
            margin-top: 0.5rem;
        }
        .progress-bar-custom .fill {
            height: 100%;
            border-radius: 3px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .visitor-row:hover { background: #f8fafc; }
        .visitor-row td { cursor: pointer; }

        .ip-address { font-family: monospace; font-size: 0.8rem; 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>

        <div class="content-wrapper">
            <!-- Filter Bar -->
            <div class="filter-bar">
                <form method="GET" class="row g-3 align-items-center">
                    <div class="col-auto">
                        <label class="form-label mb-0 me-2">Site:</label>
                        <select name="site" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                            <option value="">All Sites</option>
                            <option value="landsales" <?php echo $site === 'landsales' ? 'selected' : ''; ?>>LandSales Pro</option>
                            <option value="landscanner" <?php echo $site === 'landscanner' ? 'selected' : ''; ?>>LandScanner</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <label class="form-label mb-0 me-2">Period:</label>
                        <select name="days" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                            <option value="7" <?php echo $days === 7 ? 'selected' : ''; ?>>Last 7 days</option>
                            <option value="30" <?php echo $days === 30 ? 'selected' : ''; ?>>Last 30 days</option>
                            <option value="90" <?php echo $days === 90 ? 'selected' : ''; ?>>Last 90 days</option>
                            <option value="365" <?php echo $days === 365 ? 'selected' : ''; ?>>Last year</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="bots" value="1" id="showBots"
                                   <?php echo $showBots ? 'checked' : ''; ?> onchange="this.form.submit()">
                            <label class="form-check-label" for="showBots">Show bots</label>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Stats Cards -->
            <div class="row g-4 mb-4">
                <div class="col-md-6 col-xl-3">
                    <div class="stat-card primary">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <div class="stat-value"><?php echo number_format($stats['total_visitors']); ?></div>
                                <div class="stat-label">Total Visitors</div>
                            </div>
                            <div class="stat-icon primary">
                                <i class="fas fa-users"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 col-xl-3">
                    <div class="stat-card success">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <div class="stat-value"><?php echo number_format($stats['human_visitors']); ?></div>
                                <div class="stat-label">Human Visitors</div>
                            </div>
                            <div class="stat-icon success">
                                <i class="fas fa-user"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 col-xl-3">
                    <div class="stat-card warning">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <div class="stat-value"><?php echo number_format($stats['bot_visitors']); ?></div>
                                <div class="stat-label">Bot Visits</div>
                            </div>
                            <div class="stat-icon warning">
                                <i class="fas fa-robot"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 col-xl-3">
                    <div class="stat-card info">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <div class="stat-value"><?php echo number_format($stats['total_pageviews']); ?></div>
                                <div class="stat-label">Total Pageviews</div>
                            </div>
                            <div class="stat-icon info">
                                <i class="fas fa-eye"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- Visitors Chart -->
                <div class="col-lg-8">
                    <div class="chart-card">
                        <h5><i class="fas fa-chart-line text-primary me-2"></i>Visitors Over Time</h5>
                        <canvas id="visitorsChart" height="100"></canvas>
                    </div>

                    <!-- Recent Visitors -->
                    <div class="chart-card">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="fas fa-history text-primary me-2"></i>Recent Visitors</h5>
                            <span class="badge bg-secondary"><?php echo number_format($totalVisitorsCount); ?> total</span>
                        </div>
                        <div class="table-responsive">
                            <table class="table visitor-table mb-0">
                                <thead>
                                    <tr>
                                        <th>Visitor</th>
                                        <th>Location</th>
                                        <th>Device</th>
                                        <th>Pages</th>
                                        <th>Last Visit</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentVisitors as $visitor): ?>
                                    <tr class="visitor-row" onclick="window.location='view.php?id=<?php echo $visitor['id']; ?>'">
                                        <td>
                                            <?php if ($visitor['is_bot']): ?>
                                                <span class="badge badge-bot"><i class="fas fa-robot me-1"></i><?php echo htmlspecialchars($visitor['bot_name'] ?: 'Bot'); ?></span>
                                            <?php else: ?>
                                                <span class="badge badge-human"><i class="fas fa-user me-1"></i>Human</span>
                                            <?php endif; ?>
                                            <br>
                                            <span class="ip-address"><?php echo htmlspecialchars($visitor['ip_address']); ?></span>
                                        </td>
                                        <td>
                                            <?php if ($visitor['country_code']): ?>
                                                <img src="https://flagcdn.com/w20/<?php echo strtolower($visitor['country_code']); ?>.png"
                                                     class="country-flag" alt="<?php echo $visitor['country_code']; ?>">
                                            <?php endif; ?>
                                            <?php echo htmlspecialchars($visitor['city'] ?: $visitor['country_name'] ?: 'Unknown'); ?>
                                            <?php if ($visitor['region'] && $visitor['city']): ?>
                                                <br><small class="text-muted"><?php echo htmlspecialchars($visitor['region']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?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; ?> device-icon text-muted"></i>
                                            <?php echo htmlspecialchars($visitor['browser'] ?: 'Unknown'); ?>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($visitor['os'] ?: ''); ?></small>
                                        </td>
                                        <td>
                                            <strong><?php echo number_format($visitor['pageviews'] ?? $visitor['total_pageviews']); ?></strong>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($visitor['last_page'] ?? ''); ?></small>
                                        </td>
                                        <td>
                                            <?php echo date('M j, H:i', strtotime($visitor['last_visit'])); ?>
                                            <br>
                                            <small class="text-muted"><?php echo timeAgo($visitor['last_visit']); ?></small>
                                        </td>
                                        <td>
                                            <a href="view.php?id=<?php echo $visitor['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($recentVisitors)): ?>
                                    <tr>
                                        <td colspan="6" class="text-center text-muted py-4">
                                            <i class="fas fa-users fa-3x mb-3 d-block"></i>
                                            No visitors recorded yet
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Side Panel -->
                <div class="col-lg-4">
                    <!-- Top Countries -->
                    <div class="chart-card">
                        <h5><i class="fas fa-globe text-success me-2"></i>Top Countries</h5>
                        <?php if (!empty($stats['top_countries'])): ?>
                        <ul class="top-list">
                            <?php
                            $maxCount = $stats['top_countries'][0]['count'] ?? 1;
                            foreach ($stats['top_countries'] as $country):
                            ?>
                            <li>
                                <div style="flex: 1;">
                                    <div class="d-flex align-items-center">
                                        <?php if ($country['country_code']): ?>
                                        <img src="https://flagcdn.com/w20/<?php echo strtolower($country['country_code']); ?>.png"
                                             class="country-flag" alt="">
                                        <?php endif; ?>
                                        <?php echo htmlspecialchars($country['country_name'] ?: 'Unknown'); ?>
                                    </div>
                                    <div class="progress-bar-custom">
                                        <div class="fill" style="width: <?php echo ($country['count'] / $maxCount) * 100; ?>%"></div>
                                    </div>
                                </div>
                                <span class="count"><?php echo number_format($country['count']); ?></span>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php else: ?>
                        <p class="text-muted text-center">No data available</p>
                        <?php endif; ?>
                    </div>

                    <!-- Device Breakdown -->
                    <div class="chart-card">
                        <h5><i class="fas fa-laptop text-info me-2"></i>Devices</h5>
                        <canvas id="devicesChart" height="200"></canvas>
                    </div>

                    <!-- Top Pages -->
                    <div class="chart-card">
                        <h5><i class="fas fa-file text-warning me-2"></i>Top Pages</h5>
                        <?php if (!empty($stats['top_pages'])): ?>
                        <ul class="top-list">
                            <?php foreach (array_slice($stats['top_pages'], 0, 8) as $page): ?>
                            <li>
                                <span class="text-truncate" style="max-width: 200px;" title="<?php echo htmlspecialchars($page['page_path']); ?>">
                                    <?php echo htmlspecialchars($page['page_path']); ?>
                                </span>
                                <span class="count"><?php echo number_format($page['views']); ?></span>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php else: ?>
                        <p class="text-muted text-center">No data available</p>
                        <?php endif; ?>
                    </div>

                    <!-- Browsers -->
                    <div class="chart-card">
                        <h5><i class="fas fa-globe text-secondary me-2"></i>Browsers</h5>
                        <?php if (!empty($stats['browsers'])): ?>
                        <ul class="top-list">
                            <?php foreach ($stats['browsers'] as $browser): ?>
                            <li>
                                <span><?php echo htmlspecialchars($browser['browser'] ?: 'Unknown'); ?></span>
                                <span class="count"><?php echo number_format($browser['count']); ?></span>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php else: ?>
                        <p class="text-muted text-center">No data available</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Visitors over time chart
        const dailyData = <?php echo json_encode($stats['daily_visitors']); ?>;

        new Chart(document.getElementById('visitorsChart'), {
            type: 'line',
            data: {
                labels: dailyData.map(d => {
                    const date = new Date(d.date);
                    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                }),
                datasets: [
                    {
                        label: 'Human Visitors',
                        data: dailyData.map(d => parseInt(d.humans)),
                        borderColor: '#22c55e',
                        backgroundColor: 'rgba(34, 197, 94, 0.1)',
                        fill: true,
                        tension: 0.4
                    },
                    {
                        label: 'Bot Visits',
                        data: dailyData.map(d => parseInt(d.bots)),
                        borderColor: '#94a3b8',
                        backgroundColor: 'rgba(148, 163, 184, 0.1)',
                        fill: true,
                        tension: 0.4
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        }
                    }
                }
            }
        });

        // Devices chart
        const devicesData = <?php echo json_encode($stats['devices']); ?>;

        new Chart(document.getElementById('devicesChart'), {
            type: 'doughnut',
            data: {
                labels: devicesData.map(d => d.device_type.charAt(0).toUpperCase() + d.device_type.slice(1)),
                datasets: [{
                    data: devicesData.map(d => parseInt(d.count)),
                    backgroundColor: ['#3b82f6', '#8b5cf6', '#f59e0b', '#94a3b8', '#ef4444'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    </script>
</body>
</html>
