<?php
/**
 * this view generates fields for search form
 * <br/><br/>
 * @author Gabriele Droege, Patricia Kelbert (BGBM, GGBN/DNA Bank Network) <contact@dnabank-network.org>
 * @version yii 2.0.3
 * @package View
 * @var $this SearchController
 * @var $model SearchForm
 * @var $selectionLists - created in the controller
 * @var $form CActiveForm
 * @copyright Copyright © 2011 DNA Bank Network http://www.dnabank-network.org
 * <br/>The contents of this file are subject to the Mozilla Public License Version 1.1
 * @filesource
 * @license http://www.mozilla.org/MPL/ MPL
 */
use yii\helpers\Html;

use yii\web\View;
use yii\helpers\Url;


$institution = urlencode($_GET['repository']);
	
?>

<div class="jumbotron">
    <h2>Data Usage Statistics for <?php
        if($institution == "GGBN") echo "all GGBN core members";
        else echo $_GET['repository'];
    ?><br/></h2>
</div>
<div class="container">

<?php
if(isset($_GET['period'])) {
    $start = $_GET['period'];
    $end = date('Y-m', strtotime("+1 month", strtotime($start)));

    $today = date("Y-m-d");
    if ($today < $end or $today < $start) {
        echo "Report requested for a future time. Please check the <a href='".Yii::$app->request->baseUrl."/usagestats/details?repository=".$_GET['repository']."'>list of available reports</a>!";
        $QueryDate = "[]";
    }
    else {
    
    $jsonfile = file_get_contents("https://api.bgbm.org/portals/v1/ggbn/report?institution=" . $institution . "&period=" . $start);
    $json_array = json_decode($jsonfile);

    if ($json_array->result->nbRecordsPreview > 0) {
	echo "<table width='100%'><tr><td width='50%'>";
        echo "<a href='".Yii::$app->request->baseUrl."/usagestats/details?repository=".$_GET['repository']."' class='btn btn-success'>Back to report list</a></td>";
        echo "<td align='right'><a href='".Yii::$app->request->baseUrl."/usagestats/json?repository=".$_GET['repository']."&period=".$_GET['period']."' class='btn btn-success'>Get JSON</a></td></tr>";
        echo "<tr><td colspan='2'><h2>Report for " . date("F Y", strtotime($json_array->result->reportedPeriod)) . ", created on " . $json_array->result->reportCreated . "</h2></tr></table>";
        ?>

        <div class="row">
            <div class="col-xs-12 col-md-6">
                <div class="panel panel-info-blue">

                    <div class="row">
                        <div class="col-xs-3"><img style="border:none;" height="70px"
                                                   src="<?= Yii::$app->request->baseUrl ?>/images/icons/system-search.png"/>
                        </div>
                        <div class="col-xs-9 text-right">
                            <div class="huge"><?= $json_array->result->nbSearches ?></div>
                            searches retrieved data from this resource
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-md-6">
                <div class="panel panel-info-blue">

                    <div class="row">
                        <div class="col-xs-9 text-left">
                            <div class="huge"><?= $json_array->result->nbRecordsPreview ?></div>
                            records from this resource were previewed in the hitlist
                        </div>
                        <div class="col-xs-3 text-right"><img style="border:none;" height="70px"
                                                              src="<?= Yii::$app->request->baseUrl ?>/images/icons/table.png"/>
                        </div>
                    </div>
                </div>
            </div>


        </div>



        <?php

        $countryRequest = "";

        foreach ($json_array->result as $key1 => $list1) {


            // Countries
            if ($key1 == "query_countries") {  $countryRequest = true;
                echo '<div><h3>Query locations</h3>';
            //    echo "<table width='100%'><th>Country</th><th>Number of searches</th>";
                echo '<div id="mapdiv"></div>';
             //   echo '<div style="background: linear-gradient(to bottom right, #6baed6, #08306b);">1</div>';
                echo '</div>';

        ?>

                    <script>

                        $(function() {
                            var map,
                                colorscale,
                                countryTime = {};

                            $.fn.qtip.defaults.style.classes = 'ui-tooltip-bootstrap';
                            $.fn.qtip.defaults.style.def = false;
                            /*
                             * Now lets get the data
                             */
                            var countryTimeJSON = $.parseJSON('<?= json_encode($json_array->result->query_countries) ?>');
                            console.log(countryTimeJSON);
                            var countryTime = [];
                            for (var i  = 0; i<countryTimeJSON.length; i++) {
                                countryTime[countryTimeJSON[i].query_country.toUpperCase()] = { "time": countryTimeJSON[i].times};
                            }
                            console.log(countryTime);
                            /*
                             * once we have data, get the svg
                             */
                            $.get('../images/world.svg', function(svg) {
                                var div = $('#mapdiv');
                                // declare the dimensions of the map
                                var map = kartograph.map(div, 960, 500),
                                        /*
                                         * choose the color scale for the choropleth,
                                         * consult chroma.js api docs for more details
                                         */
                                    color = chroma.scale('Blues').domain(countryTimeJSON,5,'quantiles','times');
                                map.setMap(svg);
                                /*
                                 * now add the layer "world" which contains the paths for the country
                                 * boundaries, the map will appear empty till this is added
                                 */
                                map.addLayer('world', {
                                    styles: {
                                        'stroke-width': 0.7,
                                        /*
                                         * pass the color scale function to the fill and stroke attribute
                                         */
                                        fill: function(d) {
                                            return color(countryTime[d.iso2]?
                                                countryTime[d.iso2].time:
                                                0);
                                        },
                                        stroke: function(d) {
                                            return color(countryTime[d.iso2]?
                                                countryTime[d.iso2].time
                                                :0).darker();
                                        }
                                    },
                                    /*
                                     * set tooltip content
                                     */
                                    tooltips: function(d) {
                                        return [d.iso2,countryTime[d.iso2]?countryTime[d.iso2].time:0];
                                    }
                                });
                            });
                            //});
                        });

                    </script>

                <?php


            }

            // Queries over time
            // 0 values added to the date array after reading json values, otherwise graph not working properly
            // Array sorted before transformed into string

            if ($key1 == "query_dates") {
                echo '<div><h3>Queries over time</h3>';
                echo '<div class="col-lg-6" id="chart1" style="margin-top: 20px; width: 100%; height: 300px;"></div>';


                $QueryDateDateTime = [];

                $daysOfMonth = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'];

                foreach ($list1 as $key3 => $list3) {

                    $day = date("d", strtotime($list3->query_date));

                    $QueryDateTime [] = "['" . $day . "', " . $list3->times . "]";

                    $Days [] = $day; // additional array for finding the gaps

                }

                foreach ($daysOfMonth as $dayOfMonth) {

                    if (!in_array($dayOfMonth, $Days)) {
                        $QueryDateTime [] .= "['" . $dayOfMonth . "', 0]";
                    }

                }

                sort($QueryDateTime);

                $QueryDate = "[" . implode(", ", $QueryDateTime) . "]";


                echo '</div>';
            }


            // Query terms

            if ($key1 == "query_terms") {


                echo '<div><h3>Query terms</h3>';
                echo "<table id='myTable' class='tablesorter'><thead><tr><th>Query term</th><th>Number of records previewed</th><th>Number of searches</th></tr></thead><tbody>";
                foreach ($list1 as $key4 => $list4) {
                    echo "<tr><td>" . $list4->query_terms . "</td><td>" . $list4->records . "</td><td>" . $list4->times . "</td></tr>";

                }
                echo "</tbody></table>";
                echo "<div id='jumpdiv'><span id='jump'>Go to page</span> <input type='text' id='jumper'/></div><br/>";
                echo '</div>';
            }


        }

        if (!$countryRequest) echo '<div><h3>No query locations logged</h3></div>';




    } else {

        if ($onlineSince > $end . "-01") {echo "<a href='" . Yii::$app->request->baseUrl . "/usagestats/details?repository=" . $_GET['repository'] . "' class='btn btn-success'>Back to report list</a>";
        echo "<h2>Report for " . date("F Y", strtotime($_GET['period'])) . " not available for this institution. Institution started providing data on " . $onlineSince . "</h2>"; }
    else {
            if ($start < "2017-06") {echo "<a href='" . Yii::$app->request->baseUrl . "/usagestats/details?repository=" . $_GET['repository'] . "' class='btn btn-success'>Back to report list</a>";
            echo "<h2>Report for " . date("F Y", strtotime($_GET['period'])) . " not available for this institution. Reports available from June 2017 onwards.</h2>"; }

            else {
                    if ($onlineSince < $end . "-01") echo "<a href='" . Yii::$app->request->baseUrl . "/usagestats/details?repository=" . $_GET['repository'] . "' class='btn btn-success'>Back to report list</a>";
                    echo "<h2>Report for " . date("F Y", strtotime($_GET['period'])) . " not available for this institution. No queries or visits related to this institution were logged.</h2>";
                }
    }
        $QueryDate = "[]";
    }
}

}



else { $QueryDate = "[]";


if($coreTrue > 0 || $institution == "GGBN")
{ 
  echo "<a href='" . Yii::$app->request->baseUrl . "/usagestats/' class='btn btn-success'>Back to overview</a>"; 
 
  $jsonfileList = file_get_contents("https://api.bgbm.org/portals/v1/ggbn/report/list");
  $json_arrayList = json_decode($jsonfileList, true);
  
  $institution = urldecode($institution);
  $data = $json_arrayList["result"][$institution];
  $count = (isset($data)) ? $data["count"] : 'No reports avaiable for this institution.';   
  echo "<h2>There are ".$count." reports available for this institution</h2>"; 
  
  echo '<div class="row text-center">';
  arsort($data["reports"]);
  foreach($data["reports"] as $id => $reportdate){
  	echo '<p><a class="button btn-success btn-lg btn-block" href="'.yii::$app->request->baseUrl.'/usagestats/details?repository='.urlencode($institution).'&period='.$reportdate.'">'.$reportdate.'</a></p>';
  }
  echo '</div>';
 }

else { echo "<h2>This institution is not a core member.</h2>";}
}
/*foreach ($characters->query_terms as $queryterm)

{ echo $queryterm->records;} */

       ?>
    <style>
        #mapdiv {
            width: 960px;
            height: 500px;
        }

        .mapnail {
            display: inline-block;
            width: 33%;
        }
    </style>

    <script>
        $(document).ready(function() {


            //After form submit the invisible button in the pjax widget showing the shopping cart
            //is triggerd manually.
            $('#addButton').click(function(){
                $("#form").submit();
                $("#cartButton").click();
            });


            var oTable =$('#myTable').DataTable( {
                "autoWidth": false,
                "pageLength": 10,
                "order": [[0, 'asc']],
                "oLanguage": {
                    "sSearch": "Filter records:",
                },
                "paging":true,

            } );

            $(document).on( "click", '#jump',function(event) {
                var target = $(event.target);
                var page=0;
                try{page=parseInt($("#jumper").val()-1) || 0;
                }catch(e){page=0;}
                var info = oTable.page.info();
                if(page < 0)
                    page=0;
                if(page>parseInt(info.pages))
                    page=parseInt(info.pages);
                $("#jumper").val(page+1);
                oTable.page(page).draw( false );
            });

            $.jqplot.config.enablePlugins = true;
            var s1 = <?= $QueryDate;?>;
          //  var s1 = [['2', 4], ['3', 1], ['4', 7], ['5', 16], ['6', 1], ['7', 0], ['8', 15], ['9', 3], ['10', 12], ['11', 4], ['12', 1], ['13', 7], ['14', 16], ['15', 1], ['16', 8], ['17', 0], ['18', 3], ['19', 0]];
            //var s1 = [['2017-07-02', 4], ['2017-07-03', 1], ['2017-07-04', 7], ['2017-07-05', 16], ['2017-07-06', 1], ['2017-07-07', 0]];

            plot1 = $.jqplot('chart1', [s1], {
                // Only animate if we're not using excanvas (not in IE 7 or IE 8)..
             //   animate: !$.jqplot.use_excanvas,
                seriesDefaults:{
                     //seriesColors:['#31708f','#31708f','#31708f','#31708f','#31708f'],
                     renderer:$.jqplot.BarRenderer,
                     color: '#31708f',
                     pointLabels: { show: false }
                },
                axes: {
                    xaxis: {
                        renderer: $.jqplot.CategoryAxisRenderer

                    }
                }
            });

        });

    </script>



</div>