// File: dashboard.js (Versi Gabungan)

document.addEventListener('DOMContentLoaded', () => {
    // === Elements ===
    const passwordPrompt = document.getElementById('password-prompt');
    const dashboardContent = document.getElementById('dashboard-content');
    const passwordInput = document.getElementById('password-input');
    const passwordSubmit = document.getElementById('password-submit');
    const passwordError = document.getElementById('password-error');
    const refreshButton = document.getElementById('refresh-button');

    // Tab Elements
    const tabLinks = document.querySelectorAll('.tab-link');
    const tabContents = document.querySelectorAll('.tab-content');

    // Orders Elements
    const ordersContainer = document.getElementById('orders-container');
    const totalOrdersCount = document.getElementById('total-orders-count');

    // Analytics Elements
    const viewsChartCtx = document.getElementById('views-chart').getContext('2d');
    const cartChartCtx = document.getElementById('cart-chart').getContext('2d');
    let viewsChart, cartChart;

    // === State ===
    const correctPassword = 'juraganfiber'; // Ganti kata sandi ini jika perlu

    // === Functions ===

    // --- Authentication ---
    function checkAuth() {
        if (sessionStorage.getItem('dashboard_auth') === 'true') {
            passwordPrompt.classList.add('hidden');
            dashboardContent.classList.remove('hidden');
            document.body.style.alignItems = 'flex-start';
            loadInitialData(); 
        } else {
            passwordPrompt.classList.remove('hidden');
            dashboardContent.classList.add('hidden');
        }
    }

    function handleLogin() {
        if (passwordInput.value === correctPassword) {
            sessionStorage.setItem('dashboard_auth', 'true');
            passwordError.textContent = '';
            checkAuth();
        } else {
            passwordError.textContent = 'Kata sandi salah. Coba lagi.';
            passwordInput.value = '';
        }
    }

    // --- Tab Management ---
    function setupTabs() {
        tabLinks.forEach(tab => {
            tab.addEventListener('click', () => {
                const targetTab = tab.dataset.tab;

                tabLinks.forEach(t => t.classList.remove('active'));
                tabContents.forEach(c => c.classList.remove('active'));

                tab.classList.add('active');
                document.getElementById(targetTab).classList.add('active');
            });
        });
    }
    
    // --- Data Fetching ---
    async function fetchData(endpoint) {
        // Tambahkan parameter unik untuk mencegah caching browser
        const url = `api.php?action=${endpoint}&_=${new Date().getTime()}`;
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Gagal mengambil data dari ${endpoint}: ${response.statusText}`);
        }
        const data = await response.json();
        if (data.error) {
            throw new Error(data.error);
        }
        return data;
    }
    
    function loadInitialData() {
        fetchOrders();
        fetchAnalytics();
    }

    // --- Orders --- 
    async function fetchOrders() {
        ordersContainer.innerHTML = '<p>Memuat data pesanan...</p>';
        try {
            const orders = await fetchData('get_orders');
            renderOrders(orders);
        } catch (error) {
            ordersContainer.innerHTML = `<p class="error-message">Gagal memuat pesanan: ${error.message}</p>`;
        }
    }

    function renderOrders(orders) {
        ordersContainer.innerHTML = '';
        totalOrdersCount.textContent = orders.length;

        if (orders.length === 0) {
            ordersContainer.innerHTML = '<p>Belum ada pesanan yang masuk.</p>';
            return;
        }

        orders.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

        orders.forEach(order => {
            const orderCard = document.createElement('div');
            orderCard.className = 'order-card';
            
            let itemsHtml = '<h4>Item Pesanan</h4>';
            try {
                const items = typeof order.order_details === 'string' ? JSON.parse(order.order_details) : order.order_details;
                items.forEach(item => {
                    itemsHtml += `
                        <div class="order-item">
                            <span class="item-name">${item.name || 'N/A'} (x${item.quantity || 1})</span>
                            <span class="item-price">Rp ${(item.price * item.quantity).toLocaleString('id-ID')}</span>
                        </div>`;
                });
            } catch (e) {
                 itemsHtml += '<p>Error memproses item.</p>';
            }
            
            const formattedDate = new Date(order.created_at).toLocaleString('id-ID', { dateStyle: 'long', timeStyle: 'short' });
            const waLink = `https://wa.me/${order.customer_phone.replace(/[^0-9]/g, '')}`;

            orderCard.innerHTML = `
                <div class="order-header">
                    <div>
                        <h3>${order.customer_name}</h3>
                        <span class="order-id">Pesanan #${order.id}</span>
                    </div>
                    <span class="order-date">${formattedDate}</span>
                </div>
                <div class="order-body">
                    <p><strong>No. HP:</strong> <a href="${waLink}" target="_blank">${order.customer_phone}</a></p>
                    <p><strong>Alamat:</strong> ${order.customer_address}</p>
                    ${order.notes ? `<p><strong>Catatan:</strong> ${order.notes}</p>` : ''}
                    <p><strong>Pembayaran:</strong> ${order.payment_method}</p>
                    <div class="order-items">${itemsHtml}</div>
                    <div class="order-total">Total: Rp ${Number(order.total_price).toLocaleString('id-ID')}</div>
                </div>
            `;
            ordersContainer.appendChild(orderCard);
        });
    }

    // --- Analytics ---
    async function fetchAnalytics() {
        try {
            const analyticsData = await fetchData('get_product_analytics');
            renderAnalyticsCharts(analyticsData);
        } catch (error) {
            console.error("Gagal memuat analitik:", error);
            document.getElementById('analytics').innerHTML = `<p class="error-message">Gagal memuat data analitik: ${error.message}</p>`;
        }
    }

    function renderAnalyticsCharts({ by_views, by_cart }) {
        if (viewsChart) viewsChart.destroy();
        if (cartChart) cartChart.destroy();

        viewsChart = createBarChart(viewsChartCtx, by_views, 'view_count', 'Produk Paling Banyak Dilihat');
        cartChart = createBarChart(cartChartCtx, by_cart, 'add_to_cart_count', 'Produk Paling Sering Ditambah ke Keranjang');
    }

    function createBarChart(ctx, data, dataKey, label) {
        return new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.map(p => p.name),
                datasets: [{
                    label: `Jumlah ${dataKey === 'view_count' ? 'Dilihat' : 'Ditambah ke Keranjang'}`, 
                    data: data.map(p => p[dataKey]),
                    backgroundColor: 'rgba(0, 123, 255, 0.6)',
                    borderColor: 'rgba(0, 123, 255, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }

    // === Event Listeners ===
    passwordSubmit.addEventListener('click', handleLogin);
    passwordInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') handleLogin();
    });
    refreshButton.addEventListener('click', loadInitialData);

    // === Initial Load ===
    setupTabs();
    checkAuth();
});
