<?php require('classes/main.php'); ?>
<?php require('classes/adminCheck.php'); ?>
<?php require('classes/administration.php'); ?>
<!DOCTYPE html>
<html>
<?php require('common/head.php'); ?>

<body>
    <?php require('common/header.php'); ?>
    <h1>Administración - Resultados</h1>
    <?php
    $idsubject = isset($_POST['idsubject']) ? (int) $_POST['idsubject'] : 0;
    ?>
    <?php echo $main->formOpen(); ?>
    <div class="input box-radius login-form">
        <div class="form-grp">
            <div class="form-input">
                <select name="idsubject">
                    <option value="">--Seleccione especialidad--</option>
                    <?php
                    $optionsAvailable = '';
                    $optionsUnavailable = '';
                    foreach($main->subjects() as $idsubject2 => $subjects) {
                        if($main->checkUserSubject($_SESSION['iduser'], $idsubject2)) {
                            if($subjects['status'] == 0) {
                                $optionsUnavailable .= '<option value="' . $idsubject2 . '" ' . ($idsubject == $idsubject2 ? 'selected' : '') . '>' . $subjects['subject'] . '</option>';
                            } else {
                                $optionsAvailable .= '<option value="' . $idsubject2 . '" ' . ($idsubject == $idsubject2 ? 'selected' : '') . '>' . $subjects['subject'] . '</option>';
                            }
                        }
                    }
                    if($optionsAvailable != '') { ?>
                    <optgroup label="Habilitado(s)">
                        <?php echo $optionsAvailable; ?>
                    </optgroup>
                    <?php } 
                    if($optionsUnavailable != '') { ?>
                    <optgroup label="Deshabilitado(s)">
                        <?php echo $optionsUnavailable; ?>
                    </optgroup>
                    <?php } ?>
                </select>
            </div>
        </div>
        <div class="form-grp">
            <div class="form-input text-center">
                <input type="submit" class="btn btn-success" value="Cargar resultados">
            </div>
        </div>
    </div>
    <?php echo $main->formClose(); ?>
    <?php if($idsubject > 0) {
        $subjects = $main->subjects($idsubject);
        /*$sqlStepVerification['join'] = $subjects[$idsubject]['status'] == 0 ? ' JOIN usersubject ON usersubject.iduser = user.iduser ' : ' ';
        $sqlStepVerification['where'] = $subjects[$idsubject]['status'] == 0 ? ' AND usersubject.idsubject = ' . $idsubject . ' AND usersubject.stepverification = 1 ' : ' '; */
        $sqlStepVerification['join'] = ' JOIN usersubject ON usersubject.iduser = user.iduser ';
        $sqlStepVerification['where'] = ' AND usersubject.idsubject = ' . $idsubject . ' AND usersubject.stepverification = 1 '; ?>
    <div class="accordion">
        <h3>Perfil</h3>
        <div class="input box-radius login-form">
            <div class="form-grp">
                <div class="form-input">
                    <?php echo $subjects[$idsubject]['profile']; ?>
                </div>
            </div>
            <?php
                    $arr_sections = array('profilecomment_docente' , 'profilecomment_investigativo', 'profilecomment_administrativo');
                    foreach($arr_sections as $value) {
                        $text = '';
                        $sql = 'SELECT usersubjectprofilecomment.'.$value.' FROM usersubjectprofilecomment JOIN user ON user.iduser = usersubjectprofilecomment.iduser WHERE idsubject = ' . $idsubject;
                        if($consulta = $main->mysqli->query($sql)) {
                            while($resultado = $consulta->fetch_array()) {
                                $text .= '-' . $resultado[$value] . '<br /><br />';
                            }
                        } 
                        echo '<script>
                        var newNode = document.createElement("div");
                        newNode.innerHTML = "'.$text.'";
                        newNode.classList.add("profiletextarea-disabled");
                        var referenceNode = document.querySelector("#'.$value.'");
                        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
                        document.getElementById("'.$value.'").remove();
                        </script>';
                    } 
            ?>
        </div>
    </div>
    <?php
    $thprofiles = array();
    $sql = 'SELECT idprofile, profile FROM profile';
    if($consulta = $main->mysqli->query($sql)) {
        while($resultado = $consulta->fetch_array()) {
            $thprofiles[$resultado['idprofile']] = $resultado['profile'];
        }
    } ?>
    <?php foreach($main->subjectquestion($idsubject) as $idsubjectquestion => $subjectquestion) {
        $highcharts = 'highcharts' . mt_rand();
        $datatable = 'datatable' . mt_rand(); ?>
    <div class="accordion">
        <h3 accordion="true"><?php echo $subjectquestion['title']; ?></h3>
        <div>
            <div class="input box-radius login-form">
                <div class="form-grp">
                    <div class="form-input">
                        <?php
                        if($subjectquestion['type'] == 'checkbox') {
                            $tdanswer = array();
                            $sql = 'SELECT idsubjectquestionanswer, answer FROM subjectquestionanswer WHERE idsubjectquestion = ' . $idsubjectquestion;
                            if($consulta = $main->mysqli->query($sql)) {
                                while($resultado = $consulta->fetch_array()) {
                                    foreach($thprofiles as $idprofile => $profile) {
                                        $sql2 = 'SELECT usersubjectquestionanswer.idsubjectquestionanswer FROM usersubjectquestionanswer JOIN user ON user.iduser = usersubjectquestionanswer.iduser LEFT JOIN profile ON profile.idprofile = user.idprofile ' . $sqlStepVerification['join'] . ' WHERE usersubjectquestionanswer.idsubjectquestion = ' . $idsubjectquestion . ' AND usersubjectquestionanswer.idsubjectquestionanswer	 = ' . $resultado['idsubjectquestionanswer'] . ' AND profile.idprofile = ' . $idprofile . $sqlStepVerification['where'];
                                        if($consulta2 = $main->mysqli->query($sql2)) {
                                            $count = 0;
                                            while($resultado2 = $consulta2->fetch_array()) {
                                                $count++;
                                            }
                                            $tdanswer[$resultado['idsubjectquestionanswer']][$idprofile] = $count;
                                        }
                                    }
                                    $tdanswer[$resultado['idsubjectquestionanswer']]['answer'] = $resultado['answer'];
                                }
                            } ?>
                        <?php echo $subjectquestion['question']; ?>
                        <figure class="highcharts-figure">
                            <div id="<?php echo $highcharts; ?>"></div>
                        </figure>
                        <table class="table highcharts-table" id="<?php echo $datatable; ?>">
                            <thead>
                                <tr>
                                    <th>Respuesta / Perfiles<?php echo $subjectquestion['type']; ?></th>
                                    <?php
                                        $columns = 0;
                                        foreach($thprofiles as $idprofile => $profile) {
                                            $columns++; ?>
                                    <th><?php echo $profile; ?></th>
                                    <?php } ?>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($tdanswer as $idanswer => $answer) { ?>
                                <tr>
                                    <td><?php echo $answer['answer']; ?> </td>
                                    <?php 
                                        $total = 0;
                                        foreach($thprofiles as $idprofile => $profile) {
                                            $total += $answer[$idprofile]; ?>
                                    <td><?php echo $answer[$idprofile]; ?></td>
                                    <?php } ?>
                                    <td><?php echo $total; ?></td>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                        <script>
                        Highcharts.chart('<?php echo $highcharts; ?>', {
                            chart: {
                                polar: true,
                                type: 'line'
                            },
                            data: {
                                table: '<?php echo $datatable; ?>',
                                startColumn: 0,
                                endColumn: <?php echo $columns; ?>
                            },
                            title: {
                                text: '<?php echo $subjectquestion['title']; ?>',
                                x: -80
                            },
                            pane: {
                                size: '90%'
                            },
                            yAxis: {
                                gridLineInterpolation: 'polygon',
                                lineWidth: 0,
                                min: 0
                            },
                            tooltip: {
                                shared: true,
                                pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}</b><br/>'
                            },
                            legend: {
                                align: 'right',
                                verticalAlign: 'middle'
                            }
                        });
                        </script>
                        <?php } else if($subjectquestion['type'] == 'percent') {
                            $tdanswer = array();
                            $sql = 'SELECT idsubjectquestionanswer, answer FROM subjectquestionanswer WHERE idsubjectquestion = ' . $idsubjectquestion;
                            if($consulta = $main->mysqli->query($sql)) {
                                while($resultado = $consulta->fetch_array()) {
                                    foreach($thprofiles as $idprofile => $profile) {
                                        $tdanswer[$resultado['idsubjectquestionanswer']][$idprofile] = array();
                                        $sql2 = 'SELECT usersubjectquestionpercent.idsubjectquestionanswer, usersubjectquestionpercent.percent FROM usersubjectquestionpercent JOIN user ON user.iduser = usersubjectquestionpercent.iduser LEFT JOIN profile ON profile.idprofile = user.idprofile ' . $sqlStepVerification['join'] . ' WHERE usersubjectquestionpercent.idsubjectquestion = ' . $idsubjectquestion . ' AND usersubjectquestionpercent.idsubjectquestionanswer	 = ' . $resultado['idsubjectquestionanswer'] . ' AND profile.idprofile = ' . $idprofile . $sqlStepVerification['where'];
                                        if($consulta2 = $main->mysqli->query($sql2)) {
                                            $sum = 0;
                                            $cont = 0;
                                            while($resultado2 = $consulta2->fetch_array()) {
                                                $sum += $resultado2['percent'];
                                                $cont++;
                                            }
                                            $tdanswer[$resultado['idsubjectquestionanswer']][$idprofile] = $cont > 0 ? round($sum / $cont, 1) : 0;
                                        }
                                    }
                                    $tdanswer[$resultado['idsubjectquestionanswer']]['answer'] = $resultado['answer'];
                                }
                            } ?>
                            <?php echo $subjectquestion['question'] ;?>
                        <figure class="highcharts-figure">
                            <div id="<?php echo $highcharts; ?>"></div>
                        </figure>
                        <table class="table highcharts-table" id="<?php echo $datatable; ?>">
                            <thead>
                                <tr>
                                    <th>Respuesta / Perfiles<?php echo $subjectquestion['type']; ?></th>
                                    <?php
                                        $columns = 0;
                                        foreach($thprofiles as $idprofile => $profile) {
                                            $columns++; ?>
                                    <th><?php echo $profile; ?></th>
                                    <?php } ?>
                                    <th>Ponderación</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($tdanswer as $idanswer => $answer) { ?>
                                <tr>
                                    <td><?php echo $answer['answer']; ?> </td>
                                    <?php 
                                        $sumTotal = 0;
                                        $countTotal = 0;
                                        foreach($thprofiles as $idprofile => $profile) { ?>
                                    <td><?php if($answer[$idprofile] > 0) {
                                            $sumTotal += $answer[$idprofile];
                                            $countTotal++;
                                        } ?><?php echo $answer[$idprofile]; ?>
                                    </td>
                                    <?php } ?>
                                    <td><?php echo $countTotal > 0 ? round($sumTotal / $countTotal, 1) : 0; ?></td>

                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                        <script>
                        Highcharts.chart('<?php echo $highcharts; ?>', {
                            chart: {
                                polar: true,
                                type: 'line'
                            },
                            data: {
                                table: '<?php echo $datatable; ?>',
                                startColumn: 0,
                                endColumn: <?php echo $columns; ?>
                            },
                            title: {
                                text: '<?php echo $subjectquestion['title']; ?>',
                                style: {
                                    fontSize: '12px'
                                }
                            },
                            pane: {
                                size: '90%'
                            },
                            yAxis: {
                                gridLineInterpolation: 'polygon',
                                lineWidth: 0,
                                min: 0
                            },
                            tooltip: {
                                shared: true,
                                pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}</b><br/>'
                            },
                            legend: {
                                align: 'right',
                                verticalAlign: 'middle'
                            }
                        });
                        </script>
                        <?php } else if($subjectquestion['type'] == 'sort') {
                            echo $subjectquestion['question'] . '<label class="cite">(Top 5)</label>';
                            $sortArray = array();
                            $sql = 'SELECT sort FROM usersubjectquestionsort WHERE idsubjectquestion = ' . $idsubjectquestion;
                            $consulta = $main->mysqli->query($sql) or exit($this->mysqli->error);
                            while($resultado = $consulta->fetch_array()) {
                                $sort = $resultado['sort'];
                                $sortExplode = explode('|', $sort);
                                for($a=0;$a<5;$a++) {
                                    $id = $sortExplode[$a];
                                    if(isset($sortArray[$id])) {
                                        $sortArray[$id]++;
                                    } else {
                                        $sortArray[$id] = 1;
                                    }
                                }
                            }

                            $return = '';
                            $returnSortName = '';
                            $returnSortValue = '';
                            $type = 'sort';
                            if($stmt = $main->mysqli->prepare('SELECT subjectquestionanswer.idsubjectquestionanswer, subjectquestionanswer.answer, subjectquestion.type, subjectquestionanswer.readonly, subjectquestion.idsubject FROM subjectquestion LEFT JOIN subjectquestionanswer ON subjectquestion.idsubjectquestion = subjectquestionanswer.idsubjectquestion WHERE subjectquestion.idsubjectquestion = ? AND subjectquestion.type = ? ORDER BY subjectquestionanswer.sortorder, subjectquestionanswer.answer ASC')) {
                                $stmt->bind_param('is', $idsubjectquestion, $type);
                                $stmt->execute();
                                $stmt->store_result();
                                if($stmt->num_rows > 0) {
                                    $stmt->bind_result($idsubjectquestionanswer, $answer, $type, $readonly, $idsubjectdb);
                                    $cont = 0;
                                    $contSort = 0;
                                    while ($stmt->fetch()) {
                                        $cont = $cont < $idsubjectquestionanswer ? $idsubjectquestionanswer :  $cont;
                                        if($type == 'sort') {
                                            $id = 'sort_' . $idsubjectquestion . '_' . $idsubjectquestionanswer;
                                            $sort = true;
                                            $return .= '<li class="ui-state-default" id="' . $id . '" data-value="' . (isset($sortArray[$id]) ? $sortArray[$id] : 0) . '"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> ' . $answer . '</li>';
                                            $returnSortName = 'sort_' . $idsubjectquestion;
                                            $returnSortValue .= $id . '|';
                                            $sql = 'SELECT sort FROM usersubjectquestionsort WHERE iduser = ' . $_SESSION['iduser'] . ' AND idsubjectquestion = ' . $idsubjectquestion;
                                            if($consulta = $main->mysqli->query($sql)) {
                                                $resultados = $consulta->fetch_array();
                                                $returnSortValue = $resultados['sort'];
                                            }
                                        }
                                    }
                                }
                            } else {
                                $main->header('index.php', '?err=' . html_entity_decode(__LINE__ . $main->mysqli->error));
                            }
                            echo '<ul class="sortable" id="sortableVerification">' . $return . '</ul>';
                        ?>
                            <style>
                            .ui-state-default {
                                display: none;
                            }
                            .ui-state-default:nth-child(1), .ui-state-default:nth-child(2),.ui-state-default:nth-child(3),.ui-state-default:nth-child(4),.ui-state-default:nth-child(5) {
                                display: block;
                            }
                            </style>
                            <?php
                        } else if($subjectquestion['type'] == 'twobox') {
                            $tdanswer = array();
                            $sql = 'SELECT idsubjectquestionanswer, answer FROM subjectquestionanswer WHERE idsubjectquestion = ' . $idsubjectquestion;
                            if($consulta = $main->mysqli->query($sql)) {
                                while($resultado = $consulta->fetch_array()) {
                                    foreach($thprofiles as $idprofile => $profile) {
                                        $sql2 = 'SELECT usersubjectquestiontwobox.twobox FROM usersubjectquestiontwobox JOIN user ON user.iduser = usersubjectquestiontwobox.iduser LEFT JOIN profile ON profile.idprofile = user.idprofile ' . $sqlStepVerification['join'] . ' WHERE usersubjectquestiontwobox.idsubjectquestion = ' . $idsubjectquestion . ' AND usersubjectquestiontwobox.twobox LIKE "%_' . $resultado['idsubjectquestionanswer'] . '%" AND profile.idprofile = ' . $idprofile . $sqlStepVerification['where'];
                                        if($consulta2 = $main->mysqli->query($sql2)) {
                                            $count = 0;
                                            while($resultado2 = $consulta2->fetch_array()) {
                                                $count++;
                                            }
                                            $tdanswer[$resultado['idsubjectquestionanswer']][$idprofile] = $count;
                                        } else {
                                            exit($sql2);
                                        }
                                    }
                                    $tdanswer[$resultado['idsubjectquestionanswer']]['answer'] = $resultado['answer'];
                                }
                            } ?>
                            <?php echo $subjectquestion['question']; ?>
                        <figure class="highcharts-figure">
                            <div id="<?php echo $highcharts; ?>"></div>
                        </figure>
                        <table class="table highcharts-table" id="<?php echo $datatable; ?>">
                            <thead>
                                <tr>
                                    <th>Respuesta / Perfiles<?php echo $subjectquestion['type']; ?></th>
                                    <?php
                                        $columns = 0;
                                        foreach($thprofiles as $idprofile => $profile) {
                                            $columns++; ?>
                                    <th><?php echo $profile; ?></th>
                                    <?php } ?>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($tdanswer as $idanswer => $answer) { ?>
                                <tr>
                                    <td><?php echo $answer['answer']; ?> </td>
                                    <?php 
                                        $total = 0;
                                        foreach($thprofiles as $idprofile => $profile) {
                                            $total += $answer[$idprofile]; ?>
                                    <td><?php echo $answer[$idprofile]; ?></td>
                                    <?php } ?>
                                    <td><?php echo $total; ?></td>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                        <script>
                        Highcharts.chart('<?php echo $highcharts; ?>', {
                            chart: {
                                <?php if($subjectquestion['graph'] != '') { ?>
                                    type: '<?php echo $subjectquestion['graph']; ?>'
                                <?php } else { ?>
                                    polar: true,
                                    type: 'line'
                                <?php } ?>
                            },
                            data: {
                                table: '<?php echo $datatable; ?>',
                                startColumn: 0,
                                endColumn: <?php echo $columns; ?>
                            },

                            title: {
                                text: '<?php echo $subjectquestion['title']; ?>',
                                x: -80
                            },
                            pane: {
                                size: '90%'
                            },
                            yAxis: {
                                gridLineInterpolation: 'polygon',
                                lineWidth: 0,
                                min: 0
                            },
                            tooltip: {
                                shared: true,
                                pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}</b><br/>'
                            },
                            legend: {
                                align: 'right',
                                verticalAlign: 'middle'
                            }<?php if($subjectquestion['graph'] == 'bar') {  ?>
                                ,
                                plotOptions: {
                                    series: {
                                        stacking: 'normal'
                                    }
                                }
                            <?php } ?>
                        });
                        </script>
                        <?php } else if($subjectquestion['type'] == 'compare') {
                            $sql = 'SELECT idsubjectquestionanswer, answer FROM subjectquestionanswer WHERE idsubjectquestion = ' . $idsubjectquestion;
                            if($consulta = $main->mysqli->query($sql)) {
                                while($resultados = $consulta->fetch_array()) { ?>
                                    <span><?php echo $resultados['answer']; ?></span>
                                    <?php
                                    $sql2 = 'SELECT usersubjectquestioncompare.comment, profile.profile FROM usersubjectquestioncompare JOIN user ON user.iduser = usersubjectquestioncompare.iduser LEFT JOIN profile ON user.idprofile = profile.idprofile ' . $sqlStepVerification['join'] . ' WHERE usersubjectquestioncompare.idsubjectquestion = ' . $idsubjectquestion . ' AND usersubjectquestioncompare.idsubjectquestionanswer = ' . $resultados['idsubjectquestionanswer'] . $sqlStepVerification['where'];
                                    if($consulta2 = $main->mysqli->query($sql2)) {
                                        while($resultados2 = $consulta2->fetch_array()) {
                                            if($resultados2['comment'] != '') { ?>
                                                <div style="margin-left: 20px;"><?php echo $resultados2['comment']; ?></div><label class="cite"><?php echo $resultados2['profile']; ?></label><br /><br />
                                            <?php }
                                        }
                                    }
                                }
                            }
                        } ?>
                    </div>
                </div>
                <?php if($subjectquestion['type'] != 'compare') { ?>
                <div class="form-grp">
                    <div class="form-input">
                        <span>Justificación o comentario:</span><br />
                        <?php
                            $value = '';
                            $sql = 'SELECT usersubjectquestioncomment.comment, usersubjectquestioncomment.created, profile.profile FROM usersubjectquestioncomment JOIN user ON user.iduser = usersubjectquestioncomment.iduser LEFT JOIN profile ON user.idprofile = profile.idprofile ' . $sqlStepVerification['join'] . ' WHERE usersubjectquestioncomment.idsubjectquestion = ' . $idsubjectquestion . $sqlStepVerification['where'];
                            if($consulta = $main->mysqli->query($sql)) {
                                while($resultado = $consulta->fetch_array()) {
                                    if($resultado['comment'] != '') { ?>
                        <?php echo $resultado['comment']; ?><br />
                        <div class="cite">
                            <?php echo $resultado['profile'] != '' ? ' (' . $resultado['profile'] . ')' : ''; ?><br />
                            <?php echo $resultado['created']; ?></div><br />
                        <?php 
                                    }
                                }
                            } ?>
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>
    </div>
    <?php } ?>
    <?php } ?>
    <?php require('common/footer.php'); ?>
    <script>
    $(document).ready(function() {
        $("#sortableVerification li").sort(sort_li).appendTo('#sortableVerification');
        function sort_li(a, b) {
            return ($(b).data('value')) > ($(a).data('value')) ? 1 : -1;
        }
    });
    </script>
</body>

</html>