<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/init.inc"; global $title; global $isLoggedIn; global $lang; global $pages;
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/header.inc';

if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/stats.json")) file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/stats.json", "{}");

$cache = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/stats.json"), true);

?>

<script src="/assets/editor/chart.js"></script>

<br>
<div class="container">
    <div id="page-content">
        <h2>Statistics</h2>
        <?php

        if (!isset($cache["content"]) || date('Y-m-d') !== $cache["day"]): ob_start();

        $switchesRaindrops = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/gdapd/switches.json"), true);
        $switchesCloudburst = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/ynmuc/switches.json"), true);

        $weeks = [];
        $weeksRectified = [];

        $lastWeek = 0;
        foreach ($switchesRaindrops as $switch) {
            $week = date('YW', strtotime($switch["timestamp"]));
            if ($lastWeek === 0) $lastWeek = $week;

            if (!isset($weeks[$week])) $weeks[$week] = [
                "cloudburst" => 0,
                "raindrops" => 0,
                "total" => 0,
                "end" => strtotime($switch["timestamp"]),
                "start" => null
            ];

            if ($week !== $lastWeek) {
                if (isset($weeks[$lastWeek])) {
                    $weeks[$lastWeek]["start"] = strtotime($switch["timestamp"]);
                    $lastWeek = $week;
                }
            }

            $weeks[$week]["raindrops"]++;
            $weeks[$week]["total"]++;
        }

        $lastWeek = 0;
        foreach ($switchesCloudburst as $switch) {
            $week = date('YW', strtotime($switch["timestamp"]));
            if ($lastWeek === 0) $lastWeek = $week;

            if (!isset($weeks[$week])) $weeks[$week] = [
                "cloudburst" => 0,
                "raindrops" => 0,
                "total" => 0,
                "end" => strtotime($switch["timestamp"]),
                "start" => null
            ];

            if ($week !== $lastWeek) {
                if (isset($weeks[$lastWeek])) {
                    $weeks[$lastWeek]["start"] = strtotime($switch["timestamp"]);
                    $lastWeek = $week;
                }
            }

            $weeks[$week]["cloudburst"]++;
            $weeks[$week]["total"]++;
        }

        $index = 0;
        foreach ($weeks as $id => $week) {
            if ($index >= 20) continue;
            $weeksRectified[$id] = $week;
            $index++;
        }

        $weeksRectified = array_filter(array_reverse($weeksRectified), function ($i) {
            return $i["start"] > 1651363200;
        });

        $members = [];
        $frontersMonth = [];

        $fronts = [];
        $lastFrontIDs = [];

        foreach (array_reverse($switchesRaindrops) as $switch) {
            foreach ($lastFrontIDs as $frontID) {
                $fronts[$frontID]["end"] = strtotime($switch["timestamp"]);
            }
            $lastFrontIDs = [];

            $index = 0; foreach ($switch["members"] as $member) {
                if (strtotime($switch["timestamp"]) - (time() - 86400*30) < 0) continue;
                $fronts[$switch["id"] . ":" . $index] = [
                    "member" => $member,
                    "start" => strtotime($switch["timestamp"]),
                    "end" => strtotime(date('c')),
                    "duration" => null
                ];
                $lastFrontIDs[] = $switch["id"] . ":" . $index;
            } $index++;
        }

        foreach ($fronts as $id => $front) {
            $fronts[$id]["duration"] = $front["end"] - $front["start"];

            if (!($front["start"] - (time() - 86400*30) < 0)) {
                if (!isset($members[$front["member"]])) $members[$front["member"]] = [
                    "time" => 0,
                    "name" => getMemberWithoutSystem($front["member"])["display_name"],
                    "color" => getMemberWithoutSystem($front["member"])["color"],
                ];
                $members[$front["member"]]["time"] += $fronts[$id]["duration"];
            }
        }

        foreach ($fronts as $front) {
            if (!isset($frontersMonth[date('Y-m', $front["start"])])) $frontersMonth[date('Y-m', $front["start"])] = [];
            if (!isset($frontersMonth[date('Y-m', $front["start"])][$front["member"]])) $frontersMonth[date('Y-m', $front["start"])][$front["member"]] = 0;
            $frontersMonth[date('Y-m', $front["start"])][$front["member"]] += $front["duration"];
        }

        $fronts = [];
        $lastFrontIDs = [];

        foreach (array_reverse($switchesCloudburst) as $switch) {
            foreach ($lastFrontIDs as $frontID) {
                $fronts[$frontID]["end"] = strtotime($switch["timestamp"]);
            }
            $lastFrontIDs = [];

            $index = 0; foreach ($switch["members"] as $member) {
                $fronts[$switch["id"] . ":" . $index] = [
                    "member" => $member,
                    "start" => strtotime($switch["timestamp"]),
                    "end" => strtotime(date('c')),
                    "duration" => null
                ];
                $lastFrontIDs[] = $switch["id"] . ":" . $index;
            } $index++;
        }

        foreach ($fronts as $id => $front) {
            $fronts[$id]["duration"] = $front["end"] - $front["start"];

            if (!($front["start"] - (time() - 86400*30) < 0)) {
                if (!isset($members[$front["member"]])) $members[$front["member"]] = [
                    "time" => 0,
                    "name" => getMemberWithoutSystem($front["member"])["display_name"],
                    "color" => getMemberWithoutSystem($front["member"])["color"],
                ];
                $members[$front["member"]]["time"] += $fronts[$id]["duration"];
            }
        }

        foreach ($fronts as $front) {
            if (!isset($frontersMonth[date('Y-m', $front["start"])])) $frontersMonth[date('Y-m', $front["start"])] = [];
            if (!isset($frontersMonth[date('Y-m', $front["start"])][$front["member"]])) $frontersMonth[date('Y-m', $front["start"])][$front["member"]] = 0;
            $frontersMonth[date('Y-m', $front["start"])][$front["member"]] += $front["duration"];
        }

        $fronts = array_reverse($fronts);
        uasort($members, function ($a, $b) {
            return $b["time"] - $a["time"];
        });

        $frontersMonthRectified = [];
        foreach ($frontersMonth as $monthID => $month) {
            $thisMonth = [];

            foreach ($month as $id => $time) {
                $thisMonth[$id] = [
                    "duration" => $time,
                    "name" => getMemberWithoutSystem($id)["display_name"],
                    "color" => getMemberWithoutSystem($id)["color"]
                ];
            }

            $frontersMonthRectified[$monthID] = $thisMonth;
        }

        uasort($frontersMonthRectified, function ($a, $b) use ($frontersMonthRectified) {
            return strtotime(array_search($a, $frontersMonthRectified) . "-01") - strtotime(array_search($b, $frontersMonthRectified) . "-01");
        });

        $frontersMonthMembers = [];
        foreach ($frontersMonthRectified as $month => $fronters) {
            foreach ($fronters as $fronter => $data) {
                foreach (scoreOrderGlobal() as $member) {
                    if (!isset($frontersMonthMembers[$member["id"]])) $frontersMonthMembers[$member["id"]] = [];
                }
            }

            foreach ($frontersMonthMembers as $key => $member) {
                $frontersMonthMembers[$key][$month] = $frontersMonthRectified[$month][$key] ?? [
                    "duration" => 0
                ];
            }
        }

        ?>

        <h3>Switches per week</h3>
        <canvas id="graph-00" style="width: 100%; height: 300px; max-height: 100%;"></canvas>
        <script>
            const ctx0 = document.getElementById('graph-00').getContext('2d');
            window.chart00 = [
                {
                    label: "Raindrops System",
                    data: JSON.parse(`<?= json_encode(array_map(function ($i) {
                        return $i["raindrops"];
                    }, array_values($weeksRectified))) ?>`),
                    borderColor: "#e598ff"
                },
                {
                    label: "Cloudburst System",
                    data: JSON.parse(`<?= json_encode(array_map(function ($i) {
                        return $i["cloudburst"];
                    }, array_values($weeksRectified))) ?>`),
                    borderColor: "#98e0ff"
                },
                {
                    label: "All systems",
                    data: JSON.parse(`<?= json_encode(array_map(function ($i) {
                        return $i["total"];
                    }, array_values($weeksRectified))) ?>`),
                    borderColor: "rgba(160,255,153,0.5)",
                    borderDash: [5]
                }
            ];
            const graph0 = new Chart(ctx0, {
                type: 'line',
                data: {
                    labels: JSON.parse(`<?= json_encode(array_map(function ($i) {
                        return date("M d", $i["start"]) . " to " . date("M d", $i["end"]);
                    }, array_values($weeksRectified))) ?>`),
                    datasets: window.chart00
                },
                options: {
                    animation: {
                        duration: 0
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: "rgba(255,255,255,0.25)"
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            intersect: false
                        }
                    }
                }
            });
        </script>

        <h3 style="margin-top: 15px;">Average switches per day of the week</h3>
        <canvas id="graph-01" style="width: 100%; height: 300px; max-height: 100%;"></canvas>
        <?php

        $switchesDaysRaindrops = [0, 0, 0, 0, 0, 0, 0];
        $amountDaysRaindrops = [0, 0, 0, 0, 0, 0, 0];
        $switchDoWRaindrops = [0, 0, 0, 0, 0, 0, 0];
        $daysRaindrops = [];

        $switchesDaysCloudburst = [0, 0, 0, 0, 0, 0, 0];
        $amountDaysCloudburst = [0, 0, 0, 0, 0, 0, 0];
        $switchDoWCloudburst = [0, 0, 0, 0, 0, 0, 0];
        $daysCloudburst = [];

        foreach ($switchesCloudburst as $switch) {
            if (!in_array(date("Y-m-d", strtotime($switch["timestamp"])), $daysCloudburst)) {
                $daysCloudburst[] = date("Y-m-d", strtotime($switch["timestamp"]));
                $amountDaysCloudburst[(int)date('N', strtotime($switch["timestamp"])) - 1]++;
            }

            $switchesDaysCloudburst[(int)date('N', strtotime($switch["timestamp"])) - 1]++;
        }

        $switchDoWCloudburst = [
            $switchesDaysCloudburst[0] / $amountDaysCloudburst[0],
            $switchesDaysCloudburst[1] / $amountDaysCloudburst[1],
            $switchesDaysCloudburst[2] / $amountDaysCloudburst[2],
            $switchesDaysCloudburst[3] / $amountDaysCloudburst[3],
            $switchesDaysCloudburst[4] / $amountDaysCloudburst[4],
            $switchesDaysCloudburst[5] / $amountDaysCloudburst[5],
            $switchesDaysCloudburst[6] / $amountDaysCloudburst[6]
        ];

        foreach ($switchesRaindrops as $switch) {
            if (!in_array(date("Y-m-d", strtotime($switch["timestamp"])), $daysRaindrops)) {
                $daysRaindrops[] = date("Y-m-d", strtotime($switch["timestamp"]));
                $amountDaysRaindrops[(int)date('N', strtotime($switch["timestamp"])) - 1]++;
            }

            $switchesDaysRaindrops[(int)date('N', strtotime($switch["timestamp"])) - 1]++;
        }

        $switchDoWRaindrops = [
            $switchesDaysRaindrops[0] / $amountDaysRaindrops[0],
            $switchesDaysRaindrops[1] / $amountDaysRaindrops[1],
            $switchesDaysRaindrops[2] / $amountDaysRaindrops[2],
            $switchesDaysRaindrops[3] / $amountDaysRaindrops[3],
            $switchesDaysRaindrops[4] / $amountDaysRaindrops[4],
            $switchesDaysRaindrops[5] / $amountDaysRaindrops[5],
            $switchesDaysRaindrops[6] / $amountDaysRaindrops[6]
        ];

        $switchDoW = [
            $switchDoWCloudburst[0] + $switchDoWRaindrops[0],
            $switchDoWCloudburst[1] + $switchDoWRaindrops[1],
            $switchDoWCloudburst[2] + $switchDoWRaindrops[2],
            $switchDoWCloudburst[3] + $switchDoWRaindrops[3],
            $switchDoWCloudburst[4] + $switchDoWRaindrops[4],
            $switchDoWCloudburst[5] + $switchDoWRaindrops[5],
            $switchDoWCloudburst[6] + $switchDoWRaindrops[6]
        ];

        ?>
        <script>
            const ctx1 = document.getElementById('graph-01').getContext('2d');
            window.chart01 = [
                {
                    label: "Switches per week",
                    data: JSON.parse(`<?= json_encode($switchDoW) ?>`),
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(255, 159, 64, 0.2)',
                        'rgba(255, 205, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(201, 203, 207, 0.2)'
                    ],
                    borderColor: [
                        'rgb(255, 99, 132)',
                        'rgb(255, 159, 64)',
                        'rgb(255, 205, 86)',
                        'rgb(75, 192, 192)',
                        'rgb(54, 162, 235)',
                        'rgb(153, 102, 255)',
                        'rgb(201, 203, 207)'
                    ],
                    borderWidth: 1
                }
            ];
            const graph1 = new Chart(ctx1, {
                type: 'bar',
                data: {
                    labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
                    datasets: window.chart01
                },
                options: {
                    animation: {
                        duration: 0
                    },
                    scales: {
                        y: {
                            grid: {
                                color: "rgba(255,255,255,0.25)"
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            intersect: false
                        }
                    }
                }
            });
        </script>

        <h3 style="margin-top: 15px;">Switches per hour of the day</h3>
        <canvas id="graph-02" style="width: 100%; height: 300px; max-height: 100%;"></canvas>
        <?php

        $switchHoursRaindrops = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        $switchHoursCloudburst = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

        foreach ($switchesCloudburst as $switch) {
            $switchHoursCloudburst[(int)date('G', strtotime($switch["timestamp"]))]++;
        }

        foreach ($switchesRaindrops as $switch) {
            $switchHoursRaindrops[(int)date('G', strtotime($switch["timestamp"]))]++;
        }

        $switchHours = [
            $switchHoursRaindrops[0] + $switchHoursCloudburst[0],
            $switchHoursRaindrops[1] + $switchHoursCloudburst[1],
            $switchHoursRaindrops[2] + $switchHoursCloudburst[2],
            $switchHoursRaindrops[3] + $switchHoursCloudburst[3],
            $switchHoursRaindrops[4] + $switchHoursCloudburst[4],
            $switchHoursRaindrops[5] + $switchHoursCloudburst[5],
            $switchHoursRaindrops[6] + $switchHoursCloudburst[6],
            $switchHoursRaindrops[7] + $switchHoursCloudburst[7],
            $switchHoursRaindrops[8] + $switchHoursCloudburst[8],
            $switchHoursRaindrops[9] + $switchHoursCloudburst[9],
            $switchHoursRaindrops[10] + $switchHoursCloudburst[10],
            $switchHoursRaindrops[11] + $switchHoursCloudburst[11],
            $switchHoursRaindrops[12] + $switchHoursCloudburst[12],
            $switchHoursRaindrops[13] + $switchHoursCloudburst[13],
            $switchHoursRaindrops[14] + $switchHoursCloudburst[14],
            $switchHoursRaindrops[15] + $switchHoursCloudburst[15],
            $switchHoursRaindrops[16] + $switchHoursCloudburst[16],
            $switchHoursRaindrops[17] + $switchHoursCloudburst[17],
            $switchHoursRaindrops[18] + $switchHoursCloudburst[18],
            $switchHoursRaindrops[19] + $switchHoursCloudburst[19],
            $switchHoursRaindrops[20] + $switchHoursCloudburst[20],
            $switchHoursRaindrops[21] + $switchHoursCloudburst[21],
            $switchHoursRaindrops[22] + $switchHoursCloudburst[22],
            $switchHoursRaindrops[23] + $switchHoursCloudburst[23],
        ];

        ?>
        <script>
            const ctx2 = document.getElementById('graph-02').getContext('2d');
            window.chart02 = [
                {
                    label: "Switches per hour of day",
                    data: JSON.parse(`<?= json_encode($switchHours) ?>`),
                    borderColor: "rgb(160,255,153)"
                }
            ];
            const graph2 = new Chart(ctx2, {
                type: 'line',
                data: {
                    labels: [
                        "12am",
                        "1am",
                        "2am",
                        "3am",
                        "4am",
                        "5am",
                        "6am",
                        "7am",
                        "8am",
                        "9am",
                        "10am",
                        "11am",
                        "12pm",
                        "1pm",
                        "2pm",
                        "3pm",
                        "4pm",
                        "5pm",
                        "6pm",
                        "7pm",
                        "8pm",
                        "9pm",
                        "10pm",
                        "11pm"
                    ],
                    datasets: window.chart02
                },
                options: {
                    animation: {
                        duration: 0
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: "rgba(255,255,255,0.25)"
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            intersect: false
                        }
                    }
                }
            });
        </script>
        <?php $cache["content"] = ob_get_contents(); $cache["day"] = date('Y-m-d'); ob_end_clean(); endif;

        echo($cache["content"]);
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/stats.json", json_encode($cache));

        ?>
    </div>
</div>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/footer.inc'; ?>