<?php

    require_once($path["page"] . "Page.php");
    require_once($path["entity"] . "Fusion.php");
    require_once($path["entity"] . "K_Unit.php");


    /**
     * Fusion page model.
     */
    class Fusion_Page extends Page{

        /**
         * List of top-level {@see K_Fusion}s to display.
         */
        public $fusion = [];

        /**
         * List of top-level fuseable {@see K_Unit}s (for filter).
         */
        public $products = [];

        /**
         * The filters the page can handle.
         */
        public $filters = [
            "product" => 0,
        ];

        /**
         * Constructor.
         *
         * Retrieves the data and initializes the variables.
         *
         * @param SQLite3 $db Connection to the database.
         */
        public function __construct($db){
            global $UID;
            global $path;
            global $root;
            parent::__construct($db);
            $this->view = $path["view"] . "fusion.php";
            $this->parse_filters();
            $s =
              "SELECT DISTINCT product " .
              "FROM k_fusion " .
              "WHERE stars = 5 " .
              "ORDER BY stars DESC; ";
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->products, new K_Unit($this->db, $r["product"], false));
            }
            $s = $this->build_query();
            $q = $this->db->query($s);
            while ($r = $q->fetchArray(SQLITE3_ASSOC)){
                array_push($this->fusion, new Fusion($this->db, $r["product"], $UID));
            }
            $this->title = "Fusion - SWDB";
            $this->description = "Fusion chart";
            $this->canonical = $root . "fusion/";
        }

        /**
         * Parses the request looking for the selected filters, validates them
         * and adds them to the $filters array.
         */
        private function parse_filters(){
            if (isset($_GET["product"]) && intval($_GET["product"]) > 0){
                $this->filters["product"] = $_GET["product"];
            }
            return;
        }

        /**
         * Builds the query to the rune table using the selected or default
         * filters.
         * 
         * @return The query to be executed.
         */
        private function build_query(){
            $s =
              "SELECT DISTINCT product " .
              "FROM k_fusion " .
              "WHERE stars = 5 ";
            if ($this->filters["product"] > 0){
                $s = $s . " AND product = " . strtoupper($this->filters["product"]) . " ";
            }
            $s = $s . "ORDER BY stars DESC;";
            return $s;
        }
    }
?>
