<?php
//entrada dos parametro via GET (moedid/perid)
$moedid = filter_input(INPUT_GET, 'moedid', FILTER_VALIDATE_INT);
$perid = filter_input(INPUT_GET, 'perid', FILTER_VALIDATE_INT);

//montando as datas de acordo com o periodo
$data_ini = date("Y-m-d");
$data_fim = date('Y-m-d', strtotime("-{$perid} month", strtotime($data_ini)));
?>
<div class="page-bar">
    <ul class="page-breadcrumb">
        <li>
            <span>Indice</span>
        </li>
    </ul>
</div>
<br>
<div class="row">
    <div class="col-md-12">
        <form method="POST" action="javascript:filtro();" class="form-inline margin-bottom-40" role="form">
            <div class="form-group form-md-line-input">
                <select class="form-control" name="moedid" id="campo_moeda">
                    <option value="">Selecione a moeda</option>
                    <?php
                    $Read = new Read;
                    $Read->ExeRead("tp_moedas");
                    if ($Read->getResult()):
                        foreach ($Read->getResult() as $moedas):
                            extract($moedas);
                            $sel = '';
                            if (isset($moedid) && $moedid == $moeda_codigo) {
                                $sel = 'selected';
                            }
                            ?>

                            <option <?= $sel; ?> value="<?= $moeda_codigo; ?>"><?= $moeda_nome; ?></option>

                            <?php
                        endforeach;
                    endif;
                    ?>
                </select>
                <div class="form-control-focus"> </div>
            </div>
            <div class="form-group form-md-line-input has-success">
                <select class="form-control" name="perid" id="campo_periodo">
                    <option value="">Selecione o periodo</option>
                    <?php
                    $Read = new Read;
                    $Read->ExeRead("tp_periodos");
                    if ($Read->getResult()):
                        foreach ($Read->getResult() as $periodos):
                            extract($periodos);
                            $sel = '';
                            if (isset($perid) && $perid == $periodo_meses) {
                                $sel = 'selected';
                            }
                            ?>

                            <option <?= $sel; ?> value="<?= $periodo_meses; ?>"><?= $periodo_nome; ?></option>

                            <?php
                        endforeach;
                    endif;
                    ?>
                </select>
                <div class="form-control-focus"> </div>
            </div>
            <button type="button" onclick="filtro()" class="btn btn-sm btn-success table-group-action-submit"> <i class="fa fa-check"></i> Carregar</button>

        </form>
    </div>
</div>

<?php
if ($moedid == '' || $perid == ''):
    WSErro("Selecione a moeda e o periodo para consulta!", WS_INFOR);
else:
    ?>

    <?php
    ///////////// calcular média da tabela///////
    ////
    $i = 0;
    $Read->ExeRead("tp_indice", "WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC LIMIT 12", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    foreach ($Read->getResult() as $rs):
        $arrNonCommLong[$i] = $rs['NonComm_Positions_Long_All'];
        $arrNonCommShort[$i] = $rs['NonComm_Positions_Short_All'];
        $arrTotalNonComm[$i] = $rs['NonComm_Positions_Long_All'] + $rs['NonComm_Positions_Short_All'];
        $arrNetNonComm[$i] = $rs['NonComm_Positions_Long_All'] - $rs['NonComm_Positions_Short_All'];

        $arrcCommLong[$i] = $rs['Comm_Positions_Long_All'];
        $arrcCommShort[$i] = $rs['Comm_Positions_Short_All'];
        $arrTotalcComm[$i] = $rs['Comm_Positions_Long_All'] + $rs['Comm_Positions_Short_All'];
        $arrNetcComm[$i] = $rs['Comm_Positions_Long_All'] - $rs['Comm_Positions_Short_All'];
        $arrDifNet[$i] = $arrNetNonComm[$i] - $arrNetcComm[$i];
        $i++;
    endforeach;

    // calculando as médias do não comercial
    $nonLong = round(array_sum($arrNonCommLong) / count($arrNonCommLong));
    $nonShort = round(array_sum($arrNonCommShort) / count($arrNonCommShort));
    $nonTotal = round(array_sum($arrTotalNonComm) / count($arrTotalNonComm));
    $nonNet = round(array_sum($arrNetNonComm) / count($arrNetNonComm));
    // calculando as médias do comercial
    $cLong = round(array_sum($arrcCommLong) / count($arrcCommLong));
    $cShort = round(array_sum($arrcCommShort) / count($arrcCommShort));
    $cTotal = round(array_sum($arrTotalcComm) / count($arrTotalcComm));
    $cNet = round(array_sum($arrNetcComm) / count($arrNetcComm));
    $cDif = round(array_sum($arrDifNet) / count($arrDifNet));

    ////
    //////////// Fim do calculo da média ///////
    ?>

    <div class="row">
        <div class="col-md-12">
            <div id="container"></div>
        </div>
    </div>
<?php
endif;
?>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>

<!-- Additional files for the Highslide popup effect -->
<script src="https://www.highcharts.com/media/com_demo/js/highslide-full.min.js"></script>
<script src="https://www.highcharts.com/media/com_demo/js/highslide.config.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="https://www.highcharts.com/media/com_demo/css/highslide.css" />

<script>
                Highcharts.chart('container', {

                    chart: {
                        scrollablePlotArea: {
                            minWidth: 700
                        }
                    },

                    data: {
                        csvURL: 'https://cdn.rawgit.com/highcharts/highcharts/' +
                                '057b672172ccc6c08fe7dbb27fc17ebca3f5b770/samples/data/analytics.csv',
                        beforeParse: function (csv) {
                            return csv.replace(/\n\n/g, '\n');
                        }
                    },

                    title: {
                        text: 'Daily sessions at www.highcharts.com'
                    },

                    subtitle: {
                        text: 'Source: Google Analytics'
                    },

                    xAxis: {
                        tickInterval: 7 * 24 * 3600 * 1000, // one week
                        tickWidth: 0,
                        gridLineWidth: 1,
                        labels: {
                            align: 'left',
                            x: 3,
                            y: -3
                        }
                    },

                    yAxis: [{// left y axis
                            title: {
                                text: null
                            },
                            labels: {
                                align: 'left',
                                x: 3,
                                y: 16,
                                format: '{value:.,0f}'
                            },
                            showFirstLabel: false
                        }, {// right y axis
                            linkedTo: 0,
                            gridLineWidth: 0,
                            opposite: true,
                            title: {
                                text: null
                            },
                            labels: {
                                align: 'right',
                                x: -3,
                                y: 16,
                                format: '{value:.,0f}'
                            },
                            showFirstLabel: false
                        }],

                    legend: {
                        align: 'left',
                        verticalAlign: 'top',
                        borderWidth: 0
                    },

                    tooltip: {
                        shared: true,
                        crosshairs: true
                    },

                    plotOptions: {
                        series: {
                            cursor: 'pointer',
                            point: {
                                events: {
                                    click: function (e) {
                                        hs.htmlExpand(null, {
                                            pageOrigin: {
                                                x: e.pageX || e.clientX,
                                                y: e.pageY || e.clientY
                                            },
                                            headingText: this.series.name,
                                            maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x) + ':<br/> ' +
                                                    this.y + ' sessions',
                                            width: 200
                                        });
                                    }
                                }
                            },
                            marker: {
                                lineWidth: 1
                            }
                        }
                    },

                    series: [{
                            name: 'All sessions',
                            lineWidth: 4,
                            marker: {
                                radius: 4
                            }
                        }, {
                            name: 'New users'
                        }]
                });
</script>

<script>
    function filtro() {
        var moeda = $("#campo_moeda").val();
        var periodo = $("#campo_periodo").val();



        if (moeda == '') {
            console.log('moeda vazia');
        } else if (periodo == '') {
            console.log('periodo vazia');
        } else {
            window.location.href = "painel.php?exe=indice/index&moedid=" + moeda + "&perid=" + periodo;
        }
    }
</script>