
<script>
    function loadPieChart(el_id, labelArray, dataArray, bgArray, nameChart){
      
        console.log('elem' + el_id);
        var elemName = el_id + '_var'
         elemName = document.getElementById(el_id);
       
    var myChartPie = new Chart(elemName, {
        type: 'pie',
        data: {
            labels: labelArray,
            datasets: [{
        label: nameChart,
        data: dataArray,
        backgroundColor: bgArray,
        hoverOffset: 4
    }]
        }
        
});
    }
</script>
<?
$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
$formname    = "form_mail_log_card";
$header_id = $contact_header['id'];
?>

<div id="overlaycrumb">
    <?php
    echo $translation->get("survey_details");
    ?>
    <div id="closeoverlay" onclick="disableOverlay();"></div>
</div>

<ul class="toolbar_menu">
    <?= button("back", $translation->get("back"), $formname, "loadCard('loadStats', true, '', true)"); ?>
</ul>
<div class="clearfix"></div>

<?php
if ($messages !== null) {
    if (count($messages)) {
            echo '<div id="overlayMessages">' . join("\r\n", $messages) . '</div>';
    } 
  }
?>
<?php $formname  = $formname.'survey_persons' ?>
<form id="<?= $formname ?>" name="<?= $formname ?>" method="post">
    <input name="header_id" id="header_id" type="hidden" value="<?= $header_id ?>">
    <input type="hidden" class="selected_linklist_row" name="input_line_id" value="" />
 

    <h2><?php echo $translation->get("survey_response"); ?></h2>
   
    <div class="clearfix"></div>
   

    <?
    $query  = "SELECT DISTINCT sp.id,  sp.name AS 'Name', sp.email FROM survey_persons as sp INNER JOIN survey_answers as sa on sp.id = sa.spid WHERE sp.header_id = '" . $header_id . "' ORDER BY sp.id DESC";
    $format = array('option', 'text', 'text', 'text', 'boolean');
 
    if ($result = @mysqli_query($GLOBALS['mysql_con'], $query)) {
        linklist($result, $formname, $format, "input_line_id", "show_person_mail", FALSE, "update_sortorder_contactform");
    }
    ?>

</form>
<div>
<?php $formname  = 'survey_persons_filter' ?>
<form id="<?= $formname ?>" name="<?= $formname ?>" method="post" >
    <input name="header_id" id="input_id" type="hidden" value="<?= $header_id ?>">
    <input name="input_form" id="input_form" type="hidden" value="<?= $formname ?>">
    <div class="dashboard-right dashboard-100">
        <h2><?php echo $translation->get("filter"); ?></h2>
        <? input($translation->get("select_date"), "reportrange", "text", '', 200) ?>
        <div class="label"><label><?= $translation->get('select_option');?></label></div>
        <div class="input">
            <select class="bigselect" name="select_option" id="select_option">
                <option disabled selected>----</option>
        </div>
        <?php 
            $queryOpt = "SELECT * FROM contactform_line WHERE header_id = '".$header_id."'";
            $resultOpt = @mysqli_query($GLOBALS['mysql_con'], $queryOpt);
            while($row = @mysqli_fetch_array($resultOpt)){
                echo '<option value="'. $row['id'].'" data-type="'. $row['typ'].'" >'.$row['name'].'</option>';
            }
            
        ?>
        </select>
        <div id="suboption"></div>
        <div>
                <?= button("submit", $translation->get("apply_filter"), $formname, ""); ?>
        </div>
    </div>
<?php $sql = "SELECT MONTH(created_date) as month, count(*) NUM  FROM survey_answers WHERE header_id = '" . $header_id . "' GROUP BY month ";
$label = array(); 
$dataArrayPie = array();
$bgArray = array();
for($i = 1;$i<=12;$i++){
    $dataArrayPie[$i] = 0;
    $first = rand(0, 255);
    $second = rand(0, 255);
    $third = rand(0, 255);
    $color = 'rgb('.$first.', '.$second.', '.$third.')';
    array_push($bgArray, $color);
}

$result =  @mysqli_query($GLOBALS['mysql_con'], $sql);

while($row = @mysqli_fetch_array($result)){
    $dataArrayPie[$row['month']] = $row['NUM'];
    
}
     
?>
    <div class="lineChart">
        <canvas id="pieCharts"></canvas>
    </div>
</div>

 
<div class="dashboard-100">
        <div class="log-wrapper dashboard-100">
            <div class="log-content-wrapper">
            <div class="log-title"><?php echo $translation->get('question_chart'); ?> </div>
            <div class="log-content charts">
                <?php 
                $bgArray = array();
                $queryRow = '';
                $cfid = $header_id;
                $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 = '" . $header_id . "'  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, (strlen($row['name']) >20 ) ? substr($row['name'], 0, 30).'...' : $row['name']);
                        $first = rand(0, 255);
                        $second = rand(0, 255);
                        $third = rand(0, 255);
                        $dataArray[$row['id']] = 0;
                        $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'];
                            
                            
                        } 
                        

                        
                    }
                } 
                     
                ?>
            <canvas class="custom_form" id="ccChart" width="400" height="400"></canvas>
                <script>
                     var labelArray = [
                            <?php echo '"'.implode('","', $label).'"' ?>
                    ];
                    var dataArray  = [
                        <?php echo '"'.implode('","', $dataArray).'"' ?>
                    ];
                    var bgArray = [
                            <?php echo '"'.implode('","', $bgArray).'"' ?>
                    ];
                    loadPieChart("ccChart", labelArray, dataArray, bgArray, '<?= $translation->get('question_chart');?>')
                </script>
               
            </div>
            </div>
        </div>
    </div>
    
    <div class="dashboard-100">
        <div class="log-wrapper dashboard-100">
            <div class="log-content-wrapper">
            <div class="log-title"><?php echo $translation->get('option_chart'); ?> </div>
            <div class="log-content charts">
                <?php 
                
                $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 = '" . $header_id . "' AND (cl.typ = 10 or cl.typ = 4)  ORDER BY cl.sorting ASC";
               
                $result =  @mysqli_query($GLOBALS['mysql_con'], $queryRow);
              
                if(@mysqli_num_rows($result) > 0){
                    while($row = @mysqli_fetch_array($result)){
                    ?>
                    <div class="log-title"><?php echo $row['name']; ?> </div>
                    <?    
                        $bgArrayIN = array();
                        $queryRow = '';
                        $cfid = $header_id;
                        $labelIN = array(); 
                        $dataArrayIN = array();

                        $queryOpt = "SELECT  *  FROM  contactform_line_option WHERE line_id = '".$row['id']."'  ORDER BY id ASC";
                        
                        $resultOpt =  @mysqli_query($GLOBALS['mysql_con'], $queryOpt);

                        while($rowOpt = @mysqli_fetch_array($resultOpt)){
                            
                        
                        $cfid = $row['header_id'];
                        array_push($labelIN, (strlen($rowOpt['option_string']) >20 ) ? substr($rowOpt['option_string'], 0, 30).'...' : $rowOpt['option_string']);
                        $dataArrayIN[$rowOpt['id']] = 0;
                        $first = rand(0, 255);
                        $second = rand(0, 255);
                        $third = rand(0, 255);
                        $color = 'rgb('.$first.', '.$second.', '.$third.')';
                        array_push($bgArrayIN, $color);
                        $queryData = 'SELECT line_id, count(*) as NUMCOUNT FROM survey_answers WHERE header_id = '.$row['header_id'].' AND line_id = "'.$row['id'].'" AND clo_id = "'.$rowOpt['id'].'" ORDER BY line_id';
                         
                        $resultData =  @mysqli_query($GLOBALS['mysql_con'], $queryData);
                        // 
                        if(@mysqli_num_rows($resultData) > 0){
                            $rowData = @mysqli_fetch_array($resultData);
                            $dataArrayIN[$rowOpt['id']] = $rowData['NUMCOUNT'];
                            
                            
                        } 
                        }
                        
                     ?>
                     <canvas class="custom_form" id="ccChart2<?= $row['id']?>" width="400" height="400"></canvas>
                    <script>
                        var labelArray = [
                                <?php echo '"'.implode('","', $labelIN).'"' ?>
                        ];
                        var dataArray  = [
                            <?php echo '"'.implode('","', $dataArrayIN).'"' ?>
                        ];
                        var bgArray = [
                                <?php echo '"'.implode('","', $bgArrayIN).'"' ?>
                        ];
                        console.log('label ezut' + labelArray);
                        console.log('arr ezut' + dataArray);
                        console.log('bg ezut' + bgArray);
                        loadPieChart("ccChart2<?= $row['id']?>", labelArray, dataArray, bgArray, '<?= $translation->get('option_chart');?>')
                    </script>   

                        
                <?  $dataArrayIN = array(); $labelIN = array(); $bgArrayIN = array();
                }
                } 
                     
                ?>
             
            </div>
            </div>
        </div>
    </div>
</form>

<script>
    
    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 ctxs = document.getElementById('pieCharts');
    var labelArray = getMonths({count: 12});
     
        var dataArray  = [
            <?php echo '"'.implode('","', $dataArrayPie).'"' ?>
        ];
        var bgArray = [
            <?php echo '"'.implode('","', $bgArray).'"' ?>
        ];
        console.log('dataArray pie' + "<?= implode('","', $dataArrayPie);?>");
        var data = {
            labels: labelArray,
            datasets: [{
                label: '<?= $translation->get('survey_monthly')?>',
                data: dataArray,
                backgroundColor: bgArray,
                fill: false,
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }]
};        
var myChartBar = new Chart(ctxs, {
    type: 'line',
    data: data,
   
     
});
 

</script>


 <script>
         
        $(document).ready( function () {
             
            const picker = new easepick.create({
    element: "#reportrange",
    css: [
        "https://cdn.jsdelivr.net/npm/@easepick/bundle@1.2.0/dist/index.css"
    ],
    zIndex: 10,
    lang: "de-DE",
    locale:"DE",
    readonly: false,
    autoApply: false,
    format: "MM/DD/YY",
    PresetPlugin: {
        position: "right"
    },
    plugins: [
        "RangePlugin",
        "PresetPlugin"
    ]
})
 
 
        });
  $('body').on('change', '#select_option', function(){
    var line_id = $(this).children('option:selected').val();
    var type = $(this).children('option:selected').attr('data-type');
    var header_id = $('#input_id').val();
    if(type == 4 || type == 9 || type == 10){
        $.ajax({
                type:'POST',
                url:'?action=load_suboption',
                data: {line_id:line_id,header_id:header_id},
                success:function(result){
                    
                    $('#suboption').html(result);
                }
             });  
    }else{
        $('#suboption').html('');
    }
  });     
  $('body').on('click', '.button_submit', function(){
    var formName = $(this).attr('data-formname');
    $.ajax({
                type:'POST',
                url:'?action=load_filtered_data',
                 
                data: $('form#'+formName).serialize(),
                success:function(result){
                    var obj = JSON.parse(result);
                         
                    var dataArray = [];
              
                for(var i in obj)
                    dataArray.push(obj[i]);
                    
                    console.log(dataArray);        
                    myChartBar.destroy();
                    
                    console.log();
                    var data = {
                    labels: labelArray,
                    datasets: [{
                        label: '<?= $translation->get('survey_monthly')?>',
                        data: dataArray,
                        backgroundColor: bgArray,
                        fill: false,
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                };  
                    myChartBar = new Chart(ctxs, {
                        type: 'line',
                        data: data,
                    
                        
                    });
                }
             }); 
  }) 
// Date Range End]
</script>