<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Modal;

$this->title = Yii::t('app', 'Trainees In Branches Report');

$this->registerCssFile('@web/css/apexcharts.css');
$this->registerJsFile('@web/js/apexcharts.js');

$data   = json_encode(array_values($data));
$branches = json_encode(array_values($branches));

$url = json_encode(Url::to(['/reports/export-trainees-in-branches-within-dates-report']));
$download_url = json_encode(Url::to(['/reports/download-file']));

$script = <<< JS

var data = $data;
var branches = $branches;

var options = {
        series: [{
            data: data,
        }],
        chart: {
            type: 'bar',
            height: 350,
            toolbar: {
                show: false
            },
        },
        plotOptions: {
            bar: {
                distributed: true
            },
        },
        dataLabels: {
            enabled: true
        },
        legend: {
            show: false
        },
        xaxis: {
            categories: branches,
            labels: {
                style: {
                }
            },
        },
    };

var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();

var ajax_url = $url;
var download_url = $download_url;

$('#export-btn').click(function(e){
    e.preventDefault();
    $.ajax({
        method: 'POST',
        url: ajax_url,
        data: {
            data: data,
            branches: branches
        },
        success: function(response){
            console.log(response);
            window.location = download_url + '?link=' + response;
        }
    });
});

JS;

$this->registerJs($script);

?>

<div class="trainees-in-branches-within-dates-report">
    <h1><?= $this->title ?></h1>
    <?= Html::a(Yii::t('app', 'Advanced Search'), 
        ['#'], 
        [
            'class' => 'btn btn-purple btn-expanded advanced-search-btn',
            'value' => Url::to(['advanced-search-for-trainees-in-branches', 'from_date' => isset($_GET['from_date']) ? $_GET['from_date'] : null, 'to_date' => isset($_GET['to_date']) ? $_GET['to_date'] : null]),
            'title' => Yii::t('app', 'Advanced Search')
        ]) ?>

    <?= Html::a(Yii::t('app', 'Export'), ['#'], ['class' => 'btn btn-primary btn-expanded', 'id' => 'export-btn']) ?>
    
    <br><br>

    <?php if(Yii::$app->session->hasFlash('wrong_selected_dates')): ?>
        <div class="alert alert-danger">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
            <?= Yii::$app->session->getFlash('wrong_selected_dates') ?>
        </div>
    <?php endif; ?>

    <div class="container">
        <div id="chart"></div>
    </div>

</div>

<?php 
    Modal::begin([
        'header' => '<h3>' . \Yii::t('app', 'Advanced Search') . '</h3>',
        'id' => 'advanced-search-modal',
        'size' => 'modal-md'
    ]);

    echo '<div id="advanced-search-modal-content"></div>';

    Modal::end();
?>