<?php
// Konfigurasi Database
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Default range tanggal: bulan ini
$start_date = date('Y-m-01');
$end_date = date('Y-m-t');

// Filter tambahan
$cabang_filter = '';
$brand_filter = '';
$tipe_filter = '';

// Jika form disubmit, ambil dari input
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $cabang_filter = isset($_POST['cabang']) ? $_POST['cabang'] : '';
    $brand_filter = isset($_POST['brand']) ? $_POST['brand'] : '';
    $tipe_filter = isset($_POST['tipe']) ? $_POST['tipe'] : '';
}

// Query untuk mendapatkan nilai unik untuk filter
$cabang_query = "SELECT DISTINCT cab FROM jual ORDER BY cab";
$brand_query = "SELECT DISTINCT brand FROM jual ORDER BY brand";
$tipe_query = "SELECT DISTINCT kode, nama FROM tipe_transaksi ORDER BY nama";

$cabang_result = $conn->query($cabang_query);
$brand_result = $conn->query($brand_query);
$tipe_result = $conn->query($tipe_query);

// Query utama
$sql = "
SELECT 
    jual.brand,
    jual.cab,
    tipe_transaksi.nama AS tipe_nama,
    jual.mesin,
    jual.nomor,
    jual.tanggal,
    jual.jamm,
    jual.shift,
    jual.cover,
    jual.user AS user_jual,
    jual.batal,
    jual.kasir,
    jual.register,
    jual.deliver,
    pesani.sub,
    pesani.payment,
    pesani.tglo,
    pesani.kode,
    pesani.name AS nama_barang,
    pesani.group_name,
    pesani.quantity,
    pesani.harga,
    pesani.price,
    pesani.discp,
    pesani.discr,
    pesani.netto,
    pesani.disc,
    pesani.ppn,
    pesani.pajak,
    pesani.serv,
    pesani.service,
    pesani.jumlah,
    pesani.meja,
    pesani.user AS user_pesani
FROM jual
LEFT JOIN pesani ON jual.nomor = pesani.nomor
LEFT JOIN tipe_transaksi ON jual.tipe = tipe_transaksi.kode
WHERE jual.tanggal BETWEEN ? AND ?
  AND jual.batal = 0";

// Tambahkan filter jika ada
$params = [$start_date, $end_date];
$types = "ss";

if (!empty($cabang_filter)) {
    $sql .= " AND jual.cab = ?";
    $params[] = $cabang_filter;
    $types .= "s";
}

if (!empty($brand_filter)) {
    $sql .= " AND jual.brand = ?";
    $params[] = $brand_filter;
    $types .= "s";
}

if (!empty($tipe_filter)) {
    $sql .= " AND jual.tipe = ?";
    $params[] = $tipe_filter;
    $types .= "s";
}

$sql .= " ORDER BY jual.tanggal ASC, jual.nomor ASC, pesani.kode ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Pastikan kolom numerik tetap numerik untuk agregasi di pivot
    $row['quantity'] = (float)$row['quantity'];
    $row['harga'] = (float)$row['harga'];
    $row['jumlah'] = (float)$row['jumlah'];
    $row['discr'] = (float)$row['discr'];
    $row['pajak'] = (float)$row['pajak'];
    $row['service'] = (float)$row['service'];
    $data[] = $row;
}

$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Dashboard Analitik Penjualan</title>
    
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pivottable/2.23.0/pivot.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/pivottable/2.23.0/pivot.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.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>
    
    <style>
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            margin: 0; 
            padding: 0; 
            background-color: #f8f9fa;
            color: #333;
        }
        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .header h1 {
            margin: 0;
            font-size: 28px;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        .dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 20px;
            transition: transform 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .card h3 {
            margin-top: 0;
            color: #2575fc;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .card .value {
            font-size: 32px;
            font-weight: bold;
            margin: 15px 0;
        }
        .filter { 
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 20px;
        }
        .filter-row {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 15px;
        }
        .filter-group {
            flex: 1;
            min-width: 200px;
        }
        label { 
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #555;
        }
        input[type="date"], select { 
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button { 
            padding: 10px 20px; 
            background: #2575fc; 
            color: white; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer;
            font-weight: 600;
            transition: background 0.3s;
        }
        button:hover { 
            background: #1a68e0; 
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        .btn-secondary {
            background: #6c757d;
        }
        .btn-secondary:hover {
            background: #5a6268;
        }
        .btn-success {
            background: #28a745;
        }
        .btn-success:hover {
            background: #218838;
        }
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background: #e0a800;
        }
        .pvtUI { 
            margin-top: 20px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-radius: 8px;
            overflow: hidden;
        }
        .no-data { 
            color: #dc3545; 
            font-weight: bold; 
            margin-top: 20px;
            text-align: center;
            padding: 20px;
            background: #f8d7da;
            border-radius: 8px;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background: #f1f1f1;
            border: 1px solid #ddd;
            border-bottom: none;
            border-radius: 4px 4px 0 0;
            margin-right: 5px;
        }
        .tab.active {
            background: white;
            border-bottom: 1px solid white;
            margin-bottom: -1px;
            font-weight: bold;
            color: #2575fc;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .chart-container {
            height: 300px;
            margin-bottom: 20px;
        }
        .template-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
        }
        .template-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
        }
        .template-item:hover {
            background: #f5f5f5;
        }
        .template-item .delete {
            color: #dc3545;
            cursor: pointer;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }
        .modal-content {
            background: white;
            margin: 10% auto;
            padding: 20px;
            width: 50%;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        .close {
            float: right;
            font-size: 24px;
            cursor: pointer;
        }
        @media (max-width: 768px) {
            .filter-row {
                flex-direction: column;
            }
            .action-buttons {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <h1>📊 Dashboard Analitik Penjualan</h1>
    <p>Analisis data penjualan dengan pivot table dan visualisasi grafik</p>
</div>

<div class="container">
    <!-- Dashboard Cards -->
    <div class="dashboard">
        <div class="card">
            <h3>Total Transaksi</h3>
            <div class="value" id="total-transaksi">0</div>
            <p>Jumlah transaksi dalam periode ini</p>
        </div>
        <div class="card">
            <h3>Total Penjualan</h3>
            <div class="value" id="total-penjualan">Rp 0</div>
            <p>Total nilai penjualan</p>
        </div>
        <div class="card">
            <h3>Rata-rata Transaksi</h3>
            <div class="value" id="avg-transaksi">Rp 0</div>
            <p>Rata-rata nilai per transaksi</p>
        </div>
        <div class="card">
            <h3>Item Terlaris</h3>
            <div class="value" id="item-terlaris">-</div>
            <p>Item dengan penjualan tertinggi</p>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter">
        <h3>Filter Data</h3>
        <form method="POST" id="filter-form">
            <div class="filter-row">
                <div class="filter-group">
                    <label>Tanggal Mulai:</label>
                    <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" required>
                </div>
                <div class="filter-group">
                    <label>Tanggal Akhir:</label>
                    <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" required>
                </div>
                <div class="filter-group">
                    <label>Cabang:</label>
                    <select name="cabang">
                        <option value="">Semua Cabang</option>
                        <?php while ($row = $cabang_result->fetch_assoc()): ?>
                            <option value="<?= htmlspecialchars($row['cab']) ?>" <?= $cabang_filter == $row['cab'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($row['cab']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Brand:</label>
                    <select name="brand">
                        <option value="">Semua Brand</option>
                        <?php while ($row = $brand_result->fetch_assoc()): ?>
                            <option value="<?= htmlspecialchars($row['brand']) ?>" <?= $brand_filter == $row['brand'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($row['brand']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Tipe Transaksi:</label>
                    <select name="tipe">
                        <option value="">Semua Tipe</option>
                        <?php while ($row = $tipe_result->fetch_assoc()): ?>
                            <option value="<?= htmlspecialchars($row['kode']) ?>" <?= $tipe_filter == $row['kode'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($row['nama']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
            </div>
            <div class="action-buttons">
                <button type="submit">Terapkan Filter</button>
                <button type="button" class="btn-secondary" id="reset-filter">Reset Filter</button>
            </div>
        </form>
    </div>

    <?php if (empty($data)): ?>
        <div class="no-data">
            ❌ Tidak ada data penjualan untuk rentang tanggal dan filter ini.
        </div>
    <?php else: ?>
        <p><strong>💡 Drag & drop field</strong> di bawah untuk menganalisa <strong><?= count($data) ?> baris data</strong> dari tanggal <strong><?= $start_date ?></strong> sampai <strong><?= $end_date ?></strong></p>
        
        <!-- Tabs -->
        <div class="tabs">
            <div class="tab active" data-tab="pivot">Pivot Table</div>
            <div class="tab" data-tab="charts">Grafik</div>
            <div class="tab" data-tab="templates">Template</div>
        </div>
        
        <!-- Tab Content -->
        <div class="tab-content active" id="pivot-tab">
            <div class="action-buttons">
                <button id="save-template" class="btn-success">Simpan Template</button>
                <button id="export-csv" class="btn-secondary">Export CSV</button>
                <button id="export-excel" class="btn-secondary">Export Excel</button>
                <button id="export-pdf" class="btn-secondary">Export PDF</button>
            </div>
            <div id="output"></div>
        </div>
        
        <div class="tab-content" id="charts-tab">
            <div class="action-buttons">
                <button id="refresh-charts" class="btn-warning">Refresh Grafik</button>
            </div>
            <div class="dashboard">
                <div class="card">
                    <h3>Penjualan per Cabang</h3>
                    <div class="chart-container">
                        <canvas id="cabang-chart"></canvas>
                    </div>
                </div>
                <div class="card">
                    <h3>Penjualan per Brand</h3>
                    <div class="chart-container">
                        <canvas id="brand-chart"></canvas>
                    </div>
                </div>
                <div class="card">
                    <h3>Penjualan per Tipe Transaksi</h3>
                    <div class="chart-container">
                        <canvas id="tipe-chart"></canvas>
                    </div>
                </div>
                <div class="card">
                    <h3>Tren Penjualan Harian</h3>
                    <div class="chart-container">
                        <canvas id="tren-chart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="tab-content" id="templates-tab">
            <h3>Template Pivot Table</h3>
            <div class="action-buttons">
                <button id="save-template-btn" class="btn-success">Simpan Template Saat Ini</button>
                <button id="load-template-btn" class="btn-secondary">Load Template</button>
            </div>
            <div class="template-list" id="template-list">
                <!-- Template list will be populated by JavaScript -->
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Save Template Modal -->
<div id="save-template-modal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h3>Simpan Template</h3>
        <p>Masukkan nama template:</p>
        <input type="text" id="template-name" class="form-control" style="width: 100%; padding: 8px; margin: 10px 0;">
        <div class="action-buttons">
            <button id="confirm-save-template" class="btn-success">Simpan</button>
            <button id="cancel-save-template" class="btn-secondary">Batal</button>
        </div>
    </div>
</div>

<script>
    // Global variables
    let currentPivotConfig = null;
    let pivotData = null;
    let templates = JSON.parse(localStorage.getItem('pivotTemplates')) || [];
    
    // Initialize dashboard
    $(document).ready(function() {
        // Initialize dashboard metrics
        updateDashboardMetrics();
        
        // Initialize tabs
        $('.tab').click(function() {
            const tabId = $(this).data('tab');
            $('.tab').removeClass('active');
            $(this).addClass('active');
            $('.tab-content').removeClass('active');
            $(`#${tabId}-tab`).addClass('active');
            
            // Initialize charts when charts tab is opened
            if (tabId === 'charts') {
                initializeCharts();
            }
            
            // Load templates when templates tab is opened
            if (tabId === 'templates') {
                loadTemplatesList();
            }
        });
        
        // Reset filter
        $('#reset-filter').click(function() {
            $('#filter-form')[0].reset();
            $('#filter-form').submit();
        });
        
        // Initialize pivot table if data exists
        <?php if (!empty($data)): ?>
            pivotData = <?= json_encode($data); ?>;
            initializePivotTable();
        <?php endif; ?>
        
        // Modal handling
        $('#save-template').click(function() {
            $('#save-template-modal').show();
        });
        
        $('.close, #cancel-save-template').click(function() {
            $('#save-template-modal').hide();
        });
        
        $('#confirm-save-template').click(function() {
            const templateName = $('#template-name').val().trim();
            if (templateName) {
                saveTemplate(templateName);
                $('#save-template-modal').hide();
                $('#template-name').val('');
            }
        });
        
        // Export buttons
        $('#export-csv').click(exportToCSV);
        $('#export-excel').click(exportToExcel);
        $('#export-pdf').click(exportToPDF);
        
        // Template buttons
        $('#save-template-btn').click(function() {
            $('#save-template-modal').show();
        });
        
        $('#load-template-btn').click(function() {
            if (templates.length > 0) {
                const templateName = prompt('Masukkan nama template yang ingin dimuat:');
                if (templateName) {
                    loadTemplate(templateName);
                }
            } else {
                alert('Tidak ada template yang tersedia.');
            }
        });
        
        // Refresh charts
        $('#refresh-charts').click(function() {
            initializeCharts();
        });
    });
    
    // Update dashboard metrics
    function updateDashboardMetrics() {
        <?php if (!empty($data)): ?>
            const data = <?= json_encode($data); ?>;
            
            // Calculate metrics
            const totalTransaksi = new Set(data.map(item => item.nomor)).size;
            const totalPenjualan = data.reduce((sum, item) => sum + item.jumlah, 0);
            const avgTransaksi = totalPenjualan / totalTransaksi;
            
            // Find top selling item
            const itemSales = {};
            data.forEach(item => {
                if (!itemSales[item.nama_barang]) {
                    itemSales[item.nama_barang] = 0;
                }
                itemSales[item.nama_barang] += item.quantity;
            });
            
            let topItem = '-';
            let maxQuantity = 0;
            for (const item in itemSales) {
                if (itemSales[item] > maxQuantity) {
                    maxQuantity = itemSales[item];
                    topItem = item;
                }
            }
            
            // Update UI
            $('#total-transaksi').text(totalTransaksi.toLocaleString('id-ID'));
            $('#total-penjualan').text('Rp ' + totalPenjualan.toLocaleString('id-ID', {minimumFractionDigits: 0, maximumFractionDigits: 0}));
            $('#avg-transaksi').text('Rp ' + avgTransaksi.toLocaleString('id-ID', {minimumFractionDigits: 0, maximumFractionDigits: 0}));
            $('#item-terlaris').text(topItem);
        <?php endif; ?>
    }
    
    // Initialize pivot table
    function initializePivotTable() {
        $("#output").pivotUI(
            pivotData,
            {
                rows: ["group_name", "nama_barang"],
                cols: ["tipe_nama"],
                aggregatorName: "Sum",
                vals: ["jumlah"],
                rendererName: "Table Barchart",
                onRefresh: function(config) {
                    currentPivotConfig = config;
                }
            }
        );
    }
    
    // Initialize charts
    function initializeCharts() {
        if (!pivotData) return;
        
        // Prepare data for charts
        const cabangData = {};
        const brandData = {};
        const tipeData = {};
        const trenData = {};
        
        pivotData.forEach(item => {
            // Cabang data
            if (!cabangData[item.cab]) {
                cabangData[item.cab] = 0;
            }
            cabangData[item.cab] += item.jumlah;
            
            // Brand data
            if (!brandData[item.brand]) {
                brandData[item.brand] = 0;
            }
            brandData[item.brand] += item.jumlah;
            
            // Tipe data
            if (!tipeData[item.tipe_nama]) {
                tipeData[item.tipe_nama] = 0;
            }
            tipeData[item.tipe_nama] += item.jumlah;
            
            // Tren data (per tanggal)
            if (!trenData[item.tanggal]) {
                trenData[item.tanggal] = 0;
            }
            trenData[item.tanggal] += item.jumlah;
        });
        
        // Sort tren data by date
        const sortedTrenData = Object.keys(trenData).sort().map(date => {
            return { date, value: trenData[date] };
        });
        
        // Create charts
        createBarChart('cabang-chart', Object.keys(cabangData), Object.values(cabangData), 'Penjualan per Cabang');
        createBarChart('brand-chart', Object.keys(brandData), Object.values(brandData), 'Penjualan per Brand');
        createPieChart('tipe-chart', Object.keys(tipeData), Object.values(tipeData), 'Penjualan per Tipe Transaksi');
        createLineChart('tren-chart', sortedTrenData.map(item => item.date), sortedTrenData.map(item => item.value), 'Tren Penjualan Harian');
    }
    
    // Create bar chart
    function createBarChart(canvasId, labels, data, title) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // Destroy existing chart if it exists
        if (window[canvasId + 'Chart']) {
            window[canvasId + 'Chart'].destroy();
        }
        
        window[canvasId + 'Chart'] = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: title,
                    data: data,
                    backgroundColor: 'rgba(37, 117, 252, 0.6)',
                    borderColor: 'rgba(37, 117, 252, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'Rp ' + context.raw.toLocaleString('id-ID');
                            }
                        }
                    }
                }
            }
        });
    }
    
    // Create pie chart
    function createPieChart(canvasId, labels, data, title) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // Destroy existing chart if it exists
        if (window[canvasId + 'Chart']) {
            window[canvasId + 'Chart'].destroy();
        }
        
        // Generate colors
        const colors = labels.map((_, i) => {
            const hue = (i * 360) / labels.length;
            return `hsla(${hue}, 70%, 60%, 0.8)`;
        });
        
        window[canvasId + 'Chart'] = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    label: title,
                    data: data,
                    backgroundColor: colors,
                    borderColor: colors.map(color => color.replace('0.8', '1')),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.raw;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: Rp ${value.toLocaleString('id-ID')} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // Create line chart
    function createLineChart(canvasId, labels, data, title) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        
        // Destroy existing chart if it exists
        if (window[canvasId + 'Chart']) {
            window[canvasId + 'Chart'].destroy();
        }
        
        window[canvasId + 'Chart'] = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: title,
                    data: data,
                    backgroundColor: 'rgba(37, 117, 252, 0.2)',
                    borderColor: 'rgba(37, 117, 252, 1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'Rp ' + context.raw.toLocaleString('id-ID');
                            }
                        }
                    }
                }
            }
        });
    }
    
    // Save template
    function saveTemplate(name) {
        if (!currentPivotConfig) {
            alert('Tidak ada konfigurasi pivot table untuk disimpan.');
            return;
        }
        
        const template = {
            name: name,
            config: currentPivotConfig,
            date: new Date().toISOString()
        };
        
        // Check if template with same name exists
        const existingIndex = templates.findIndex(t => t.name === name);
        if (existingIndex !== -1) {
            if (confirm('Template dengan nama ini sudah ada. Apakah Anda ingin menggantinya?')) {
                templates[existingIndex] = template;
            } else {
                return;
            }
        } else {
            templates.push(template);
        }
        
        localStorage.setItem('pivotTemplates', JSON.stringify(templates));
        alert('Template berhasil disimpan!');
    }
    
    // Load template
    function loadTemplate(name) {
        const template = templates.find(t => t.name === name);
        if (!template) {
            alert('Template tidak ditemukan.');
            return;
        }
        
        // Apply template config
        $("#output").pivotUI(
            pivotData,
            template.config
        );
        
        // Switch to pivot tab
        $('.tab').removeClass('active');
        $('.tab[data-tab="pivot"]').addClass('active');
        $('.tab-content').removeClass('active');
        $('#pivot-tab').addClass('active');
    }
    
    // Load templates list
    function loadTemplatesList() {
        const templateList = $('#template-list');
        templateList.empty();
        
        if (templates.length === 0) {
            templateList.append('<p>Tidak ada template yang tersimpan.</p>');
            return;
        }
        
        templates.forEach(template => {
            const date = new Date(template.date).toLocaleDateString('id-ID');
            const templateItem = $(`
                <div class="template-item">
                    <span>${template.name} (${date})</span>
                    <span class="delete" data-name="${template.name}">Hapus</span>
                </div>
            `);
            
            templateItem.click(function(e) {
                if (!$(e.target).hasClass('delete')) {
                    loadTemplate(template.name);
                }
            });
            
            templateItem.find('.delete').click(function(e) {
                e.stopPropagation();
                if (confirm(`Apakah Anda yakin ingin menghapus template "${template.name}"?`)) {
                    templates = templates.filter(t => t.name !== template.name);
                    localStorage.setItem('pivotTemplates', JSON.stringify(templates));
                    loadTemplatesList();
                }
            });
            
            templateList.append(templateItem);
        });
    }
    
    // Export to CSV
    function exportToCSV() {
        if (!pivotData) return;
        
        // Get current pivot table data
        const pivotTable = $('.pvtTable')[0];
        if (!pivotTable) {
            alert('Tidak ada data pivot table untuk diekspor.');
            return;
        }
        
        let csv = [];
        
        // Get headers
        const headers = [];
        $(pivotTable).find('thead th').each(function() {
            headers.push($(this).text().trim());
        });
        csv.push(headers.join(','));
        
        // Get rows
        $(pivotTable).find('tbody tr').each(function() {
            const row = [];
            $(this).find('td').each(function() {
                row.push($(this).text().trim());
            });
            csv.push(row.join(','));
        });
        
        // Download CSV
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', `pivot_table_${new Date().toISOString().slice(0, 10)}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    // Export to Excel
    function exportToExcel() {
        if (!pivotData) return;
        
        // Create workbook
        const wb = XLSX.utils.book_new();
        
        // Add raw data sheet
        const wsData = XLSX.utils.json_to_sheet(pivotData);
        XLSX.utils.book_append_sheet(wb, wsData, 'Raw Data');
        
        // Get pivot table data
        const pivotTable = $('.pvtTable')[0];
        if (pivotTable) {
            let pivotDataArray = [];
            
            // Get headers
            const headers = [];
            $(pivotTable).find('thead th').each(function() {
                headers.push($(this).text().trim());
            });
            pivotDataArray.push(headers);
            
            // Get rows
            $(pivotTable).find('tbody tr').each(function() {
                const row = [];
                $(this).find('td').each(function() {
                    row.push($(this).text().trim());
                });
                pivotDataArray.push(row);
            });
            
            // Add pivot table sheet
            const wsPivot = XLSX.utils.aoa_to_sheet(pivotDataArray);
            XLSX.utils.book_append_sheet(wb, wsPivot, 'Pivot Table');
        }
        
        // Download Excel
        XLSX.writeFile(wb, `pivot_table_${new Date().toISOString().slice(0, 10)}.xlsx`);
    }
    
    // Export to PDF
    function exportToPDF() {
        if (!pivotData) return;
        
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        
        // Add title
        doc.setFontSize(18);
        doc.text('Laporan Pivot Table Penjualan', 14, 22);
        
        // Add date range
        doc.setFontSize(12);
        doc.text(`Periode: ${$('#start_date').val()} - ${$('#end_date').val()}`, 14, 30);
        
        // Get pivot table data
        const pivotTable = $('.pvtTable')[0];
        if (!pivotTable) {
            alert('Tidak ada data pivot table untuk diekspor.');
            return;
        }
        
        // Prepare data for PDF table
        const headers = [];
        $(pivotTable).find('thead th').each(function() {
            headers.push($(this).text().trim());
        });
        
        const data = [];
        $(pivotTable).find('tbody tr').each(function() {
            const row = [];
            $(this).find('td').each(function() {
                row.push($(this).text().trim());
            });
            data.push(row);
        });
        
        // Add table to PDF
        doc.autoTable({
            head: [headers],
            body: data,
            startY: 40,
            styles: {
                fontSize: 10,
                cellPadding: 3
            },
            headStyles: {
                fillColor: [37, 117, 252],
                textColor: 255
            }
        });
        
        // Download PDF
        doc.save(`pivot_table_${new Date().toISOString().slice(0, 10)}.pdf`);
    }
</script>
</body>
</html>