<?php

use \yii\helpers\Html;
use \yii\helpers\Url;
use app\components\Utilities;

$this->title = 'Data of ' . $model->name;

$this->registerCssFile(\app\components\Utilities::getDataTableCssFileLink());
$this->registerJsFile('@web/js/apexcharts.js');

$encoded_view_id = json_encode($view_id);
$base_url = json_encode(Url::base(true));
$encoded_additional_data = Utilities::customJsonEncode($model->additionalData);

$script =<<< JS
    var additionalData = $encoded_additional_data;
    var matrixName = $matrix_name;
    var statisticsData = $statistics_data;

    $(document).ready(function(){
        var dataTable = initDatatable(
            $columns_names,
            $base_url + '/views/get-data?is_matrix=true&id=' + $encoded_view_id,
            additionalData
        );

        // Remove details icon from header
        if(additionalData){
            $($('#data-table').find('thead td')[1]).css('background', 'none');
        }

        // To handle open/close details
        // Details show matrix fields
        $('#data-table tbody').on('click', 'tr td.details-control', function(){
            var tr = $(this).closest('tr');
            var that = $(this);
            var row = dataTable.row(tr);
            
            if(row.child.isShown()){
                tr.removeClass('shown');
                that.removeClass('opened');
                row.child.hide();
            }
            else{
                $('#loader').show();
                $.ajax({
                    url: $base_url + '/views/get-parent-data-of-matrix-record?form_id=' + $form_id + '&id=' + that.find('a').attr('parent-id'),
                    method: 'GET',
                    success: function(response){
                        row.child(JSON.parse(response)).show();
                        tr.addClass('shown');
                        that.addClass('opened');
                        $('#loader').hide();
                    },
                    error: function(error){
                        $('#loader').hide();
                    },
                });
            }
        });

        if(statisticsData){
            for(var i = 0; i < statisticsData.length; i++){
                var containerId = 'statistics_chart_' + i;
                $('#charts').append('<div class="chart-container row" style="flex-direction: column;" id="' + containerId + '">Please wait while fetching statistics chart data ...</div>');
                if(statisticsData[i]['enternal']){
                    getChartData(statisticsData[i]['chart_data'], containerId, statisticsData[i]['label'], statisticsData[i]['type'], statisticsData[i]['enternal']);
                }
                else{
                    getChartData(statisticsData[i]['chart_data'], containerId, statisticsData[i]['label'], statisticsData[i]['type'], statisticsData[i]['enternal'], statisticsData[i]['statistics_column'], statisticsData[i]['statistics_group'], statisticsData[i]['function']);
                }
            }
        }

        function getChartData(chartData, containerId, label, type, enternal, column = null, group = null, _function = null){
            $.ajax({
                url: $base_url + '/views/get-statistics-data',
                method: 'POST',
                data: {
                    isMatrix: true,
                    matrixName: matrixName,
                    formId: $form_id,
                    chartData: chartData,
                    chartLabel: label,
                    type: type,
                    enternal: enternal,
                    column: column,
                    group: group,
                    _function: _function
                },
                success: function(response){
                    var data = JSON.parse(response);
                    console.log(data);
                    if(data['status']){
                        if(data['labels'].length == 0){
                            $('#' + containerId).html('<h4>No data found!</h4>');
                        }
                        else{
                            var options = {};
                            if(data['chart_type'] == 'Pie'){
                                options = {
                                    chart: {
                                        height: 350,
                                        type: 'pie',
                                    },
                                    labels: data['labels'],

                                    series: data['values'],
                                    dataLabels: {
                                        formatter: function(value, opts){
                                            return opts.globals.series[opts.seriesIndex];
                                        }
                                    },
                                }
                            }
                            else{
                                options = {
                                    chart: {
                                        height: 350,
                                        type: 'bar',
                                    },
                                    plotOptions: {
                                        bar: {
                                            columnWidth: '50%',
                                            distributed: true
                                        }
                                    },
                                    dataLabels: {
                                        enabled: true,
                                    },
                                    series: [{
                                        data: data['values']
                                    }],
                                    xaxis: {
                                        categories: data['labels'],
                                        labels: {
                                            style: {
                                                fontSize: '14px'
                                            }
                                        }
                                    },
                                }
                            }
                            $('#' + containerId).html('<h4>' + data['chart_label'] + '</h4>');
                            var chart = new ApexCharts(
                                document.querySelector("#" + containerId),
                                options
                            );

                            chart.render();
                        }
                    }
                },
                error: function(error){
                    
                },
            });
        }

        $('.collapse-charts').click(function(e){
            e.preventDefault();
            if($(this).text() == 'Collapse Charts'){
                $(this).text('Expand Charts');
            }
            else{
                $(this).text('Collapse Charts');
            }
            $('#charts').slideToggle(250);
        });

    });

JS;

$this->registerJs($script);

?>

<div class="view-data">

    <h1><?= $this->title ?></h1>

    <p>
        <?php if(! Yii::$app->user->identity->is_admin): ?>
            <?php if(! $model->isDefaultView): ?>
                <?= Html::a('Update', ['update', 'id' => $view_id], ['class' => 'btn btn-primary btn-expanded']) ?>
            <?php endif; ?>
        <?php else: ?>
            <?= Html::a('Update', ['update', 'id' => $view_id], ['class' => 'btn btn-primary btn-expanded']) ?>
            <?php if(count(json_decode($statistics_data)) > 0): ?>
                <?= Html::a('Collapse Charts', ['#'], ['class' => 'btn btn-purple btn-expanded collapse-charts']) ?>
            <?php endif; ?>
        <?php endif; ?>
    </p>
    
    <div id='charts'></div>

    <div class="table-responsive">

        <table class='cell-border stripe' id='data-table'>
            <thead>
                <td></td>
                <?= $model->additionalData ? '<td></td>' : '' ?>
                <?php foreach($columns as $column): ?>
                    <td><?= ucfirst($column) ?></td>
                <?php endforeach; ?>
            </thead>
            
            <tfoot>
                <tr>
                    <th></th>
                    <?= $model->additionalData ? '<th></th>' : '' ?>
                </tr>
            </tfoot>
        </table>

    </div>

</div>
