
<?php $__env->startSection('title', 'Statistik Pengunjung'); ?>

<?php $__env->startSection('styles'); ?>
    <style>
        body {
            background: #f4f4f4;
        }

        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
        }

        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        .main-header .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        .main-header .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
        }

        .main-content {
            padding: 32px;
        }

        .stat-summary {
            display: flex;
            gap: 24px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            flex: 1;
            padding: 24px 18px 18px 18px;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            min-width: 180px;
        }

        .stat-card .stat-icon {
            width: 44px;
            height: 44px;
            border-radius: 8px;
            background: #eaf6f3;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.6rem;
            margin-bottom: 8px;
        }

        .stat-card .stat-title {
            font-size: 1.05rem;
            color: #444;
            font-weight: 600;
            margin-bottom: 2px;
        }

        .stat-card .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #222;
            margin-bottom: 2px;
        }

        .stat-card .stat-growth {
            font-size: 0.98rem;
            color: #22c1b6;
            font-weight: 600;
            margin-bottom: 2px;
        }

        .content-box {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            overflow: hidden;
            margin-bottom: 24px;
        }

        .content-box-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .content-box-header h3 {
            margin: 0;
            font-size: 1.15rem;
            font-weight: 700;
            color: #222;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .content-box-header h3 i {
            color: #22c1b6;
        }

        .content-box-body {
            padding: 24px;
        }

        .chart-container {
            position: relative;
            height: 400px;
            width: 100%;
        }

        .loading-spinner {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .loading-spinner i {
            font-size: 32px;
            margin-bottom: 12px;
        }

        .alert {
            padding: 14px 18px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-danger {
            background: #fee;
            border: 1px solid #fcc;
            color: #c33;
        }

        .alert-success {
            background: #efe;
            border: 1px solid #cfc;
            color: #3c3;
        }
    </style>

    <div class="admin-dashboard">
        <?php echo $__env->make('admin.components.sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Statistik Pengunjung</div>
                    <div class="subtitle">Laporan statistik kunjungan website</div>
                </div>
            </div>
            <div class="main-content">
                <?php if(session('error')): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo e(session('error')); ?></span>
                    </div>
                <?php endif; ?>

                <?php if(session('success')): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo e(session('success')); ?></span>
                    </div>
                <?php endif; ?>

                <div class="stat-summary">
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#e8f4fd;color:#3498db;">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-title">Pengunjung Hari Ini</div>
                        <div class="stat-value" id="visitorToday">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="visitorTodayLabel">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fdf6e3;color:#f7b731;">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <div class="stat-title">Pengunjung Bulan Ini</div>
                        <div class="stat-value" id="visitorMonth">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="visitorMonthLabel">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fbeaf3;color:#d72660;">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <div class="stat-title">Total Pengunjung</div>
                        <div class="stat-value" id="visitorTotal">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="visitorTotalLabel">Loading...</div>
                    </div>
                </div>

                <div style="margin-bottom: 24px; display: flex; justify-content: flex-end;">
                    <button id="exportPdfBtn" onclick="exportToPDF()"
                        style="background: linear-gradient(135deg, #22c1b6 0%, #1aa89f 100%); color: white; border: none; padding: 12px 24px; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px; box-shadow: 0 2px 8px rgba(34, 193, 182, 0.3); transition: all 0.3s ease;"
                        onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(34, 193, 182, 0.4)';"
                        onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(34, 193, 182, 0.3)';">
                        <i class="fas fa-file-pdf"></i>
                        <span>Ekspor Laporan PDF</span>
                    </button>
                </div>

                <div class="content-box">
                    <div class="content-box-header">
                        <h3><i class="fas fa-chart-bar"></i> Statistik Pengunjung Bulanan</h3>
                    </div>
                    <div class="content-box-body">
                        <div id="chartLoading" class="loading-spinner">
                            <i class="fas fa-spinner fa-spin"></i>
                            <p>Memuat data chart...</p>
                        </div>
                        <div id="chartContainer" class="chart-container" style="display: none;">
                            <canvas id="visitorChart"></canvas>
                        </div>
                    </div>
                </div>

                <div class="content-box">
                    <div class="content-box-header">
                        <h3><i class="fas fa-table"></i> Data Pengunjung Per Bulan</h3>
                    </div>
                    <div class="content-box-body">
                        <div id="tableLoading" class="loading-spinner">
                            <i class="fas fa-spinner fa-spin"></i>
                            <p>Memuat data tabel...</p>
                        </div>
                        <div id="monthlyStatsTable" style="display: none;">
                            <table style="width: 100%; border-collapse: collapse;">
                                <thead>
                                    <tr style="background: #f4f4f4; border-bottom: 2px solid #e5e7eb;">
                                        <th style="padding: 12px; text-align: left; font-weight: 700; color: #222;">Bulan
                                        </th>
                                        <th style="padding: 12px; text-align: right; font-weight: 700; color: #222;">Total
                                            Pengunjung</th>
                                    </tr>
                                </thead>
                                <tbody id="monthlyStatsBody"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.31/jspdf.plugin.autotable.min.js"></script>

    <script>
        const baseUrl = '<?php echo e(env('BASE_URL')); ?>';

        function getAuthToken() {
            return '<?php echo e(session('auth.token')); ?>';
        }

        let visitorChart = null;
        let globalStats = {}; // Store stats globally for PDF export
        let globalMonthlyStats = []; // Store monthly stats globally for PDF export

        // Load statistics on page load
        document.addEventListener('DOMContentLoaded', async function() {
            await loadVisitorStatistics();
        });

        async function loadVisitorStatistics() {
            const token = getAuthToken();
            try {
                const response = await fetch(`${baseUrl}/api/admin/visitor/stats`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Accept': 'application/json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    const stats = data.stats || {};
                    const monthlyStats = data.monthly_stats || [];

                    // Store globally for PDF export
                    globalStats = stats;
                    globalMonthlyStats = monthlyStats;

                    // Update summary statistics
                    document.getElementById('visitorToday').textContent = stats.today || 0;
                    document.getElementById('visitorTodayLabel').innerHTML =
                        `<i class="fas fa-eye"></i> Kunjungan Hari Ini`;
                    document.getElementById('visitorMonth').textContent = stats.this_month || 0;
                    document.getElementById('visitorMonthLabel').innerHTML =
                        `<i class="fas fa-calendar-check"></i> Bulan Ini`;
                    document.getElementById('visitorTotal').textContent = stats.total || 0;
                    document.getElementById('visitorTotalLabel').innerHTML =
                        `<i class="fas fa-chart-bar"></i> Total Kunjungan`;

                    // Display chart and table
                    displayVisitorChart(monthlyStats);
                    displayMonthlyStatsTable(monthlyStats);
                } else {
                    handleError();
                }
            } catch (error) {
                console.error('Error loading visitor statistics:', error);
                handleError();
            }
        }

        function displayVisitorChart(monthlyStats) {
            if (!monthlyStats || monthlyStats.length === 0) {
                document.getElementById('chartLoading').innerHTML =
                    '<p style="text-align:center;color:#999;">Tidak ada data untuk ditampilkan</p>';
                return;
            }

            monthlyStats.sort((a, b) => a.month.localeCompare(b.month));

            const labels = monthlyStats.map(stat => {
                const date = new Date(stat.month + '-01');
                return date.toLocaleDateString('id-ID', {
                    month: 'short',
                    year: 'numeric'
                });
            });
            const data = monthlyStats.map(stat => stat.total_visitors);

            document.getElementById('chartLoading').style.display = 'none';
            document.getElementById('chartContainer').style.display = 'block';

            if (visitorChart) {
                visitorChart.destroy();
            }

            const ctx = document.getElementById('visitorChart').getContext('2d');
            visitorChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Pengunjung',
                        data: data,
                        backgroundColor: 'rgba(34, 193, 182, 0.1)',
                        borderColor: '#22c1b6',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#22c1b6',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        pointHoverRadius: 7
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: {
                                font: {
                                    size: 14,
                                    weight: '600'
                                },
                                color: '#222',
                                padding: 20
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            padding: 12,
                            borderColor: '#22c1b6',
                            borderWidth: 1,
                            displayColors: false,
                            callbacks: {
                                label: function(context) {
                                    return 'Pengunjung: ' + context.parsed.y.toLocaleString('id-ID');
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                color: '#666',
                                font: {
                                    size: 12
                                },
                                callback: function(value) {
                                    return value.toLocaleString('id-ID');
                                }
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            ticks: {
                                color: '#666',
                                font: {
                                    size: 12
                                }
                            },
                            grid: {
                                display: false
                            }
                        }
                    }
                }
            });
        }

        function displayMonthlyStatsTable(monthlyStats) {
            if (!monthlyStats || monthlyStats.length === 0) {
                document.getElementById('tableLoading').innerHTML =
                    '<p style="text-align:center;color:#999;">Tidak ada data untuk ditampilkan</p>';
                return;
            }

            monthlyStats.sort((a, b) => b.month.localeCompare(a.month));

            let html = '';
            monthlyStats.forEach((stat, index) => {
                const date = new Date(stat.month + '-01');
                const monthLabel = date.toLocaleDateString('id-ID', {
                    month: 'long',
                    year: 'numeric'
                });
                const bgColor = index % 2 === 0 ? '#fff' : '#f9f9f9';

                html += `
                    <tr style="background: ${bgColor}; border-bottom: 1px solid #e5e7eb;">
                        <td style="padding: 14px; color: #222; font-weight: 500;">${monthLabel}</td>
                        <td style="padding: 14px; text-align: right; color: #22c1b6; font-weight: 700; font-size: 1.1rem;">
                            ${stat.total_visitors.toLocaleString('id-ID')}
                        </td>
                    </tr>
                `;
            });

            document.getElementById('monthlyStatsBody').innerHTML = html;
            document.getElementById('tableLoading').style.display = 'none';
            document.getElementById('monthlyStatsTable').style.display = 'block';
        }

        function handleError() {
            document.getElementById('visitorToday').textContent = '0';
            document.getElementById('visitorTodayLabel').textContent = 'Error';
            document.getElementById('visitorMonth').textContent = '0';
            document.getElementById('visitorMonthLabel').textContent = 'Error';
            document.getElementById('visitorTotal').textContent = '0';
            document.getElementById('visitorTotalLabel').textContent = 'Error';
            document.getElementById('chartLoading').innerHTML =
                '<p style="text-align:center;color:#c33;">Gagal memuat data. Silakan refresh halaman.</p>';
            document.getElementById('tableLoading').innerHTML =
                '<p style="text-align:center;color:#c33;">Gagal memuat data. Silakan refresh halaman.</p>';
        }

        // Handle session expired
        if (typeof window.handleSessionExpired !== 'function') {
            window.handleSessionExpired = function() {
                if (window.sessionExpiredHandled) return;
                window.sessionExpiredHandled = true;
                alert('Session Anda telah habis. Silakan login ulang.');
                window.location.href = '/login';
            };
        }

        // ==========================================
        // FUNGSI EKSPOR PDF YANG SUDAH DIPERBAIKI
        // ==========================================
        async function exportToPDF() {
            const exportBtn = document.getElementById('exportPdfBtn');
            const originalContent = exportBtn.innerHTML;

            try {
                // Show loading state
                exportBtn.disabled = true;
                exportBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span>Membuat PDF...</span>';

                // Wait a bit for jsPDF to be ready
                await new Promise(resolve => setTimeout(resolve, 100));

                const {
                    jsPDF
                } = window.jspdf;
                const doc = new jsPDF();

                // Get current date for filename
                const now = new Date();
                const dateStr = now.toLocaleDateString('id-ID', {
                    day: '2-digit',
                    month: '2-digit',
                    year: 'numeric'
                }).replace(/\//g, '-');

                const timeStr = now.toLocaleTimeString('id-ID', {
                    hour: '2-digit',
                    minute: '2-digit'
                }).replace(/:/g, '.');

                // Add header
                doc.setFontSize(18);
                doc.setFont(undefined, 'bold');
                doc.text('Laporan Statistik Pengunjung Website', 14, 20);

                // Add generation date
                doc.setFontSize(10);
                doc.setFont(undefined, 'normal');
                doc.text(`Digenerate pada: ${now.toLocaleDateString('id-ID', { 
                    weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
                    hour: '2-digit', minute: '2-digit'
                })}`, 14, 28);

                // Add line separator
                doc.setLineWidth(0.5);
                doc.line(14, 32, 196, 32);

                // Summary Statistics Section
                doc.setFontSize(14);
                doc.setFont(undefined, 'bold');
                doc.text('Ringkasan Statistik', 14, 42);

                doc.setFontSize(11);
                doc.setFont(undefined, 'normal');

                const summaryData = [
                    ['Pengunjung Hari Ini', (globalStats.today || 0).toLocaleString('id-ID') + ' pengunjung'],
                    ['Pengunjung Bulan Ini', (globalStats.this_month || 0).toLocaleString('id-ID') + ' pengunjung'],
                    ['Total Pengunjung', (globalStats.total || 0).toLocaleString('id-ID') + ' pengunjung']
                ];

                doc.autoTable({
                    startY: 46,
                    head: [
                        ['Metrik', 'Nilai']
                    ],
                    body: summaryData,
                    theme: 'striped',
                    headStyles: {
                        fillColor: [34, 193, 182],
                        textColor: [255, 255, 255],
                        fontStyle: 'bold',
                        fontSize: 11
                    },
                    bodyStyles: {
                        fontSize: 10
                    },
                    columnStyles: {
                        0: {
                            cellWidth: 80,
                            fontStyle: 'bold'
                        },
                        1: {
                            cellWidth: 'auto',
                            halign: 'right'
                        }
                    },
                    margin: {
                        left: 14,
                        right: 14
                    }
                });

                // Monthly Statistics Section
                let finalY = doc.lastAutoTable.finalY + 10;

                doc.setFontSize(14);
                doc.setFont(undefined, 'bold');
                doc.text('Statistik Pengunjung Per Bulan', 14, finalY);

                // Prepare monthly data
                const sortedMonthlyStats = [...globalMonthlyStats].sort((a, b) => b.month.localeCompare(a.month));

                const monthlyData = sortedMonthlyStats.map(stat => {
                    const date = new Date(stat.month + '-01');
                    const monthLabel = date.toLocaleDateString('id-ID', {
                        month: 'long',
                        year: 'numeric'
                    });
                    return [monthLabel, stat.total_visitors.toLocaleString('id-ID')];
                });

                // Calculate total
                const totalVisitors = sortedMonthlyStats.reduce((sum, stat) => sum + stat.total_visitors, 0);

                doc.autoTable({
                    startY: finalY + 4,
                    head: [
                        ['Bulan', 'Total Pengunjung']
                    ],
                    body: monthlyData,
                    foot: [
                        ['TOTAL', totalVisitors.toLocaleString('id-ID')]
                    ],
                    theme: 'striped',
                    headStyles: {
                        fillColor: [34, 193, 182],
                        textColor: [255, 255, 255],
                        fontStyle: 'bold',
                        fontSize: 11
                    },
                    footStyles: {
                        fillColor: [34, 193, 182],
                        textColor: [255, 255, 255],
                        fontStyle: 'bold',
                        fontSize: 11
                    },
                    bodyStyles: {
                        fontSize: 10
                    },
                    columnStyles: {
                        0: {
                            cellWidth: 120
                        },
                        1: {
                            cellWidth: 'auto',
                            halign: 'right',
                            fontStyle: 'bold'
                        }
                    },
                    margin: {
                        left: 14,
                        right: 14
                    }
                });

                // Add footer
                const pageCount = doc.internal.getNumberOfPages();
                for (let i = 1; i <= pageCount; i++) {
                    doc.setPage(i);
                    doc.setFontSize(9);
                    doc.setFont(undefined, 'normal');
                    doc.setTextColor(150);
                    doc.text(`Halaman ${i} dari ${pageCount}`, doc.internal.pageSize.width / 2, doc.internal.pageSize
                        .height - 10, {
                            align: 'center'
                        });
                    doc.text('© ' + new Date().getFullYear() + ' - Sistem Informasi Statistik Pengunjung', 14, doc
                        .internal.pageSize.height - 10);
                }

                // Save PDF
                doc.save(`Laporan_Statistik_Pengunjung_${dateStr}_${timeStr}.pdf`);

                // Show success message
                exportBtn.innerHTML = '<i class="fas fa-check"></i> <span>Berhasil Diekspor!</span>';
                setTimeout(() => {
                    exportBtn.innerHTML = originalContent;
                    exportBtn.disabled = false;
                }, 2000);

            } catch (error) {
                console.error('Error exporting PDF:', error);
                alert('Gagal mengekspor PDF. Silakan coba lagi.');
                exportBtn.innerHTML = originalContent;
                exportBtn.disabled = false;
            }
        }
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.layoutadmin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laravel\krs-jawa3-template\daerah\resources\views/admin/statistikAdmin.blade.php ENDPATH**/ ?>