<?php
include_once('include/common.inc.php');
include_header('Open Gov Rankings');
$db = $server->get_db('disclosr-agencies');
?>
<div class="foundation-header">
    <h1><a href="about.php">Open Government Rankings</a></h1>
    <h4 class="subheader"></h4>
</div>
<table>
    <?php
    $agenciesdb = $server->get_db('disclosr-agencies');
    //$docsdb = $server->get_db('disclosr-documents');
    $scoredagencies = Array();
    $scores = Array();
    $columnKeys = Array();

    try {
        $rows = $agenciesdb->get_view("app", "all", null, true)->rows;


        if ($rows) {
            foreach ($rows as $row) {
                $columns = Array();
                foreach ($row->value as $key => $value) {
                    if ((strstr($key, "has") || strstr($key, "URL")) && $key != "rtkURLs") {
                        //echo "$key<br>";
                        $columns[$key] = $value;
                    }
                }
                //print_r(array_keys($columns));
                $columnKeys = array_unique(array_merge($columnKeys, array_keys($columns)));
                //print_r($columnKeys);
                $score = count($columns);
                if (isset($scores[$score])){
$scores[$score]++;
} else {
$scores[$score] =1;
}
                $scoredagencies[] = Array("id"=> $row->key, "website"=> (isset($row->value->website)?$row->value->website:""), "name" => $row->value->name, "columns" => $columns, "score" => $score);
            }
        }

    } catch (SetteeRestClientException $e) {
        setteErrorHandler($e);
    }
    function cmp($a, $b)
    {
        if ($a['score'] == $b['score']) {
            return strcmp($a['name'], $b['name']);
        }
        return ($a['score'] > $b['score']) ? -1 : 1;
    }

    usort($scoredagencies, "cmp");
    echo "<tr>";
    echo "<th>Agency Name</th>";
    echo "<th>Score</th>";
    foreach ($columnKeys as $columnID) {
        echo "<th>" . (isset($schemas['agency']["properties"][$columnID]['x-title']) ? $schemas['agency']["properties"][$columnID]['x-title'] : "<i>$columnID</i>") .  "</th>";
    }
    echo "</tr>";
    foreach ($scoredagencies as $scoredagency) {
        echo "<tr>";
        echo "<td><b><a href='getAgency.php?id=" . $scoredagency['id'] . "'>". $scoredagency['name'] . "</a></b></td>";
        echo "<td><b>" . $scoredagency['score'] . "</b></td>";
        foreach ($columnKeys as $key) {
            echo "<td style='text-align: center;'>";
            if (isset($scoredagency['columns'][$key])) {
                $value = $scoredagency['columns'][$key];
                if (is_array($value)) {
                    if (count($value) == 1) {
                        $href = $value[0];
                    } else {
                        $href = $value[0];
                    }

                } else {
                    $href = $value;
                }
                if (isset($href[0]) && $href[0] == "@") {
                    $href = str_replace("@","https://twitter.com/",$href);
                }
                //$href= urlencode($href);

                echo "<font color='lightgreen'>";

                if (strstr($href, "http")) {
                    echo "<a title='Yes' href='$href' style='color:lightgreen;'>&check;</a>";
                } else {
                    echo "&check;";
                }

                echo "</font>";
            } else {
                echo "<font color='orange'><abbr title='No'>✘</abbr></font>";
            }
            echo "</td>";
        }
        echo "</tr>\n";
    }
    ?>
</table><br>
<div id="criteria" style="width:500px;height:900px;"></div>
<div id="scores" style="width:900px;height:500px;"></div>
<script id="source">
    window.onload = function () {
        $(document).ready(function () {
            var d1 = [];
            var scorelabels = [];
            <?php
            try {
                $rows = $db->get_view("app", "scoreHas?group=true", null, true)->rows;


                $dataValues = Array();
                foreach ($rows as $row) {
                    $dataValues[$row->value] = $row->key;
                }
                $i = 0;
                ksort($dataValues);
                foreach ($dataValues as $value => $key) {

                    echo "       d1.push([$value, $i]);" . PHP_EOL;
                    echo "        scorelabels.push('$key');" . PHP_EOL;
                    $i++;
                }
            } catch (SetteeRestClientException $e) {
                setteErrorHandler($e);
            }
            ?>
            function scoretrackformatter(obj) {
                if (scorelabels[Math.floor(obj.y)]) {
                    return (scorelabels[Math.floor(obj.y)]) + "=" + obj.x;

                } else {
                    return "";
                }
            }

            function scoretickformatter(val, axis) {
                if (scorelabels[Math.floor(val)]) {
                    return (scorelabels[Math.floor(val)]) ;

                } else {
                    return "";
                }
            }

            Flotr.draw(document.getElementById("criteria"), [
                {data: d1}
            ], {
                title: 'Total count of agencies with criteria',
                HtmlText: true,
                bars: {
                    show: true,
                    horizontal: true
                },
                mouse: {
                    track: true,
                    relative: true,
                    trackFormatter: scoretrackformatter
                }, yaxis: {
                    autoscaling: true,
                    minorTickFreq: 0.6,
                    noTicks: scorelabels.length,
                    tickFormatter: scoretickformatter
                },
                xaxis: {
                    autoscaling: true

                }
            });

            var d2 = [];
            <?php
            try {

                ksort($scores);
                foreach ($scores as $key => $value) {

                    echo "       d2.push([$key,$value]);" . PHP_EOL;
                    $i++;
                }
            } catch (SetteeRestClientException $e) {
                setteErrorHandler($e);
            }
            ?>


            Flotr.draw(document.getElementById("scores"), [
                {data: d2}
            ], {
                title: 'Frequency distribution of Scores',
                HtmlText: true,
                bars: {
                    show: true
                },
                mouse: {
                    track: true,
                    relative: true
                }, yaxis: {
                    autoscaling: true
                },
                xaxis: {
                    autoscaling: true

                }
            });

        });
    };
</script>
<?php
include_footer();
?>

