@extends('layouts.layoutadmin')
@section('title', 'Statistik Rating')

@section('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">
        @include('admin.components.sidebar')
        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Statistik Rating</div>
                    <div class="subtitle">Laporan statistik rating dan feedback website</div>
                </div>
            </div>
            <div class="main-content">
                @if (session('error'))
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <span>{{ session('error') }}</span>
                    </div>
                @endif

                @if (session('success'))
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span>{{ session('success') }}</span>
                    </div>
                @endif

                <div class="stat-summary">
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fff4e6;color:#ff9800;">
                            <i class="fas fa-star"></i>
                        </div>
                        <div class="stat-title">Rating Rata-rata</div>
                        <div class="stat-value" id="averageRating">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="averageRatingLabel">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#e8f5e9;color:#4caf50;">
                            <i class="fas fa-comments"></i>
                        </div>
                        <div class="stat-title">Total Feedback</div>
                        <div class="stat-value" id="totalFeedbacks">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="totalFeedbacksLabel">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#e3f2fd;color:#2196f3;">
                            <i class="fas fa-chart-pie"></i>
                        </div>
                        <div class="stat-title">Status Rating</div>
                        <div class="stat-value" id="ratingStatus">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="ratingStatusLabel">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, #ff9800 0%, #f57c00 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(255, 152, 0, 0.3); transition: all 0.3s ease;"
                        onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(255, 152, 0, 0.4)';"
                        onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(255, 152, 0, 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 Rating 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="ratingChart"></canvas>
                        </div>
                    </div>
                </div>

                <div class="content-box">
                    <div class="content-box-header">
                        <h3><i class="fas fa-table"></i> Data Rating 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: center; font-weight: 700; color: #222;">Rating
                                            Rata-rata</th>
                                        <th style="padding: 12px; text-align: right; font-weight: 700; color: #222;">Total
                                            Feedback</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 = '{{ env('BASE_URL') }}';

        function getAuthToken() {
            return '{{ session('auth.token') }}';
        }

        let ratingChart = null;
        let globalStats = {}; // Variable global untuk menyimpan data summary
        let globalMonthlyStats = []; // Variable global untuk menyimpan data bulanan

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

        async function loadRatingStatistics() {
            const token = getAuthToken();

            try {
                const response = await fetch(`${baseUrl}/api/admin/visitor/rating`, {
                    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
                    const avgRating = stats.average_rating || 0;
                    document.getElementById('averageRating').textContent = avgRating.toFixed(2);
                    document.getElementById('averageRatingLabel').innerHTML = `<i class="fas fa-star"></i> dari 10.0`;

                    document.getElementById('totalFeedbacks').textContent = stats.total_feedbacks || 0;
                    document.getElementById('totalFeedbacksLabel').innerHTML =
                        `<i class="fas fa-comment"></i> Total Feedback`;

                    // Determine rating status
                    let statusText = 'Perlu Ditingkatkan';
                    let statusIcon = 'fa-sad-tear';
                    if (avgRating >= 8) {
                        statusText = 'Sangat Baik';
                        statusIcon = 'fa-laugh-beam';
                    } else if (avgRating >= 6) {
                        statusText = 'Baik';
                        statusIcon = 'fa-smile';
                    } else if (avgRating >= 4) {
                        statusText = 'Cukup';
                        statusIcon = 'fa-meh';
                    }

                    // Simpan status text di global object agar bisa dipakai di PDF
                    globalStats.statusText = statusText;

                    document.getElementById('ratingStatus').textContent = statusText;
                    document.getElementById('ratingStatusLabel').innerHTML = `<i class="fas ${statusIcon}"></i> Status`;

                    // Display chart
                    displayRatingChart(monthlyStats);

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

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

            // Sort by month
            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 ratingData = monthlyStats.map(stat => stat.average_rating);
            const feedbackData = monthlyStats.map(stat => stat.total_feedbacks);

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

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

            const ctx = document.getElementById('ratingChart').getContext('2d');
            ratingChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Rating Rata-rata',
                        data: ratingData,
                        backgroundColor: 'rgba(255, 152, 0, 0.8)',
                        borderColor: '#ff9800',
                        borderWidth: 2,
                        yAxisID: 'y',
                        order: 2
                    }, {
                        label: 'Total Feedback',
                        data: feedbackData,
                        type: 'line',
                        backgroundColor: 'rgba(76, 175, 80, 0.1)',
                        borderColor: '#4caf50',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#4caf50',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 5,
                        pointHoverRadius: 7,
                        yAxisID: 'y1',
                        order: 1
                    }]
                },
                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: '#ff9800',
                            borderWidth: 1,
                            displayColors: true,
                            callbacks: {
                                label: function(context) {
                                    if (context.datasetIndex === 0) {
                                        return 'Rating: ' + context.parsed.y.toFixed(2);
                                    } else {
                                        return 'Feedback: ' + context.parsed.y;
                                    }
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            type: 'linear',
                            position: 'left',
                            beginAtZero: true,
                            max: 10,
                            ticks: {
                                color: '#666',
                                font: {
                                    size: 12
                                },
                                callback: function(value) {
                                    return value.toFixed(1);
                                }
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            title: {
                                display: true,
                                text: 'Rating (0-10)',
                                color: '#ff9800',
                                font: {
                                    size: 12,
                                    weight: '600'
                                }
                            }
                        },
                        y1: {
                            type: 'linear',
                            position: 'right',
                            beginAtZero: true,
                            ticks: {
                                color: '#666',
                                font: {
                                    size: 12
                                }
                            },
                            grid: {
                                drawOnChartArea: false
                            },
                            title: {
                                display: true,
                                text: 'Total Feedback',
                                color: '#4caf50',
                                font: {
                                    size: 12,
                                    weight: '600'
                                }
                            }
                        },
                        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';
                const avgRating = stat.average_rating || 0;
                const starCount = Math.round(avgRating / 2);
                let stars = '';
                for (let i = 0; i < 5; i++) {
                    if (i < starCount) {
                        stars += '<i class="fas fa-star" style="color:#ff9800;"></i>';
                    } else {
                        stars += '<i class="far fa-star" style="color:#ddd;"></i>';
                    }
                }

                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: center;">
                            <div style="display: flex; flex-direction: column; align-items: center; gap: 4px;">
                                <div style="color: #ff9800; font-weight: 700; font-size: 1.2rem;">${avgRating.toFixed(2)}</div>
                                <div>${stars}</div>
                            </div>
                        </td>
                        <td style="padding: 14px; text-align: right; color: #4caf50; font-weight: 700; font-size: 1.1rem;">${stat.total_feedbacks}</td>
                    </tr>
                `;
            });

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

        function handleError() {
            document.getElementById('averageRating').textContent = '0';
            document.getElementById('averageRatingLabel').textContent = 'Error';
            document.getElementById('totalFeedbacks').textContent = '0';
            document.getElementById('totalFeedbacksLabel').textContent = 'Error';
            document.getElementById('ratingStatus').textContent = 'Error';
            document.getElementById('ratingStatusLabel').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 UNTUK RATING
        // ==========================================
        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();

                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, '.');

                // Header
                doc.setFontSize(18);
                doc.setFont(undefined, 'bold');
                doc.text('Laporan Statistik Rating Website', 14, 20);

                // 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);

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

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

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

                const avgRating = globalStats.average_rating ? globalStats.average_rating.toFixed(2) : "0.00";
                const totalFeed = globalStats.total_feedbacks || 0;
                const status = globalStats.statusText || "Tidak Diketahui";

                const summaryData = [
                    ['Rating Rata-rata', avgRating + ' / 10.0'],
                    ['Total Feedback', totalFeed.toLocaleString('id-ID') + ' ulasan'],
                    ['Status Performa', status]
                ];

                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('Detail Data Bulanan', 14, finalY);

                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'
                    });
                    const rate = stat.average_rating ? stat.average_rating.toFixed(2) : "0.00";
                    return [monthLabel, rate, stat.total_feedbacks.toLocaleString('id-ID')];
                });

                doc.autoTable({
                    startY: finalY + 4,
                    head: [
                        ['Bulan', 'Rating Rata-rata', 'Jumlah Feedback']
                    ],
                    body: monthlyData,
                    theme: 'striped',
                    headStyles: {
                        fillColor: [34, 193, 182],
                        textColor: [255, 255, 255],
                        fontStyle: 'bold',
                        fontSize: 11
                    },
                    bodyStyles: {
                        fontSize: 10
                    },
                    columnStyles: {
                        0: {
                            cellWidth: 80
                        },
                        1: {
                            cellWidth: 'auto',
                            halign: 'center'
                        },
                        2: {
                            cellWidth: 'auto',
                            halign: 'right'
                        }
                    },
                    margin: {
                        left: 14,
                        right: 14
                    }
                });

                // 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 Rating', 14, doc.internal
                        .pageSize.height - 10);
                }

                doc.save(`Laporan_Statistik_Rating_${dateStr}_${timeStr}.pdf`);

                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>
@endsection
