<?php
// require '../connect.php';
$dbHost = 'localhost';
$dbUser = 'dynacompqc_admindb';
$dbPass = 'qu@l!tyc';
$dbName = 'dynacompqc_quality';

class Chart
{

    public $dbC;
    public $filter;
    public $headers;

    public function __construct(array $filter)
    {
        $this->connect();
        $this->filter['monada'] = $filter[0];
        $this->filter['column'] = $filter[1];
        $this->filter['limit'] = isset($filter[2]) ? $filter[2] : 0;
        switch ($this->filter['column']) { //Set headers based on filter selection.
            case "katast_dermatos":
                $this->headers = [
                    1 => "Χρώμα θαμπό. Αδιαφανή επιλύπτουσα γλοιώδη ουσία.", 2 => "Αποχρωματισμένο & θαμπό με θολή γλοιώδης ουσία.",
                    3 => "Ζωηρό χρώμα χωρίς λάμψη. Επικαλύπτουσα γλοιώδη ουσία, ελαφρώς θολή.", 4 => "Ζωηρό και ιριδίζον χρώμα χωρίς αποχρωματισμό. Υδαρή και διαυγή επικαλύπτουσα γλοιώδη ουσία.",
                ];
                break;

            case "katast_ofthalmou":
                $this->headers = [
                    1 => "Κιτρινωπά. Γαλακτόχροα επικαλύπτουσα γλοιώδη ουσία.", 2 => "Αποχρωματισμένα με ελαφρώς θολή γλοιώδης ουσία.", 3 => "Λιγότερο χρωματισμένα. Ελαφρά ίχνη διαυγούς επικαλύπτουσας γλοιώδους ουσίας.",
                    4 => "Στίλβοντα. Άνευ βλέννας.",
                ];
                break;

            case "katast_bragxiwn":
                $this->headers = [
                    1 => "Κοίλος εις το μέσον. Κερατοειδής γαλακτόχρους, κόρη γκρίζα.", 2 => "Επίπεδος, αδιαφανής, κόρη διαφανής.", 3 => "Κυρτός ελαφρώς αποκυρτούμενος. Κερατοειδής ελαφρώς αδιαφανής, μαύρη κόρη, θαμπή.",
                    4 => "Κυρτός (bombe). Κερατοειδής διαυγής, κόρη μαύρη και στίλβουσα.",
                ];
                break;

            default:
                $this->headers = [
                    "elafra" => "Ελαφρά", "mesaia" => "Μεσσαία", "entona" => "Έντονα", "khlides" => "Κηλίδες", "stikta" => "Στικτά", "diaxuta" => "Διάχυτα", "rodina" => "Ρόδινα", "faia" => "φαιά", "mebn" => "Μ.Ε.Β.Ν.", "aimatwmata" => "Αιματώματα", "kafe" => "Καφέ",
                    "apoxrwm" => "Αποχρωματισμοί", "vlenna" => "Βλέννα", "aim_vlenna" => "Αιματηρή Βλέννα", "lampera" => "Λαμπερά", "thola" => "Θολά", "leuka" => "Λευκά", "epoulwmena" => "Επουλωμένα", "tufla" => "Τυφλά", "aimoragika" => "Αιμοραγικά", "stravo_stoma" => "Στραβό Στόμα",
                    "eksogkoma_katw" => "Εξόγκωμα Κάτω", "proekt_katw" => "Προέκταση Κάτω", "paramorf_kefali" => "Παραμορφωμένο Κεφάλι", "katheto_kefali" => "Κάθετο Κεφάλι", "papagalaki" => "Παπαγαλάκι", "vragxiokaluma" => "Βραγχιοκάλυμμα",
                    "raxitika" => "Ραχιτικά", "lordwsh" => "Λόρδωση", "kontoxontra" => "Κοντόχοντρα", "klish_ouras" => "Κλίση Ουράς", "fagwmenes_oures" => "Φαγωμένες Ουρές", "plhges_gdarmena" => "Πληγές - Γδραμένα", "pseires" => "Ψείρες", "lamanthropus" => "Lernanthropus", "" => "Κενό",
                ];
                break;
        }

    }

    /**
     * Connect to the database
     */

    private function connect()
    {
        $this->dbC = mysqli_connect($GLOBALS['dbHost'], $GLOBALS['dbUser'], $GLOBALS['dbPass'], $GLOBALS['dbName']) or die('Error Connecting to MySQL DataBase');
        mysqli_query($this->dbC, "SET NAMES 'utf8'");
        mysqli_query($this->dbC, "SET CHARACTER SET 'utf8'");
    }

    /**
     * Collect filters and return the final query
     */
    public function makeQuery()
    {
        $date = (isset($_POST['from']) && $_POST['from'] != "" ? "hm_elegxou>='{$_POST['from']}'" . (isset($_POST['to']) && $_POST['to'] != "" ? " AND hm_elegxou<='{$_POST['to']}'" : "") : (isset($_POST['to']) && $_POST['to'] != "" ? "hm_elegxou<='{$_POST['to']}'" : ""));
        $monada = (isset($_POST['monada']) && $_POST['monada'] != "" ? " monada_paxunshs='{$_POST['monada']}'" : "");
        $susk = (isset($_POST['susk']) && $_POST['susk'] != "" ? " kwd_sus='{$_POST['susk']}'" : "");
        $filter = ($date != "" ? "WHERE ${date}" . ($monada != "" ? " AND ${monada}" : "") : ($monada != "" ? "WHERE ${monada}" : ""));
        $filter = $filter != "" ? ($susk != "" ? "${filter} AND ${susk}" : $filter) : ($susk != "" ? "${filter} WHERE ${susk}" : $filter);
        return "(SELECT ar_psariwn, {$this->filter['column']} FROM control_form ${filter}) UNION (SELECT ar_psariwn, {$this->filter['column']} FROM control_form2 ${filter}) UNION (SELECT ar_psariwn, {$this->filter['column']} FROM control_form4 ${filter})";
    }

    private function gatherData()
    {
        $dataRes = mysqli_query($this->dbC, $this->makeQuery());
        // $data = mysqli_fetch_all($dataRes);
        return $dataRes;
    }

    private function getNumRows()
    {
        return mysqli_num_rows($this->gatherData());
    }

    /**
     * Get Rows and morph data into array of statistics
     */

    private function morphData()
    {
        $dataRes = $this->gatherData();
        $fishSum = 0;
        $statSum = array();
        $statHeads = array();
        $object = 0;
        //$rowData[0] => fishNum, $rowData[1] => statName
        while ($rowData = mysqli_fetch_array($dataRes)) { //Loop through returned rows
            foreach (json_decode($rowData[0]) as $fishNum) { //Loop through ar_psariwn and get sum
                $fishSum += intVal($fishNum);
            } //foreach -- $fishNum

            if (is_object(json_decode($rowData[1]))) {
                $object = 1;
                foreach (json_decode($rowData[1]) as $statName => $statArray) { //Loop through Stats by name
                    if (!in_array($this->headers[$statName], $statHeads)) {
                        array_push($statHeads, $this->headers[$statName]);
                    }
                    $statSum[array_search($this->headers[$statName], $statHeads)] = (!isset($statSum[array_search($this->headers[$statName], $statHeads)]) ? 0 : $statSum[array_search($this->headers[$statName], $statHeads)]); //Initialize array item
                    if (is_array($statArray)) {
                        foreach ($statArray as $statData) { //Loop through Stats data
                            $statSum[array_search($this->headers[$statName], $statHeads)] += $statData; //Sum the given data for each Stat
                        }
                    }
                } //foreach -- $statArray
            } else if (is_numeric(intval($rowData[1])) && intval($rowData[1]) != 0) { //if is rating, set description as headers.
                if ($rowData[1] == "" || gettype(strpos($rowData[1], "0")) != boolean) {continue;} //Do not add "0" to the headers array.
                $rowData[1] = preg_replace('~[\"\[\]]~', '', $rowData[1]); //Remove possible symbols in header.
                if (!in_array($this->headers[$rowData[1]], $statHeads)) {
                    array_push($statHeads, $this->headers[$rowData[1]]);
                }
                $statSum[array_search($this->headers[$rowData[1]], $statHeads)] = (isset($statSum[array_search($this->headers[$rowData[1]], $statHeads)]) ? $statSum[array_search($this->headers[$rowData[1]], $statHeads)] + 1 : 1);
            } else if (is_string($rowData[1])) {
                if ($rowData[1] == "" || gettype(strpos($rowData[1], "0")) != boolean) {continue;} //Do not add "0" to the headers array.
                $rowData[1] = preg_replace('~[\"\[\]]~', '', $rowData[1]); //Remove possible symbols in header.
                if (!in_array($rowData[1], $statHeads)) {
                    array_push($statHeads, $rowData[1]);
                }
                $statSum[array_search($rowData[1], $statHeads)] = (isset($statSum[array_search($rowData[1], $statHeads)]) ? $statSum[array_search($rowData[1], $statHeads)] + 1 : 1);
            }
        } //while -- $rowData
        $totals = ($object == 1 ? $fishSum : $this->getNumRows());
        $statHeads = $this->refreshHeaders($statSum, $statHeads, $totals); //Update headers with number of results.
        return ["total" => ($object == 1 ? "$fishSum Ψάρια" : $this->getNumRows() . " Κιβώτια"), "statSum" => $statSum, "Headers" => $statHeads, "query" => $this->makeQuery()];
    } //function -- morphData()

    private function refreshHeaders(array $data, array $headers, $total)
    { //refresh headers with number of results. ex ελαφρα -> ελαφρα(200)
        $temp = array();
        foreach ($data as $index => $val) {
            $percent = ($val / $total) * 100;
            if($percent < 0.01) $percent = number_format($percent, 3);
            else $percent = number_format($percent, 2);
            $temp[$index] = "{$headers[$index]} (${val} -- ${percent}%)";
        }
        return empty($headers) ? $headers : $temp;
    }

    /**
     * Return Data in readable format for debugging
     */

    public function showData()
    {
        // $this->morphData();
        print_r($this->morphData());
    }

    /**
     * Return data in JSON format, for API use.
     */

    public function getJSON()
    {
        return json_encode($this->morphData());
    }
}

$chart = new Chart([$_POST['type'], $_POST['type']]);
// $chart = new Chart(["","stat_sarkas"]);
// print_r($chart->gatherData());
echo $chart->getJSON();
// echo $chart->makeQuery();
// echo intval("");
