<?php
    /**
     * Fusion page file.
     *
     * Provides a class with all the properties and methods to display the page.
     *
     * @category Page
     */

    /**
     * Require dependent files if not present.
     */
    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{

        /**
         * @var \K_Fusion[] List of top-level fusions to display.
         */
        public $fusion = [];

        /**
         * @var \K_Unit[] List of top-level fuseable units (for filter).
         */
        public $products = [];


        /**
         * Constructor.
         *
         * Retrieves the data and initializes the variables.
         *
         * @param resource $db Connection to the database.
         * @global int User ID.
         */
        public function __construct($db){
            global $UID;
            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 = URL::BASE . "fusion/";
        }

        /**
         * Parses the request looking for the selected filters, validates them
         * and adds them to the $filters array.
         */
        private function parse_filters(){
            $this->filters = FILTER::FUSION;
            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 string 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 = " . $this->filters["product"] . " ";
            }
            $s = $s . "ORDER BY stars DESC;";
            return $s;
        }
    }
?>

