<style>
    #wpLapor {
        min-width: 600px;
        max-width: auto;
        height: 600px;
        margin: 0 auto;
    }

    #wpLaporTable {
        width: 100% !important;
    }

    #wpLaporTable th, #wpLaporTable td {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    #wpLaporTable td.dt-body-right {
        text-align: right;
    }
</style>
<?php

ini_set('memory_limit', '4096M');

echo 'Initial memory usage: ' . memory_get_usage() . ' bytes' . PHP_EOL;

$tahun2 = date('Y');
$rentang_tahun = range($tahun2, 2022);

$kanwilData = [];
foreach ($raporlpr as $row) {
    $y = (($row->WPLPR / $row->JMLWP ?: 0)) * 100;
    $kanwilData[] = [
        'y' => $y,
        'name' => addslashes($row->NAMA),
        'drilldown' => (string)$row->KWLADM,
        'jmlwp' => $row->JMLWP,
        'wplpr' => $row->WPLPR
    ];
}

// Sort the data by the 'y' value in descending order
usort($kanwilData, function ($a, $b) {
    return $b['y'] <=> $a['y'];
});

// Convert the sorted array to a JSON string
$dataraporkwl = json_encode($kanwilData);

$drilldownSeries = [];

// Prepare KPP drilldown
foreach ($raporlpr as $kanwil) {
    $kppData = [];
    foreach ($raporlprkpp as $kpp) {
        if ($kpp->KWLADM == $kanwil->KWLADM) {
            $kppData[] = [
                'name' => $kpp->NAMA,
                'y' => ($kpp->WPLPR / ($kpp->JMLWP ?: 1)) * 100,
                'drilldown' => (string)$kpp->KPPADM,
                'jmlwp' => $kpp->JMLWP,
                'wplpr' => $kpp->WPLPR
            ];
        }
    }

    // Sort the KPP data by the 'y' value in descending order
    usort($kppData, function ($a, $b) {
        return $b['y'] <=> $a['y'];
    });

    $drilldownSeries[] = [
        'id' => (string)$kanwil->KWLADM,
        'name' => "KPP in " . $kanwil->NAMA,
        'data' => $kppData
    ];
}

// Prepare Seksi drilldown
foreach ($raporlprkpp as $kpp) {
    $sieData = [];
    foreach ($raporlprsie as $sie) {
        if ($sie->KPPADM == $kpp->KPPADM) {
            $sieData[] = [
                'name' => $sie->NAMA,
                'y' => ($sie->WPLPR / ($sie->JMLWP ?: 1)) * 100,
                'drilldown' => (string)($kpp->KPPADM . '_' . $sie->KODESIE),
                'jmlwp' => $sie->JMLWP,
                'wplpr' => $sie->WPLPR
            ];
        }
    }

    // Sort the Seksi data by the 'y' value in descending order
    usort($sieData, function ($a, $b) {
        return $b['y'] <=> $a['y'];
    });

    $drilldownSeries[] = [
        'id' => (string)$kpp->KPPADM,
        'name' => "Seksi in " . $kpp->NAMA,
        'data' => $sieData
    ];
}

// Prepare Pegawai drilldown (if available)
if (isset($raporlprpeg)) {
    foreach ($raporlprsie as $sie) {
        $pegData = [];
        foreach ($raporlprpeg as $peg) {
            if ($peg->KPPADM == $sie->KPPADM && $peg->KODESIE == $sie->KODESIE) {
                $pegData[] = [
                    'name' => $peg->NAMA,
                    'y' => ($peg->WPLPR / ($peg->JMLWP ?: 1)) * 100,
                    'jmlwp' => $peg->JMLWP,
                    'wplpr' => $peg->WPLPR
                ];
            }
        }

        // Sort the Pegawai data by the 'y' value in descending order
        usort($pegData, function ($a, $b) {
            return $b['y'] <=> $a['y'];
        });

        $drilldownSeries[] = [
            'id' => (string)($sie->KPPADM . '_' . $sie->KODESIE),
            'name' => "Pegawai in " . $sie->NAMA,
            'data' => $pegData
        ];
    }
}

?>
<div class="main-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-12 mb-2">
                <form class="form-inline" action="<?php base_url('rapor/wplapor') ?>" method="post">
                    <label class="my-1 mr-2">Tahun Pajak:</label>
                    <select class="custom-select my-1 mr-sm-2" id="tahun" name="tahun">
                        <?php
                        foreach ($rentang_tahun as $tahun) {
                            if ($tahun == $tahunx) {
                                $sel = "selected";
                            } else {
                                $sel = "";
                            }
                            echo "<option value=\"" . $tahun . "\" " . $sel . ">" . $tahun . "</option>";
                        }
                        ?>
                    </select>

                    <button type="submit" class="btn btn-primary my-1">Proses</button>
                </form>
            </div>
        </div>
        <div class="row clearfix">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="text-center">WP Lapor</h3>
                        <div class="card-header-right">
                            <ul class="list-unstyled card-option">
                                <li><i class="ik ik-chevron-left action-toggle"></i></li>
                                <li><i class="ik ik-minus minimize-card"></i></li>
                                <li><i class="ik ik-x close-card"></i></li>
                            </ul>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="wpLapor" style="height:600px"></div>
                    </div>
                    <div class="card-body">
                        <table class="table table-hover table-striped table-bordered tablesorter" id="wpLaporTable">
                            <thead class='thead-dark'>
                            <tr class="table-active">
                                <th class="text-center">No</th>
                                <th class="text-center">Unit</th>
                                <th class="text-center">Persentase WP Lapor</th>
                                <th class="text-center">Jumlah WP</th>
                                <th class="text-center">WP Lapor</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                            $no = 1;
                            $totalJmlWP = 0;
                            $totalWPLapor = 0;
                            foreach ($kanwilData as $row) {
                                $totalJmlWP += $row['jmlwp'];
                                $totalWPLapor += $row['wplpr'];
                                ?>
                                <tr>
                                    <td><?= $no++ ?></td>
                                    <td><?= $row['name'] ?></td>
                                    <td class="text-right"><?= number_format($row['y'], 2) ?>%</td>
                                    <td class="text-right"><?= number_format($row['jmlwp'], 0, ',', '.') ?></td>
                                    <td class="text-right"><?= number_format($row['wplpr'], 0, ',', '.') ?></td>
                                </tr>
                            <?php } ?>
                            </tbody>
                            <tfoot class='thead-dark'>
                            <tr>
                                <th colspan="2" class="text-center">Total</th>
                                <th class="text-right">
                                    <?= number_format(($totalWPLapor / ($totalJmlWP ?: 1)) * 100, 2) ?>
                                    %
                                </th>
                                <th class="text-right"><?= number_format($totalJmlWP, 0, ',', '.') ?></th>
                                <th class="text-right"><?= number_format($totalWPLapor, 0, ',', '.') ?></th>
                            </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>

<?php echo view('inc/js.php') ?>

<script>
    var wpLaporTable = $('#wpLaporTable').DataTable({
        "order": [[2, "desc"]],
        "columnDefs": [
            {
                "searchable": false,
                "orderable": false,
                "targets": 0,
                "width": "5%",
                "className": "dt-body-right"
            },
            {
                "targets": 1,
                "width": "30%"
            },
            {
                "type": "formatted-num",
                "targets": [2],
                "width": "20%",
                "className": "dt-body-right",
                "render": function (data, type, row) {
                    if (type === 'sort') {
                        return parseFloat(data.replace(/[\.%,]/g, ''));
                    }
                    return data;
                }
            },
            {
                "type": "formatted-num",
                "targets": [3, 4],
                "width": "20%",
                "className": "dt-body-right",
                "render": function (data, type, row) {
                    if (type === 'sort') {
                        return parseFloat(data.replace(/[\.%,]/g, ''));
                    }
                    if (type === 'display') {
                        return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
                    }
                    return data;
                }
            }
        ],
        "language": {
            "decimal": ",",
            "thousands": "."
        },
        "lengthChange": false,
        "pageLength": -1,
        "searching": false,
        "info": false,
        "autoWidth": false,
        "responsive": true
    });

    function updateWpLaporTable(data) {
        wpLaporTable.clear();
        data.forEach(function (point, index) {
            var percentage = (point.wplpr / (point.jmlwp || 1)) * 100;
            wpLaporTable.row.add([
                index + 1,
                point.name,
                percentage.toFixed(2) + '%',
                point.jmlwp,
                point.wplpr
            ]);
        });
        wpLaporTable.draw();
        wpLaporTable.columns.adjust().responsive.recalc();
    }

    function updateWpLaporTableFromChart(chart) {
        var currentSeries = chart.series[0];
        var data = currentSeries.options.data;
        updateWpLaporTable(data);
    }

    Highcharts.chart('wpLapor', {
        chart: {
            type: 'column',
            events: {
                drilldown: function (e) {
                    var chart = this;
                    setTimeout(function () {
                        updateWpLaporTableFromChart(chart);
                    }, 100);
                },
                drillup: function () {
                    var chart = this;
                    setTimeout(function () {
                        updateWpLaporTableFromChart(chart);
                    }, 100);
                }
            }
        },
        title: {
            text: '%WP Lapor'
        },
        subtitle: {
            text: 'Klik untuk melihat detail per KPP'
        },
        xAxis: {
            type: 'category'
        },
        yAxis: {
            title: {
                text: '%WP Lapor SPT Tahunan/Jumlah WP Terdaftar'
            }
        },
        legend: {
            enabled: false
        },
        credits: {
            enabled: false
        },
        plotOptions: {
            series: {
                borderWidth: 0,
                dataLabels: {
                    enabled: true,
                    format: '{point.y:.1f}%'
                }
            }
        },
        accessibility: {
            point: {
                valueDescriptionFormat: '{index}. {point.name}, WPbayar: {point.x}%, WPBayarT: {point.y}%, index: {point.z}%.'
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> dari total<br>Jumlah WP: <b>{point.jmlwp}</b><br>WP Lapor: <b>{point.wplpr}</b><br/>'
        },
        series: [{
            name: 'Kanwil',
            colorByPoint: true,
            data: <?php echo $dataraporkwl; ?>
        }],
        drilldown: {
            series: <?php echo json_encode($drilldownSeries); ?>
        }
    });

    // Initial table update
    updateWpLaporTableFromChart(Highcharts.charts[Highcharts.charts.length - 1]);

    // Adjust table columns on window resize
    $(window).on('resize', function () {
        wpLaporTable.columns.adjust().responsive.recalc();
    });
</script>