<?
$messages    = array();
$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
$filter = (isset($_REQUEST['filter']) ? $_REQUEST['filter'] : "");

$action = (isset($_GET['action']) ? $_GET['action'] : "");

if ($action != "" && $action != "admin_login") {
    require_once(CMS_PATH . "admin/mail_log.inc.php");
    exit();
}

?>
<? $formname = "form_stat"; ?>
<script type="text/javascript">
    function filter_collection() {
        var formname = '#<?=$formname."response";?>';
        jQuery(formname + ' .requestLoader').show();

        var filter = jQuery('#collection_filter').val();

        jQuery(formname).attr("action", "?filter=" + filter).submit();

        return;

        var formData = {
            filter_id: jQuery('#collection_filter').val(),
        };

        jQuery('#spid').val(jQuery('#collection_filter').val());
        $.ajax({
                   url    : "?action=filter_collection",
                   type   : 'POST',
                   data   : formData,
                   success: function ( output, status, xhr ) {
                       if (xhr.getResponseHeader('REQUIRES_AUTH') == 1) {
                           window.location.replace("/mysyde/");
                       } else {
                           jQuery(formname + ' .requestLoader').hide();
                           jQuery('#page_linklist').html(output);

                           initForm();
                           initLinklist();
                       }
                   }
               });
    }
</script>
<div id="mainContent">
    <?php echo current_website_language($site, $language); ?>
    <h1><?php echo get_translation('top_statistic'); ?></h1>

    <?php
if ($messages !== null) {
    if (count($messages)) {
            echo '<div id="overlayMessages">' . join("\r\n", $messages) . '</div>';
    } 
  }

    ?>

   

    <!-- <form id="<?= $formname ?>" name="<?= $formname ?>" method="post" action="?action=filter">
        <input type="hidden" class="selected_linklist_row" name="input_id" value="" />

        <div class="requestLoader"></div>
        <?

        $where = 'where send_date >= DATE_SUB(NOW(),INTERVAL 7 DAY)';

        $query  = "SELECT id, subject AS '" . $translation->get("subject") . "', DATE_FORMAT(send_date,'%d.%m.%Y um %H:%i Uhr') AS '" . $translation->get("send_on") . "', to_adress AS '" . $translation->get("recipient_email") . "', from_adress AS '" . $translation->get("sender_email") . "' FROM main_mail_log " . $where . " ORDER BY send_date DESC";
        $format = array('option', 'text', 'text', 'text', 'text');
        if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
            linklist($result, $formname, $format, "input_id", "card");
        }
        ?>

    </form> -->
    <!-- content -->
    <div class="dashboard-wrapper">
        <div class="dashboard_left">
            <div class="dashboad-left-wrapper">
                <div class="dashboard-padding">
                    <div class="dashboard-100 teaser border position-relative" style="height:160px;">
                        <div class="dashboard-left-content-statistics">               
                        <div class="link-wrapper" >
                            <div class="dashboard-100 shortlink link-collection position-relative">
                                <div class="card-wrapper dashboard-100 " style="margin-top:40px;">
                                    <div class="card-content dashboard-100">
                                    <div class="log-title"><?php echo get_translation('left_survey_contactforms_last'); ?> </div>
                                    <form id="<?= $formname.'response' ?>" name="<?= $formname .'response'?>" method="post" action="?action=filter">
                                    <div class="input">
                                        <select id="collection_filter" name="collection_filter" class="bigselect" onchange="filter_collection();">
                                        <option value=""> ----</option>
                                           <?php $query = "SELECT * FROM contactform_header WHERE is_survey = 1";
                                                $result =  @mysqli_query($GLOBALS['mysql_con'], $query);
                                                if(@mysqli_num_rows($result) > 0){
                                                    while($row = @mysqli_fetch_array($result)){
                                            ?>
                                                <option value="<?=$row['id']?>"   <?php echo ($filter == $row['id'] ? 'selected="selected"' : ""); ?>><?php echo $row['description'] ?></option>
                                                <?php } } ?>   
                                        </select>
                                    </div>
                                        <input id="spid" name="input_id" type="hidden" value="">
                                         
                                        <div class="requestLoader"></div>
                                        
                                         
                                        <div class="clearfix"></div>
                                         <div id="page_linklist">                   
                                        <?
                                        $where = " WHERE cf.is_survey = 1 ";
                                        if($filter != ""){
                                            $where = " AND  cf.id =".$filter;
                                        }

                                        $query  = "SELECT DISTINCT sp.id, cf.description  AS '" . $translation->get("type") . "',  sp.name AS 'Name', sp.email FROM contactform_header as cf  INNER JOIN survey_persons as sp  on sp.header_id = cf.id INNER JOIN survey_answers as sa on sp.id = sa.spid " .$where."  ORDER BY sp.id DESC";
                      
                                        $format = array('option', 'text', 'text', 'text', 'boolean');
                                    
                                        if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
                                            linklist($result, $formname.'response', $format, "input_line_id", "edit_line_contactform", FALSE, "update_sortorder_contactform");
                                        }
                                        ?>
                                        </div>
                                    </form>
                                    
                                    </div>
                                </div>
                            </div>
                            <!-- Mail protocol -->
                            <!-- Mail protocol end -->
                        </div>
                        </div>
                            
                        
                         
                    </div>
                </div>
            </div>
        </div>

        <div class="dashboard_right">
            <div class="dashboard-right-wrapper dashboard-100">
                <div class="dashboard-padding dashboard-100">
                    
                    <div class="dashboard-100">
                        <div class="log-wrapper dashboard-100">
                            <div class="log-content-wrapper">
                            <div class="log-title"><?php echo get_translation('left_survey_contactforms'); ?> </div>
                            <div class="log-content-statistics">
                                
                                <?php 
                                $bgArray = array();
                                $queryRow = '';
                                $cfid = '';
                                $dataset = array();
                                if($filter != ''){
                                    ?>
                                    <canvas id="myChart"></canvas>
                                    <?
                                    $cfid = $filter;
                                    $queryRow = "SELECT  cl.id, cl.header_id,cl.name  FROM  contactform_line as cl INNER JOIN contactform_header as ch on cl.header_id = ch.id WHERE ch.is_survey = 1 AND header_id = '" . $filter . "'  ORDER BY cl.sorting ASC";
                                    $label = array(); 
                                    $dataArray = array();
                                    $result =  @mysqli_query($GLOBALS['mysql_con'], $queryRow);
                                    if(@mysqli_num_rows($result) > 0){
                                        while($row = @mysqli_fetch_array($result)){
                                            $cfid = $row['header_id'];
                                            array_push($label, substr($row['name'], 0, 10).'...');
                                            $first = rand(0, 255);
                                            $second = rand(0, 255);
                                            $third = rand(0, 255);
                                            $color = 'rgb('.$first.', '.$second.', '.$third.')';
                                            array_push($bgArray, $color);
                                            $queryData = 'SELECT line_id, count(*) as NUMCOUNT FROM survey_answers WHERE header_id = '.$row['header_id'].' AND line_id = "'.$row['id'].'" ORDER BY option_string';
                                            $resultData =  @mysqli_query($GLOBALS['mysql_con'], $queryData);
                                            // 
                                            if(@mysqli_num_rows($resultData)){
                                                $rowData = @mysqli_fetch_array($resultData);
                                                $dataArray[$row['id']] = $rowData['NUMCOUNT'];
                                                
                                                
                                            } 
                                            

                                            
                                        }
                                    } 
                                
                                }else{
                                    
                                    $querySet = "SELECT * FROM contactform_header WHERE is_survey = 1 ORDER BY ID ASC";
                                    $resultSet =  @mysqli_query($GLOBALS['mysql_con'], $querySet);
                                    if(@mysqli_num_rows($resultSet) > 0){
                                        $date1 = date('Y').'-01-01';
                                        $date2 = date('Y').'-'.date('m-d');
                                        while($rowSet = @mysqli_fetch_array($resultSet)){
                                            // $dataset[$rowSet['id']]['name'] = $rowSet['description'];
                                            for($i = 1;$i<=12;$i++){
                                                $dataset[$rowSet['id']][$i] = 0;
                                                 
                                            }
                                            $queryPerson = "SELECT MONTH(created_date) as month, count(*) NUM FROM survey_persons WHERE DATE(created_date) BETWEEN '".$date1."' AND '".$date2."'  AND  header_id = '".$rowSet['id']."'  GROUP BY month ";
                                            $resultPerson =   @mysqli_query($GLOBALS['mysql_con'], $queryPerson);
                                            while($rowPerson = @mysqli_fetch_array($resultPerson)){
                                                $dataset[$rowSet['id']][$row['month']] = $row['NUM'];
                                            }

                                            
                                        } 
                                    }
                                    if(!empty($dataset)){?>
                                        <canvas id="myChartLine"></canvas>
                                    <?php }  
                                     
                                }
                             ?>

                               
                            </div>
                            </div>
                        </div>
                    </div>
                    <!-- Show Surveys list -->
                        <div class="dashboard-right-wrapper dashboard-100">
                                        <div class="dashboard-padding dashboard-100">
                                            
                                            <div class="dashboard-100">
                                                <div class="log-wrapper dashboard-100">
                                                    <div class="log-content-wrapper">
                                                    <div class="log-title"><?php echo get_translation('left_survey_contactforms'); ?> </div>
                                                    <div class="log-content" style="height:auto;">
                                                        <!-- table -->
                                                        <form id="<?= $formname.'surveys' ?>" name="<?= $formname .'surveys'?>" method="post" action="?action=filter">
                                                            
                                                                <input id="spid" name="input_id" type="hidden" value="">
                                                                <input type="hidde" name="header_id" id="header_id" value="">
                                                                <div class="requestLoader"></div>
                                                                
                                                                
                                                                <div class="clearfix"></div>
                                                                <div id="page_linklist_surveys">                   
                                                                <?
                                                                
                                                                $query  = "SELECT 
                                                                    id,
                                                                    description AS '" . $translation->get("description") . "',
		                                                            from_unixtime(modified_date, '%d.%m.%Y %H:%i:%s') AS '" . $translation->get("changed_on") . "' 
                                                                 FROM contactform_header WHERE is_survey = 1";
                                                                
                                                                $format = array('option', 'text', 'text', 'text', 'boolean');

                                                                if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
                                                                    linklist($result, $formname.'survey', $format, "header_id", "show_survey_contactform", FALSE, "update_sortorder_contactform");
                                                                }
                                                                ?>
                                                                </div>
                                                            </form>
                                                        <!-- table end -->
                                                    </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                            <!-- Survey list end -->
                </div>
            </div>
        </div>
        
    <!-- Content end -->
    <div class="clearfix"></div>
   
</div>
 
<script>
    
        const ctx = document.getElementById('myChart');
        var labelArray = [
                <?php echo '"'.implode('","', $label).'"' ?>
            ];
            var dataArray  = [
                <?php echo '"'.implode('","', $dataArray).'"' ?>
            ];
            var bgArray = [
                <?php echo '"'.implode('","', $bgArray).'"' ?>
            ];
            console.log('dataArray are' + "<?= implode('","', $dataArray);?>");
    const myChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: labelArray,
            datasets: [{
        label: 'My First Dataset',
        data: dataArray,
        backgroundColor: bgArray,
        hoverOffset: 4
    }]
        }
        
    });

    const MONTHS = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
];

 function getMonths(config) {
    var cfg = config || {};
    var count = cfg.count || 12;
    var section = cfg.section;
    var values = [];
    var i, value;

    for (i = 0; i < count; ++i) {
        value = MONTHS[Math.ceil(i) % 12];
        values.push(value.substring(0, section));
    }

    return values;
}
    const DATA_COUNT = 7;
const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100};
function getnumbers(config) {
    var cfg = config || {};
    var min = valueOrDefault(cfg.min, 0);
    var max = valueOrDefault(cfg.max, 100);
    var from = valueOrDefault(cfg.from, []);
    var count = valueOrDefault(cfg.count, 8);
    var decimals = valueOrDefault(cfg.decimals, 8);
    var continuity = valueOrDefault(cfg.continuity, 1);
    var dfactor = Math.pow(10, decimals) || 0;
    var data = [];
    var i, value;

    for (i = 0; i < count; ++i) {
        value = (from[i] || 0) + this.rand(min, max);
        if (this.rand() <= continuity) {
            data.push(Math.round(dfactor * value) / dfactor);
        } else {
            data.push(null);
        }
    }

    return data;
}
var CHART_COLORSS = {
    red: 'rgb(255, 99, 132)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgb(255, 205, 86)',
    green: 'rgb(75, 192, 192)',
    blue: 'rgb(54, 162, 235)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgb(201, 203, 207)'
};
var dataArraySet  = [
            <?php echo '"'.implode('","', $dataset[30]).'"' ?>
        ];
        function transparentize(value, opacity) {
    var alpha = opacity === undefined ? 0.5 : 1 - opacity;
    return colorLib(value).alpha(alpha).rgbString();
}     
aDatasets1 = [0,0,0,0,0,0,15, 1,0,0,0,0];  
aDatasets2 = [20,30,40,50,60,20,25, 1,2,3,4, 5];
aDatasets3 = [30,20,25,65,90,34,20, 5,4,3,2,1];
var ctxLine = document.getElementById("myChartLine");
var myChartLine = new Chart(ctxLine, {
    type: 'bar',
    data: {
        labels: getMonths({count: 12}),
        
        datasets: [ {
              label: 'Result',
              fill:false,
            data: aDatasets1,
            backgroundColor: '#E91E63',
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(255,99,132,1)',
                'rgba(255,99,132,1)',
                'rgba(255,99,132,1)',
                'rgba(255,99,132,1)',
                'rgba(255,99,132,1)',
            ],
            borderWidth: 1
        }
        
        
        ]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        title: {
            display: true,
            text: 'Nishi IT Institute'
        },
        responsive: true,
        
       tooltips: {
            callbacks: {
                labelColor: function(tooltipItem, chart) {
                    return {
                        borderColor: 'rgb(255, 0, 20)',
                        backgroundColor: 'rgb(255,20, 0)'
                    }
                }
            }
        },
        legend: {
            labels: {
                // This more specific font property overrides the global property
                fontColor: 'red',
               
            }
        }
    }
});   
// const labels = getMonths({count: 12});
//     var ctxLine = document.getElementById('myChartLine').getContext("2d");;
//     const data = {
//     labels: labels,
//     datasets: [
//         {
//         label: 'Dataset 1',
//         data: dataArraySet,
//         borderColor: CHART_COLORSS.red,
//         backgroundColor: [
//             'rgba(255, 99, 132, 0.2)',
//             'rgba(255, 159, 64, 0.2)',
//             'rgba(255, 205, 86, 0.2)',
//             'rgba(75, 192, 192, 0.2)',
//             'rgba(54, 162, 235, 0.2)',
//             'rgba(153, 102, 255, 0.2)',
//             'rgba(221, 203, 207, 0.2)', 
//             'rgba(231, 203, 207, 0.2)',
//             'rgba(201, 203, 207, 0.2)',
//             'rgba(21, 203, 207, 0.2)',
//             'rgba(23, 203, 207, 0.2)',
//             'rgba(233, 203, 207, 0.2)',
            
//             ],
//         } 
//     ]
// };
//     var myChartLine = new Chart(ctxLine, {
//         type: 'bar',
//         data: data,
//         options: {
//             responsive: true,
//             plugins: {
//             legend: {
//                 position: 'top',
//             },
//             title: {
//                 display: true,
//                 text: 'Chart.js Bar Chart'
//             }
//             }
//         }
        
//     });
    
$('.dashboard-100').css('display', 'contents');
</script>