<?php
session_start(['read_and_close' => true]);
require('routeros_api.class.php');

// ===== CEK LOGIN =====
if (!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
    header('Location: index.php');
    exit;
}

// ===== FOLDER CACHE =====
$cacheDir = __DIR__ . '/cache';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

// ===== FILE CACHE - MULTI MIKROTIK SUPPORT =====
$mikrotikIpRaw = $_SESSION['ip'] ?? '';
$mikrotikIp = preg_replace('/[^0-9\.]/', '', $mikrotikIpRaw);
$cacheFile = $cacheDir . '/cache_comment_' . ($mikrotikIp ?: 'unknown') . '.json';

// ===== HELPER FUNCTIONS =====
function read_json_file_lock(string $path): array {
    if (!file_exists($path)) return [];
    $fp = @fopen($path, 'r');
    if (!$fp) return [];
    $contents = '';
    if (flock($fp, LOCK_SH)) {
        $contents = stream_get_contents($fp);
        flock($fp, LOCK_UN);
    }
    fclose($fp);
    $data = json_decode($contents, true);
    return is_array($data) ? $data : [];
}

function extractPrefix(string $comment): string {
    if (preg_match('/\d{2}\.\d{2}\.\d{2}-\d*([A-Za-z]+)/', $comment, $match)) {
        return strtoupper($match[1]);
    }
    return '-';
}

function extractDate(string $comment): string {
    if (preg_match('/(\d{2})\.(\d{2})\.(\d{2})/', $comment, $match)) {
        return '20' . $match[3] . '-' . $match[1] . '-' . $match[2];
    }
    return date('Y-m-d');
}

// ===== COLLECT DATA =====
$cacheData = read_json_file_lock($cacheFile);
$allComments = [];
$activeCount = 0;
$expiredCount = 0;
$prefixStats = [];
$dateStats = [];
$profileStats = [];

if (!empty($cacheData['data'])) {
    $allComments = array_merge($allComments, $cacheData['data']);
}
if (!empty($cacheData['expired'])) {
    $allComments = array_merge($allComments, $cacheData['expired']);
}

foreach ($allComments as $item) {
    $status = $item['status'] ?? 'active';
    $comment = $item['user']['comment'] ?? '';
    $profile = $item['user']['profile'] ?? 'unknown';
    $jumlah = (int)($item['jumlah'] ?? 0);
    $prefix = $item['prefix'] ?? extractPrefix($comment);
    $date = extractDate($comment);

    if ($status === 'active') {
        $activeCount++;
    } else {
        $expiredCount++;
    }

    // Prefix Stats
    if (!isset($prefixStats[$prefix])) {
        $prefixStats[$prefix] = ['count' => 0, 'users' => 0];
    }
    $prefixStats[$prefix]['count']++;
    $prefixStats[$prefix]['users'] += $jumlah;

    // Date Stats
    if (!isset($dateStats[$date])) {
        $dateStats[$date] = ['count' => 0, 'users' => 0];
    }
    $dateStats[$date]['count']++;
    $dateStats[$date]['users'] += $jumlah;

    // Profile Stats
    if (!isset($profileStats[$profile])) {
        $profileStats[$profile] = ['count' => 0, 'users' => 0];
    }
    $profileStats[$profile]['count']++;
    $profileStats[$profile]['users'] += $jumlah;
}

ksort($dateStats);
arsort($prefixStats);
arsort($profileStats);

$totalCount = $activeCount + $expiredCount;
$totalUsers = array_sum(array_column($allComments, 'jumlah', null));

// ===== PREPARE CHART DATA =====
$chartDates = array_keys($dateStats);
$chartCounts = array_map(function($d) { return $d['count']; }, array_values($dateStats));
$chartUsers = array_map(function($d) { return $d['users']; }, array_values($dateStats));

$prefixNames = array_keys($prefixStats);
$prefixCounts = array_map(function($p) { return $p['count']; }, array_values($prefixStats));

$profileNames = array_keys($profileStats);
$profileCounts = array_map(function($p) { return $p['count']; }, array_values($profileStats));

?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Analytics - Monitoring VCR</title>
    <link rel="icon" href="favicon.png" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: 100vh;
    padding: 20px;
}

/* ===== HEADER ===== */
header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 25px 30px;
    border-radius: 15px;
    margin-bottom: 30px;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.header-logo {
    font-size: 2.5em;
}

.header-info h1 {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 5px;
}

.header-info p {
    font-size: 14px;
    opacity: 0.9;
}

.header-mikrotik {
    background: rgba(255, 255, 255, 0.2);
    padding: 8px 15px;
    border-radius: 20px;
    font-size: 13px;
    backdrop-filter: blur(10px);
}

/* ===== MAIN ===== */
main {
    max-width: 1400px;
    margin: 0 auto;
}

/* ===== ACTION BAR ===== */
.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
    margin-bottom: 25px;
    flex-wrap: wrap;
}

.btn {
    padding: 12px 20px;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    background: white;
    color: #333;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.btn-primary:hover {
    box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
}

.btn-success {
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    color: white;
}

.btn-success:hover {
    box-shadow: 0 5px 20px rgba(40, 167, 69, 0.4);
}

/* ===== KPI CARDS ===== */
.kpi-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.kpi-card {
    background: white;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    border-left: 4px solid #667eea;
}

.kpi-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.kpi-card.active {
    border-left-color: #28a745;
}

.kpi-card.expired {
    border-left-color: #ff9800;
}

.kpi-card.total {
    border-left-color: #17a2b8;
}

.kpi-icon {
    font-size: 2.5em;
    margin-bottom: 10px;
}

.kpi-value {
    font-size: 32px;
    font-weight: 700;
    color: #333;
    margin-bottom: 5px;
}

.kpi-label {
    font-size: 14px;
    color: #999;
    font-weight: 600;
}

.kpi-percent {
    font-size: 12px;
    color: #666;
    margin-top: 8px;
}

/* ===== CHARTS ===== */
.charts-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.chart-card {
    background: white;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-title {
    font-size: 18px;
    font-weight: 700;
    color: #333;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.chart-wrapper {
    position: relative;
    height: 300px;
}

/* ===== TABLES ===== */
.tables-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 20px;
}

.table-card {
    background: white;
    padding: 25px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.table-card h3 {
    font-size: 18px;
    font-weight: 700;
    color: #333;
    margin-bottom: 20px;
}

.analytics-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}

.analytics-table th {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 12px;
    text-align: left;
    font-weight: 600;
}

.analytics-table td {
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
}

.analytics-table tbody tr:hover {
    background: #f8f9fa;
}

.rank-badge {
    background: linear-gradient(135deg, #ffc107 0%, #ffb74d 100%);
    color: #333;
    padding: 4px 10px;
    border-radius: 20px;
    font-weight: 700;
    font-size: 11px;
    min-width: 30px;
    text-align: center;
}

/* ===== EMPTY STATE ===== */
.empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #999;
}

.empty-state-icon {
    font-size: 48px;
    margin-bottom: 15px;
    opacity: 0.3;
}

/* ===== RESPONSIVE ===== */
@media (max-width: 1024px) {
    header {
        flex-direction: column;
        align-items: flex-start;
    }

    .charts-container {
        grid-template-columns: 1fr;
    }

    .tables-container {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    header {
        padding: 15px;
    }

    header h1 {
        font-size: 24px;
    }

    .kpi-container {
        grid-template-columns: repeat(2, 1fr);
    }

    .kpi-value {
        font-size: 24px;
    }

    .chart-wrapper {
        height: 250px;
    }

    .action-bar {
        flex-direction: column;
    }

    .btn {
        width: 100%;
        justify-content: center;
    }
}

@media (max-width: 480px) {
    main {
        padding: 0;
    }

    .kpi-container {
        grid-template-columns: 1fr;
    }

    .kpi-card {
        padding: 15px;
    }

    .kpi-value {
        font-size: 20px;
    }

    .chart-wrapper {
        height: 200px;
    }

    .table-card {
        padding: 15px;
    }

    .analytics-table {
        font-size: 12px;
    }

    .analytics-table th,
    .analytics-table td {
        padding: 8px;
    }
}

@media print {
    body {
        background: white;
        padding: 0;
    }

    .action-bar {
        display: none;
    }

    header {
        box-shadow: none;
        border-bottom: 2px solid #667eea;
    }

    .kpi-card,
    .chart-card,
    .table-card {
        page-break-inside: avoid;
        box-shadow: none;
        border: 1px solid #ddd;
    }

    @page {
        margin: 0.5cm;
        size: A4 landscape;
    }
}
    </style>
</head>
<body>

<header>
    <div class="header-left">
        <div class="header-logo">📊</div>
        <div class="header-info">
            <h1>Analytics Dashboard</h1>
            <p>Real-time Statistics & Reports</p>
        </div>
    </div>
    <div class="header-mikrotik">
        🔗 <?= htmlspecialchars($mikrotikIpRaw) ?>
    </div>
</header>

<main>
    <div class="action-bar">
        <div>
            <a href="index.php" class="btn btn-primary">
                <i class="fas fa-arrow-left"></i> Back to Home
            </a>
            <a href="comment.php" class="btn btn-success">
                <i class="fas fa-list"></i> View Comments
            </a>
        </div>
        <div>
            <button class="btn" onclick="printAnalytics()">
                <i class="fas fa-print"></i> Print
            </button>
            <button class="btn" onclick="exportCSV()">
                <i class="fas fa-download"></i> Export CSV
            </button>
        </div>
    </div>

    <?php if ($totalCount === 0): ?>
    <div class="empty-state">
        <div class="empty-state-icon">📭</div>
        <p>Belum ada data untuk ditampilkan</p>
    </div>
    <?php else: ?>

    <!-- KPI CARDS -->
    <div class="kpi-container">
        <div class="kpi-card active">
            <div class="kpi-icon">✅</div>
            <div class="kpi-value"><?= $activeCount ?></div>
            <div class="kpi-label">Active Comments</div>
            <div class="kpi-percent"><?= $totalCount > 0 ? number_format(($activeCount / $totalCount) * 100, 1) : 0 ?>% of Total</div>
        </div>

        <div class="kpi-card expired">
            <div class="kpi-icon">⏱️</div>
            <div class="kpi-value"><?= $expiredCount ?></div>
            <div class="kpi-label">Expired Comments</div>
            <div class="kpi-percent"><?= $totalCount > 0 ? number_format(($expiredCount / $totalCount) * 100, 1) : 0 ?>% of Total</div>
        </div>

        <div class="kpi-card total">
            <div class="kpi-icon">📋</div>
            <div class="kpi-value"><?= $totalCount ?></div>
            <div class="kpi-label">Total Comments</div>
            <div class="kpi-percent"><?= count($prefixStats) ?> Prefixes</div>
        </div>

        <div class="kpi-card">
            <div class="kpi-icon">👥</div>
            <div class="kpi-value"><?= $totalUsers ?></div>
            <div class="kpi-label">Total Users</div>
            <div class="kpi-percent">Across all comments</div>
        </div>
    </div>

    <!-- CHARTS -->
    <div class="charts-container">
        <div class="chart-card">
            <div class="chart-title">
                <i class="fas fa-chart-line"></i> Comments by Date
            </div>
            <div class="chart-wrapper">
                <canvas id="dateChart"></canvas>
            </div>
        </div>

        <div class="chart-card">
            <div class="chart-title">
                <i class="fas fa-chart-pie"></i> Status Distribution
            </div>
            <div class="chart-wrapper">
                <canvas id="statusChart"></canvas>
            </div>
        </div>

        <div class="chart-card">
            <div class="chart-title">
                <i class="fas fa-tag"></i> Comments by Prefix
            </div>
            <div class="chart-wrapper">
                <canvas id="prefixChart"></canvas>
            </div>
        </div>

        <div class="chart-card">
            <div class="chart-title">
                <i class="fas fa-users"></i> Comments by Profile
            </div>
            <div class="chart-wrapper">
                <canvas id="profileChart"></canvas>
            </div>
        </div>
    </div>

    <!-- TABLES -->
    <div class="tables-container">
        <div class="table-card">
            <h3>🏆 Top Prefixes</h3>
            <table class="analytics-table">
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Prefix</th>
                        <th>Count</th>
                        <th>Users</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $rank = 1;
                    foreach (array_slice($prefixStats, 0, 5) as $prefix => $stats): ?>
                    <tr>
                        <td><span class="rank-badge">#<?= $rank++ ?></span></td>
                        <td><strong><?= htmlspecialchars($prefix) ?></strong></td>
                        <td><?= $stats['count'] ?></td>
                        <td><?= $stats['users'] ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="table-card">
            <h3>👥 Top Profiles</h3>
            <table class="analytics-table">
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Profile</th>
                        <th>Count</th>
                        <th>Users</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $rank = 1;
                    foreach (array_slice($profileStats, 0, 5) as $profile => $stats): ?>
                    <tr>
                        <td><span class="rank-badge">#<?= $rank++ ?></span></td>
                        <td><strong><?= htmlspecialchars($profile) ?></strong></td>
                        <td><?= $stats['count'] ?></td>
                        <td><?= $stats['users'] ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="table-card">
            <h3>📅 Latest Dates</h3>
            <table class="analytics-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Count</th>
                        <th>Users</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (array_slice(array_reverse($dateStats), 0, 8) as $date => $stats): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($date) ?></strong></td>
                        <td><?= $stats['count'] ?></td>
                        <td><?= $stats['users'] ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php endif; ?>

</main>

<script>
const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
        legend: {
            labels: {
                font: { size: 12, weight: '600' },
                padding: 15,
                usePointStyle: true
            }
        }
    }
};

const primaryColor = 'rgb(102, 126, 234)';
const secondaryColor = 'rgb(118, 75, 162)';
const successColor = 'rgb(40, 167, 69)';
const warningColor = 'rgb(255, 152, 0)';

<?php if ($totalCount > 0): ?>

// 1. Date Chart
const dateCtx = document.getElementById('dateChart');
if (dateCtx) {
    new Chart(dateCtx, {
        type: 'line',
        data: {
            labels: <?= json_encode($chartDates) ?>,
            datasets: [
                {
                    label: 'Comments',
                    data: <?= json_encode($chartCounts) ?>,
                    borderColor: primaryColor,
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    borderWidth: 3,
                    tension: 0.4,
                    fill: true,
                    pointRadius: 5,
                    pointBackgroundColor: primaryColor,
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2
                },
                {
                    label: 'Users',
                    data: <?= json_encode($chartUsers) ?>,
                    borderColor: secondaryColor,
                    backgroundColor: 'rgba(118, 75, 162, 0.1)',
                    borderWidth: 3,
                    tension: 0.4,
                    fill: false,
                    pointRadius: 5,
                    pointBackgroundColor: secondaryColor,
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2
                }
            ]
        },
        options: {
            ...chartOptions,
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0, 0, 0, 0.05)' }
                },
                x: {
                    grid: { color: 'rgba(0, 0, 0, 0.05)' }
                }
            }
        }
    });
}

// 2. Status Chart
const statusCtx = document.getElementById('statusChart');
if (statusCtx) {
    new Chart(statusCtx, {
        type: 'doughnut',
        data: {
            labels: ['Active', 'Expired'],
            datasets: [{
                data: [<?= $activeCount ?>, <?= $expiredCount ?>],
                backgroundColor: [successColor, warningColor],
                borderColor: ['#fff', '#fff'],
                borderWidth: 2
            }]
        },
        options: chartOptions
    });
}

// 3. Prefix Chart
const prefixCtx = document.getElementById('prefixChart');
if (prefixCtx) {
    new Chart(prefixCtx, {
        type: 'bar',
        data: {
            labels: <?= json_encode(array_slice($prefixNames, 0, 8)) ?>,
            datasets: [{
                label: 'Count',
                data: <?= json_encode(array_slice($prefixCounts, 0, 8)) ?>,
                backgroundColor: [
                    primaryColor,
                    secondaryColor,
                    successColor,
                    warningColor,
                    '#17a2b8',
                    '#6c757d',
                    '#fd7e14',
                    '#e83e8c'
                ],
                borderRadius: 6,
                borderSkipped: false
            }]
        },
        options: {
            ...chartOptions,
            indexAxis: 'y',
            scales: {
                x: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0, 0, 0, 0.05)' }
                },
                y: {
                    grid: { color: 'rgba(0, 0, 0, 0.05)' }
                }
            }
        }
    });
}

// 4. Profile Chart
const profileCtx = document.getElementById('profileChart');
if (profileCtx) {
    new Chart(profileCtx, {
        type: 'bar',
        data: {
            labels: <?= json_encode(array_slice($profileNames, 0, 8)) ?>,
            datasets: [{
                label: 'Count',
                data: <?= json_encode(array_slice($profileCounts, 0, 8)) ?>,
                backgroundColor: primaryColor,
                borderColor: secondaryColor,
                borderWidth: 1,
                borderRadius: 6,
                borderSkipped: false
            }]
        },
        options: {
            ...chartOptions,
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0, 0, 0, 0.05)' }
                },
                x: {
                    grid: { color: 'rgba(0, 0, 0, 0.05)' }
                }
            }
        }
    });
}

<?php endif; ?>

function printAnalytics() {
    window.print();
}

function exportCSV() {
    let csv = 'Monitoring VCR Analytics Report\n';
    csv += 'Generated: ' + new Date().toLocaleString('id-ID') + '\n';
    csv += 'Mikrotik IP: <?= htmlspecialchars($mikrotikIpRaw) ?>\n\n';

    csv += 'SUMMARY\n';
    csv += 'Active Comments,<?= $activeCount ?>\n';
    csv += 'Expired Comments,<?= $expiredCount ?>\n';
    csv += 'Total Comments,<?= $totalCount ?>\n';
    csv += 'Total Users,<?= $totalUsers ?>\n\n';

    csv += 'TOP PREFIXES\n';
    csv += 'Prefix,Count,Users\n';
    <?php foreach (array_slice($prefixStats, 0, 10) as $prefix => $stats): ?>
    csv += '<?= htmlspecialchars($prefix) ?>,<?= $stats['count'] ?>,<?= $stats['users'] ?>\n';
    <?php endforeach; ?>

    csv += '\nTOP PROFILES\n';
    csv += 'Profile,Count,Users\n';
    <?php foreach (array_slice($profileStats, 0, 10) as $profile => $stats): ?>
    csv += '<?= htmlspecialchars($profile) ?>,<?= $stats['count'] ?>,<?= $stats['users'] ?>\n';
    <?php endforeach; ?>

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'analytics-<?= $mikrotikIp ?>-' + new Date().toISOString().split('T')[0] + '.csv';
    link.click();
}
</script>

</body>
</html>